Skip to content

Commit

Permalink
introduce generate_overflowing and increment_overflowing methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Ekleog committed Feb 2, 2024
1 parent c220598 commit 1395a3e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,35 @@ impl Generator {
self.generate_from_datetime(crate::time_utils::now())
}

/// Generate a new Ulid. Each call is guaranteed to provide a Ulid with a larger value than the
/// last call. The time part of the returned [`Ulid`] can be up to one millisecond in the future,
/// under reasonable assumptions about processor speeds.
///
/// # Panics
///
/// This function panics if the previously returned value was already the highest possible ulid.
/// This should not happen before year 91000 of the gregorian calendar at least.
///
/// ```rust
/// use ulid::Generator;
/// let mut gen = Generator::new();
///
/// let ulid1 = gen.generate_overflowing();
/// let ulid2 = gen.generate_overflowing();
///
/// assert!(ulid1 < ulid2);
/// ```
pub fn generate_overflowing(&mut self) -> Ulid {
let next = Ulid::new();
if next > self.previous {
self.previous = next;
next
} else {
self.previous = self.previous.increment_overflowing();
self.previous
}
}

/// Generate a new Ulid matching the given DateTime.
/// Each call is guaranteed to provide a Ulid with a larger value than the last call.
/// If the random bits would overflow, this method will return an error.
Expand Down
31 changes: 31 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,37 @@ impl Ulid {
}
}

/// Increment the random number, increasing the timestamp if the random number overflows
///
/// # Panics
///
/// This function panics if the previous value was already the highest possible ulid.
/// This should not happen before year 91000 of the gregorian calendar at least.
///
/// # Example
///
/// ```rust
/// use ulid::Ulid;
///
/// let ulid_0 = Ulid::from_parts(0, (1 << Ulid::TIME_BITS) - 1);
/// assert_eq!(
/// ulid_0.to_string(),
/// "00000000000000007ZZZZZZZZZ"
/// );
///
/// let ulid_1 = ulid_0.increment_overflowing();
/// assert_eq!(
/// ulid_1.to_string(),
/// "00000000000000008000000000"
/// );
/// ```
pub const fn increment_overflowing(&self) -> Ulid {
Ulid(match self.0.checked_add(1) {
Some(val) => val,
None => panic!("ULID overflow"),
})
}

/// Creates a Ulid using the provided bytes array.
///
/// # Example
Expand Down

0 comments on commit 1395a3e

Please sign in to comment.