Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add NonZeroUuid type for optimized Option<Uuid> representation #779

Merged
merged 4 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/external/arbitrary_support.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{std::convert::TryInto, Builder, Uuid};
use crate::{non_nil::NonNilUuid, std::convert::TryInto, Builder, Uuid};

use arbitrary::{Arbitrary, Unstructured};

Expand All @@ -16,6 +16,18 @@ impl Arbitrary<'_> for Uuid {
(16, Some(16))
}
}
impl arbitrary::Arbitrary<'_> for NonNilUuid {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let uuid = Uuid::arbitrary(u)?;

// Generated `Uuid`s are never nil since we set version/variant bits
Ok(NonNilUuid::from(uuid))
}

fn size_hint(_: usize) -> (usize, Option<usize>) {
(16, Some(16))
}
}

#[cfg(test)]
mod tests {
Expand All @@ -42,4 +54,16 @@ mod tests {

assert!(uuid.is_err());
}

#[test]
fn test_arbitrary_non_nil() {
let mut bytes = Unstructured::new(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);

let non_nil_uuid = NonNilUuid::arbitrary(&mut bytes).unwrap();
let uuid: Uuid = non_nil_uuid.into();

assert_eq!(Some(Version::Random), uuid.get_version());
assert_eq!(Variant::RFC4122, uuid.get_variant());
assert!(!uuid.is_nil());
}
}
37 changes: 37 additions & 0 deletions src/external/serde_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use crate::{
error::*,
fmt::{Braced, Hyphenated, Simple, Urn},
non_nil::NonNilUuid,
std::fmt,
Uuid,
};
Expand All @@ -30,6 +31,15 @@ impl Serialize for Uuid {
}
}

impl Serialize for NonNilUuid {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Uuid::from(*self).serialize(serializer)
}
}

impl Serialize for Hyphenated {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.encode_lower(&mut Uuid::encode_buffer()))
Expand Down Expand Up @@ -127,6 +137,16 @@ impl<'de> Deserialize<'de> for Uuid {
}
}

impl<'de> Deserialize<'de> for NonNilUuid {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let uuid = Uuid::deserialize(deserializer)?;
Ok(NonNilUuid::from(uuid))
}
}

enum ExpectedFormat {
Simple,
Braced,
Expand Down Expand Up @@ -732,4 +752,21 @@ mod serde_tests {
"UUID parsing failed: invalid length: expected 16 bytes, found 11",
);
}

#[test]
fn test_serialize_non_nil_uuid() {
let uuid_str = "f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4";
let uuid = Uuid::parse_str(uuid_str).unwrap();
let non_nil_uuid = NonNilUuid::from(uuid);

serde_test::assert_ser_tokens(&non_nil_uuid.readable(), &[Token::Str(uuid_str)]);
}
#[test]
fn test_deserialize_non_nil_uuid() {
let uuid_str = "f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4";
let uuid = Uuid::parse_str(uuid_str).unwrap();
let non_nil_uuid = NonNilUuid::from(uuid);

serde_test::assert_de_tokens(&non_nil_uuid.readable(), &[Token::Str(uuid_str)]);
}
}
13 changes: 12 additions & 1 deletion src/external/slog_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::Uuid;
use crate::{non_nil::NonNilUuid, Uuid};

impl slog::Value for Uuid {
fn serialize(
Expand All @@ -22,6 +22,17 @@ impl slog::Value for Uuid {
}
}

impl slog::Value for NonNilUuid {
fn serialize(
&self,
record: &slog::Record<'_>,
key: slog::Key,
serializer: &mut dyn slog::Serializer,
) -> Result<(), slog::Error> {
Uuid::from(*self).serialize(record, key, serializer)
}
}

#[cfg(test)]
mod tests {
use crate::tests::new;
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,13 +223,14 @@ extern crate std;
extern crate core as std;

#[cfg(all(uuid_unstable, feature = "zerocopy"))]
use zerocopy::{IntoBytes, FromBytes, Immutable, KnownLayout, Unaligned};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};

mod builder;
mod error;
mod parser;

pub mod fmt;
pub mod non_nil;
pub mod timestamp;

pub use timestamp::{context::NoContext, ClockSequence, Timestamp};
Expand Down
84 changes: 84 additions & 0 deletions src/non_nil.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! A wrapper type for nil UUIDs that provides a more memory-efficient
//! `Option<NonNilUuid>` representation.

use std::{fmt, num::NonZeroU128};

use crate::Uuid;

/// A UUID that is guaranteed not to be the nil UUID.
///
/// This is useful for representing optional UUIDs more efficiently, as `Option<NonNilUuid>`
/// takes up the same space as `Uuid`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct NonNilUuid(NonZeroU128);
KodrAus marked this conversation as resolved.
Show resolved Hide resolved

impl fmt::Display for NonNilUuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", Uuid::from(*self))
}
}

impl From<NonNilUuid> for Uuid {
/// Converts a [`NonNilUuid`] back into a [`Uuid`].
///
/// # Examples
/// ```
/// use uuid::{non_nil::NonNilUuid, Uuid};
///
/// let uuid = Uuid::from_u128(0x0123456789abcdef0123456789abcdef);
/// let non_nil = NonNilUuid::from(uuid);
/// let uuid_again = Uuid::from(non_nil);
///
/// assert_eq!(uuid, uuid_again);
/// ```
fn from(non_nil: NonNilUuid) -> Self {
Uuid::from_u128(non_nil.0.get())
}
}

impl From<Uuid> for NonNilUuid {
KodrAus marked this conversation as resolved.
Show resolved Hide resolved
/// Converts a [`Uuid`] into a [`NonNilUuid`].
///
/// # Panics
/// Panics if the input UUID is nil (all zeros).
///
/// # Examples
/// ```
/// use uuid::{non_nil::NonNilUuid, Uuid};
///
/// let uuid = Uuid::from_u128(0x0123456789abcdef0123456789abcdef);
/// let non_nil = NonNilUuid::from(uuid);
/// ```
fn from(uuid: Uuid) -> Self {
NonZeroU128::new(uuid.as_u128())
.map(Self)
.expect("Attempted to convert nil Uuid to NonNilUuid")
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_nonzero_uuid_option_size() {
assert_eq!(
std::mem::size_of::<Option<NonNilUuid>>(),
std::mem::size_of::<Uuid>()
);
}

#[test]
fn test_new_with_non_nil() {
let uuid = Uuid::from_u128(0x0123456789abcdef0123456789abcdef);
let nn_uuid = NonNilUuid::from(uuid);
assert_eq!(Uuid::from(nn_uuid), uuid);
}

#[test]
#[should_panic(expected = "Attempted to convert nil Uuid to NonNilUuid")]
fn test_new_with_nil() {
let nil_uuid = Uuid::from_u128(0x0);
let _ = NonNilUuid::from(nil_uuid);
}
}
Loading