Skip to main content

qubit_codec/value/
value_codec_registry.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! Local immutable value-codec registry.
10
11use crate::ValueCodecRegistration;
12use crate::ValueCodecRegistryError;
13
14// Implements process-wide lookup for the bytes-wire specialization.
15#[path = "value_codec_registry/value_bytes_codec_registry.rs"]
16mod value_bytes_codec_registry;
17// Implements process-wide lookup for the string-wire specialization.
18#[path = "value_codec_registry/value_string_codec_registry.rs"]
19mod value_string_codec_registry;
20
21pub use value_bytes_codec_registry::ValueBytesCodecRegistry;
22pub use value_string_codec_registry::ValueStringCodecRegistry;
23
24/// An immutable value-codec registry sorted by stable ID.
25///
26/// # Type Parameters
27///
28/// - `D`: Static descriptor type identifying one wire representation. The
29///   registry API is implemented for descriptors that also satisfy `Copy`.
30///
31/// # Examples
32///
33/// ```
34/// use qubit_codec::ValueCodecRegistry;
35/// use qubit_codec::ValueStringCodecDescriptor;
36/// use qubit_codec::ValueStringCodecRegistry;
37///
38/// let registry: ValueCodecRegistry<ValueStringCodecDescriptor> =
39///     ValueStringCodecRegistry::empty();
40/// assert!(registry.get("missing.example").is_none());
41/// ```
42#[derive(Debug)]
43pub struct ValueCodecRegistry<D: 'static> {
44    /// Owned registrations sorted once by stable ID for binary-search lookup.
45    registrations: Box<[ValueCodecRegistration<D>]>,
46}
47
48impl<D: Copy + 'static> ValueCodecRegistry<D> {
49    /// Builds a local registry from static registrations without consulting
50    /// or modifying the process-wide registry.
51    ///
52    /// # Parameters
53    ///
54    /// - `registrations`: Static entries copied into this registry; input order
55    ///   is ignored.
56    ///
57    /// # Returns
58    ///
59    /// An owned, immutable registry sorted by ID, independent of the iterator.
60    ///
61    /// # Errors
62    ///
63    /// Returns a duplicate-ID error when multiple entries claim one ID.
64    ///
65    /// # Examples
66    ///
67    /// This example uses a local static registration; it does not submit an
68    /// entry to the process-wide inventory.
69    ///
70    /// ```
71    /// use std::convert::Infallible;
72    /// use qubit_codec::ValueCodecId;
73    /// use qubit_codec::ValueCodecRegistration;
74    /// use qubit_codec::ValueCodecRegistrationSource;
75    /// use qubit_codec::ValueDecoder;
76    /// use qubit_codec::ValueEncoder;
77    /// use qubit_codec::ValueStringCodecDescriptor;
78    /// use qubit_codec::ValueStringCodecRegistration;
79    /// use qubit_codec::ValueStringCodecRegistry;
80    ///
81    /// #[derive(Default)]
82    /// struct LocalText;
83    ///
84    /// impl ValueEncoder<String> for LocalText {
85    ///     type Output = String;
86    ///     type Error = Infallible;
87    ///
88    ///     fn encode(&mut self, input: &String) -> Result<String, Infallible> {
89    ///         Ok(input.clone())
90    ///     }
91    /// }
92    ///
93    /// impl ValueDecoder<str> for LocalText {
94    ///     type Output = String;
95    ///     type Error = Infallible;
96    ///
97    ///     fn decode(&mut self, input: &str) -> Result<String, Infallible> {
98    ///         Ok(input.to_owned())
99    ///     }
100    /// }
101    ///
102    /// static DESCRIPTOR: ValueStringCodecDescriptor =
103    ///     ValueStringCodecDescriptor::of::<LocalText, String>();
104    /// static REGISTRATION: ValueStringCodecRegistration = ValueCodecRegistration::new(
105    ///     ValueCodecId::new("example.local.text"),
106    ///     &DESCRIPTOR,
107    ///     ValueCodecRegistrationSource::new("local-example", "example", file!(), line!()),
108    /// );
109    ///
110    /// let registry = ValueStringCodecRegistry::from_registrations([&REGISTRATION])
111    ///     .expect("unique local registration");
112    /// let descriptor = registry.get("example.local.text")
113    ///     .expect("registered locally").descriptor();
114    /// let encoded = descriptor.encode(&String::from("hello")).expect("encode");
115    /// assert_eq!("hello", encoded);
116    /// let decoded = descriptor.decode(&encoded).expect("decode");
117    /// assert_eq!("hello", *decoded.downcast::<String>().expect("String output"));
118    /// assert!(registry.get("example.missing").is_none());
119    /// ```
120    pub fn from_registrations(
121        registrations: impl IntoIterator<Item = &'static ValueCodecRegistration<D>>,
122    ) -> Result<Self, ValueCodecRegistryError> {
123        Self::build(registrations.into_iter().copied().collect())
124    }
125
126    /// Returns an empty local registry.
127    ///
128    /// # Returns
129    ///
130    /// A local registry with no registrations.
131    #[must_use]
132    #[inline]
133    pub fn empty() -> Self {
134        Self {
135            registrations: Box::new([]),
136        }
137    }
138
139    /// Sorts registrations and rejects duplicate IDs.
140    ///
141    /// # Parameters
142    ///
143    /// - `registrations`: Owned entries sorted in place by stable ID.
144    ///
145    /// # Returns
146    ///
147    /// An immutable registry owning the sorted entries used for lookup.
148    ///
149    /// # Errors
150    ///
151    /// Returns `DuplicateId` with the lexically first conflicting ID and all
152    /// of its sources sorted by source fields. Repeated identical sources are
153    /// retained because each registration is reported.
154    pub(super) fn build(mut registrations: Vec<ValueCodecRegistration<D>>) -> Result<Self, ValueCodecRegistryError> {
155        registrations.sort_by_key(ValueCodecRegistration::id);
156        for (index, pair) in registrations.windows(2).enumerate() {
157            if pair[0].id() == pair[1].id() {
158                let id = pair[0].id();
159                let mut sources = registrations[index..]
160                    .iter()
161                    .take_while(|registration| registration.id() == id)
162                    .map(ValueCodecRegistration::source)
163                    .collect::<Vec<_>>();
164                sources.sort_unstable();
165                return Err(ValueCodecRegistryError::DuplicateId {
166                    id: id.as_str(),
167                    sources,
168                });
169            }
170        }
171        Ok(Self {
172            registrations: registrations.into_boxed_slice(),
173        })
174    }
175
176    /// Finds a registration by stable ID.
177    ///
178    /// # Parameters
179    ///
180    /// - `id`: Exact stable ID to look up, without normalization.
181    ///
182    /// # Returns
183    ///
184    /// `Some` borrows the matching registration from this registry; `None`
185    /// means the ID is absent. Lookup uses a binary search over the sorted
186    /// registration array.
187    #[inline]
188    pub fn get(&self, id: &str) -> Option<&ValueCodecRegistration<D>> {
189        let index = self
190            .registrations
191            .binary_search_by(|registration| registration.id().as_str().cmp(id))
192            .ok()?;
193        self.registrations.get(index)
194    }
195
196    /// Returns registrations in deterministic ID order.
197    ///
198    /// # Returns
199    ///
200    /// The immutable registration slice borrowed from this registry without
201    /// allocation.
202    #[must_use]
203    #[inline]
204    pub fn registrations(&self) -> &[ValueCodecRegistration<D>] {
205        &self.registrations
206    }
207}