qubit_id/id_generator.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Common trait for ID generators.
11
12use std::error::Error;
13use std::fmt::Display;
14
15/// Generates IDs of type `T`.
16///
17/// The trait keeps the generated representation generic while still providing a
18/// string-producing helper. Numeric generators normally use the default
19/// [`Display`] based formatting. Generators with specialized textual forms can
20/// override [`IdGenerator::format_id`].
21pub trait IdGenerator<T> {
22 /// Error returned when generation fails.
23 type Error: Error;
24
25 /// Generates the next ID value.
26 ///
27 /// # Returns
28 /// The next generated ID.
29 ///
30 /// # Errors
31 /// Returns `Self::Error` when the generator cannot allocate a unique value,
32 /// for example because the clock moved backwards too far, the configured
33 /// time range overflowed, or the random source failed.
34 fn next_id(&self) -> Result<T, Self::Error>;
35
36 /// Formats an already generated ID.
37 ///
38 /// # Parameters
39 /// - `id`: ID value to format.
40 ///
41 /// # Returns
42 /// String representation of `id`.
43 fn format_id(&self, id: &T) -> String
44 where
45 T: Display,
46 {
47 id.to_string()
48 }
49
50 /// Generates the next ID and formats it as a string.
51 ///
52 /// # Returns
53 /// String representation of the next ID.
54 ///
55 /// # Errors
56 /// Returns the same error as [`IdGenerator::next_id`].
57 fn next_string(&self) -> Result<String, Self::Error>
58 where
59 T: Display,
60 {
61 self.next_id().map(|id| self.format_id(&id))
62 }
63}