grain_id/id.rs
1use core::{fmt::Display, str::FromStr};
2
3use crate::{Error, alphabet};
4
5/// Grain id struct
6///
7/// # Examples
8#[cfg_attr(all(feature = "rand", feature = "std"), doc = "```rust")]
9#[cfg_attr(not(all(feature = "rand", feature = "std")), doc = "```ignore")]
10/// # use grain_id::*;
11/// # fn main() -> Result<(), Error> {
12/// // Generate random value.
13/// let random = GrainId::random();
14///
15/// // Parse from string.
16/// let from_str: GrainId = "012abcd".parse()?;
17///
18/// // Parse from integer.
19/// let from_int: GrainId = 35990925u64.try_into()?;
20///
21/// assert_eq!(from_str, from_int);
22/// # Ok(())
23/// # }
24/// ```
25#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
26pub struct GrainId(u64);
27
28impl GrainId {
29 /// The number of significant bits of a [`GrainId`].
30 ///
31 /// The value is stored in a [`u64`], but only the lower 35 bits are used.
32 pub const BITS: u32 = 35;
33
34 /// The number of characters of the string representation.
35 pub(crate) const LEN: usize = 7;
36
37 const MAX_VALUE: u64 = (1 << Self::BITS) - 1;
38
39 const fn from_u64_unchecked(value: u64) -> Self {
40 Self(value)
41 }
42
43 /// The smallest value that can be represented by [`GrainId`].
44 ///
45 /// # Examples
46 ///
47 /// ```
48 /// # use grain_id::*;
49 /// # fn main() -> Result<(), Error> {
50 /// assert_eq!(GrainId::NIL, "0000000".parse::<GrainId>()?);
51 /// assert_eq!(GrainId::NIL, GrainId::try_from(0)?);
52 /// # Ok(())
53 /// # }
54 /// ```
55 pub const NIL: Self = Self::from_u64_unchecked(0);
56
57 /// The largest value that can be represented by [`GrainId`].
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// # use grain_id::*;
63 /// # fn main() -> Result<(), Error> {
64 /// assert_eq!(GrainId::MAX, "zzzzzzz".parse::<GrainId>()?);
65 /// assert_eq!(GrainId::MAX, GrainId::try_from((1 << GrainId::BITS) - 1)?);
66 /// # Ok(())
67 /// # }
68 /// ```
69 pub const MAX: Self = Self::from_u64_unchecked(Self::MAX_VALUE);
70
71 /// Test if the [`GrainId`] is nil.
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// # use grain_id::*;
77 /// # fn main() -> Result<(), Error> {
78 /// assert!("0000000".parse::<GrainId>()?.is_nil());
79 /// # Ok(())
80 /// # }
81 /// ```
82 pub const fn is_nil(&self) -> bool {
83 self.0 == Self::NIL.0
84 }
85
86 /// Test if the [`GrainId`] is max.
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// # use grain_id::*;
92 /// # fn main() -> Result<(), Error> {
93 /// assert!("zzzzzzz".parse::<GrainId>()?.is_max());
94 /// # Ok(())
95 /// # }
96 /// ```
97 pub const fn is_max(&self) -> bool {
98 self.0 == Self::MAX.0
99 }
100
101 /// Converts an unsigned integer to [`GrainId`] by truncating bits that exceed the valid range.
102 ///
103 /// This is a lossy conversion that keeps only the lower [`BITS`](Self::BITS) bits
104 /// (i.e. the value modulo 2<sup>35</sup>).
105 /// If you need to detect out-of-range values, use [`from_u64`](Self::from_u64) instead.
106 ///
107 /// # Examples
108 ///
109 /// ```
110 /// # use grain_id::*;
111 /// // Values within range are preserved
112 /// let valid_int = 123;
113 /// let id = GrainId::from_u64_lossy(valid_int);
114 /// assert_eq!(u64::from(id), valid_int);
115 ///
116 /// // Values exceeding 35 bits are truncated (MSBs dropped)
117 /// let oversized_int = valid_int + (1 << GrainId::BITS);
118 /// let overflowed_id = GrainId::from_u64_lossy(oversized_int);
119 /// assert_eq!(u64::from(overflowed_id), valid_int)
120 /// ```
121 pub const fn from_u64_lossy(int: u64) -> Self {
122 Self::from_u64_unchecked(int & Self::MAX_VALUE)
123 }
124
125 /// Attempts to convert a [`u64`] to [`GrainId`].
126 ///
127 /// Returns an error if the value is larger than [`GrainId::MAX`].
128 /// If you don't need to detect out-of-range values, use [`from_u64_lossy`](Self::from_u64_lossy).
129 ///
130 /// # Examples
131 ///
132 /// ```
133 /// # use grain_id::*;
134 /// # fn main() -> Result<(), Error> {
135 /// assert_eq!(GrainId::from_u64(0x7FFFFFFFF)?, GrainId::MAX);
136 /// assert!(GrainId::from_u64(0x800000000).is_err());
137 /// # Ok(())
138 /// # }
139 /// ```
140 pub const fn from_u64(value: u64) -> Result<Self, Error> {
141 if value <= Self::MAX_VALUE {
142 Ok(Self::from_u64_unchecked(value))
143 } else {
144 Err(Error::ValueOutOfRange(value))
145 }
146 }
147
148 /// Returns a reference of internal 64bit integer.
149 #[deprecated(
150 since = "0.17.0",
151 note = "Use `to_u64()` (or `u64::from(id)`) to get the value instead."
152 )]
153 pub const fn as_u64(&self) -> &u64 {
154 &self.0
155 }
156
157 /// Returns an internal 64bit integer value.
158 ///
159 /// # Examples
160 ///
161 /// ```
162 /// # use grain_id::*;
163 /// # fn main() -> Result<(), Error> {
164 /// let id = GrainId::from_u64(0x123456789)?;
165 /// assert_eq!(id.to_u64(), 0x123456789);
166 /// # Ok(())
167 /// # }
168 /// ```
169 pub const fn to_u64(self) -> u64 {
170 self.0
171 }
172
173 /// Returns the string representation as ASCII bytes.
174 pub(crate) const fn encode(self) -> [u8; Self::LEN] {
175 alphabet::encode(self.0)
176 }
177
178 /// Creates a `GrainId` from a [`Duration`](core::time::Duration) based on decisecond precision.
179 ///
180 /// This method converts the given duration into deciseconds (0.1 second units)
181 /// and generates a `GrainId` from it. The resulting 35-bit identifier can
182 /// represent approximately 109 years worth of deciseconds.
183 ///
184 /// # Timestamp Format
185 ///
186 /// The entire 35 bits are used to represent the timestamp in deciseconds,
187 /// allowing for chronological sorting while maintaining a compact 7-character
188 /// BASE32 representation.
189 ///
190 /// # Overflow Behavior
191 ///
192 /// If the duration exceeds the maximum representable value (2^35 deciseconds,
193 /// approximately 109 years), the timestamp will wrap around. This is generally
194 /// not a concern for personal applications within a human lifespan.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// # use grain_id::*;
200 /// use std::time::Duration;
201 ///
202 /// # fn main() -> Result<(), Error> {
203 /// let duration = Duration::new(5, 730_023_852);
204 /// let id = GrainId::from_duration(duration);
205 /// assert_eq!(id, GrainId::from_u64(57)?);
206 /// # Ok(())
207 /// # }
208 /// ```
209 pub const fn from_duration(duration: core::time::Duration) -> Self {
210 let decisecs = duration.as_millis() / 100;
211 // 2^35 divides 2^64, so truncating to u64 first does not change the result.
212 Self::from_u64_lossy(decisecs as u64)
213 }
214
215 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the boundary of the type.
216 ///
217 /// # Examples
218 /// ```
219 /// # use grain_id::*;
220 /// # fn main() -> Result<(), Error> {
221 /// assert_eq!(
222 /// GrainId::from_u64(100)?.wrapping_sub(GrainId::from_u64(100)?),
223 /// GrainId::NIL
224 /// );
225 /// assert_eq!(
226 /// GrainId::from_u64(100)?.wrapping_sub(GrainId::from_u64(101)?),
227 /// GrainId::MAX
228 /// );
229 /// # Ok(())
230 /// # }
231 /// ```
232 pub const fn wrapping_sub(self, rhs: Self) -> Self {
233 GrainId::from_u64_lossy(self.0.wrapping_sub(rhs.0))
234 }
235
236 /// Increments the value by 1, wrapping around to [`GrainId::NIL`] on overflow.
237 ///
238 /// # Examples
239 /// ```
240 /// # use grain_id::*;
241 /// # fn main() -> Result<(), Error> {
242 /// assert_eq!(GrainId::from_u64(100)?.increment(), GrainId::from_u64(101)?);
243 /// assert_eq!(GrainId::MAX.increment(), GrainId::NIL);
244 /// # Ok(())
245 /// # }
246 /// ```
247 pub const fn increment(self) -> Self {
248 GrainId::from_u64_lossy(self.0 + 1)
249 }
250
251 /// Creates a `GrainId` from the leading (most significant) 35 bits of a 5-byte array.
252 ///
253 /// This is useful for generating a compact identifier from a pre-computed hash,
254 /// public key, or any arbitrary byte sequence.
255 ///
256 /// # Examples
257 ///
258 /// ```
259 /// # use grain_id::*;
260 /// // Extract leading 35 bits from a byte array
261 /// let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
262 /// let id = GrainId::from_byte_prefix(&bytes);
263 /// assert_eq!(id, GrainId::MAX);
264 ///
265 /// // For longer data, slice the first 5 bytes
266 /// let hash: [u8; 32] = [0; 32];
267 /// let id = GrainId::from_byte_prefix(hash[..5].try_into().unwrap());
268 /// assert_eq!(id, GrainId::NIL);
269 /// ```
270 pub const fn from_byte_prefix(bytes: &[u8; 5]) -> Self {
271 let [a, b, c, d, e] = *bytes;
272 Self::from_u64_unchecked(u64::from_be_bytes([0, 0, 0, a, b, c, d, e]) >> 5)
273 }
274
275 /// Creates a `GrainId` from the trailing (least significant) 35 bits of a 5-byte array.
276 ///
277 /// This is the counterpart to [`from_byte_prefix`](Self::from_byte_prefix).
278 /// The upper 5 bits of the first byte are ignored.
279 ///
280 /// # Examples
281 ///
282 /// ```
283 /// # use grain_id::*;
284 /// // Extract trailing 35 bits from a byte array
285 /// let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
286 /// let id = GrainId::from_byte_suffix(&bytes);
287 /// assert_eq!(id, GrainId::MAX);
288 ///
289 /// // Upper 5 bits of the first byte are ignored
290 /// let bytes = [0xF8, 0x00, 0x00, 0x00, 0x00];
291 /// let id = GrainId::from_byte_suffix(&bytes);
292 /// assert_eq!(id, GrainId::NIL);
293 /// ```
294 pub const fn from_byte_suffix(bytes: &[u8; 5]) -> Self {
295 let [a, b, c, d, e] = *bytes;
296 Self::from_u64_lossy(u64::from_be_bytes([0, 0, 0, a, b, c, d, e]))
297 }
298
299 /// Returns a 5-byte array with the `GrainId` value stored in the leading (most significant) 35 bits.
300 ///
301 /// This is the counterpart to [`from_byte_prefix`](Self::from_byte_prefix).
302 /// The lower 5 bits of the last byte are always zero.
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// # use grain_id::*;
308 /// # fn main() -> Result<(), Error> {
309 /// let bytes = GrainId::from_u64(0x123456789)?.to_byte_prefix();
310 /// assert_eq!(bytes, [0x24, 0x68, 0xAC, 0xF1, 0x20]);
311 ///
312 /// // Round-trip
313 /// let id = GrainId::from_u64(0x123456789)?;
314 /// assert_eq!(GrainId::from_byte_prefix(&id.to_byte_prefix()), id);
315 /// # Ok(())
316 /// # }
317 /// ```
318 pub const fn to_byte_prefix(self) -> [u8; 5] {
319 let [_, _, _, a, b, c, d, e] = (self.0 << 5).to_be_bytes();
320 [a, b, c, d, e]
321 }
322
323 /// Returns a 5-byte array with the `GrainId` value stored in the trailing (least significant) 35 bits.
324 ///
325 /// This is the counterpart to [`from_byte_suffix`](Self::from_byte_suffix).
326 /// The upper 5 bits of the first byte are always zero.
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// # use grain_id::*;
332 /// # fn main() -> Result<(), Error> {
333 /// let bytes = GrainId::from_u64(0x123456789)?.to_byte_suffix();
334 /// assert_eq!(bytes, [0x01, 0x23, 0x45, 0x67, 0x89]);
335 ///
336 /// // Round-trip
337 /// let id = GrainId::from_u64(0x123456789)?;
338 /// assert_eq!(GrainId::from_byte_suffix(&id.to_byte_suffix()), id);
339 /// # Ok(())
340 /// # }
341 /// ```
342 pub const fn to_byte_suffix(self) -> [u8; 5] {
343 let [_, _, _, a, b, c, d, e] = self.0.to_be_bytes();
344 [a, b, c, d, e]
345 }
346}
347
348impl AsRef<u64> for GrainId {
349 fn as_ref(&self) -> &u64 {
350 &self.0
351 }
352}
353
354impl TryFrom<u64> for GrainId {
355 type Error = Error;
356 /// Attempts to convert a [`u64`] to [`GrainId`].
357 ///
358 /// See [`GrainId::from_u64`] for details.
359 ///
360 /// # Examples
361 ///
362 /// ```
363 /// # use grain_id::*;
364 /// assert!(GrainId::try_from(GrainId::MAX.to_u64()).is_ok());
365 /// assert!(GrainId::try_from(GrainId::MAX.to_u64() + 1).is_err());
366 /// ```
367 fn try_from(value: u64) -> Result<Self, Self::Error> {
368 Self::from_u64(value)
369 }
370}
371
372impl From<GrainId> for u64 {
373 fn from(value: GrainId) -> Self {
374 value.0
375 }
376}
377
378impl Display for GrainId {
379 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
380 f.pad(alphabet::as_str(&self.encode()))
381 }
382}
383
384impl FromStr for GrainId {
385 type Err = Error;
386
387 /// Parses a 7-character grain-id string.
388 ///
389 /// Decoding is case-insensitive and accepts the aliases described in
390 /// [`alphabet`](crate::alphabet).
391 ///
392 /// # Examples
393 ///
394 /// ```
395 /// # use grain_id::*;
396 /// # fn main() -> Result<(), Error> {
397 /// assert_eq!("012ABCD".parse::<GrainId>()?, "o12abcd".parse::<GrainId>()?);
398 /// assert_eq!("0123".parse::<GrainId>(), Err(Error::InvalidLength(4)));
399 /// // Non-ASCII input is rejected, never panics.
400 /// assert!("ab€cd".parse::<GrainId>().is_err());
401 /// # Ok(())
402 /// # }
403 /// ```
404 fn from_str(s: &str) -> Result<Self, Self::Err> {
405 let len = s.chars().count();
406 if len != Self::LEN {
407 return Err(Error::InvalidLength(len));
408 }
409 let (value, _) = alphabet::decode(s)?;
410 Ok(Self::from_u64_unchecked(value))
411 }
412}