Debian Codegraph @

debian/missing-sources/icu_provider/src/export/mod.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 //! This module contains types required to export ICU4X data via the `icu_provider_export` crate.
6 //! End users should not need to consume anything in this module.
7 //!
8 //! This module is enabled with the `export` Cargo feature.
9
10 mod payload;
11
12 #[doc(hidden)] // macro
13 pub use payload::ExportBox;
14 pub use payload::ExportMarker;
15
16 use crate::prelude::*;
17 use alloc::collections::BTreeSet;
18
19 /// An object capable of exporting data payloads in some form.
20 pub trait DataExporter: Sync {
21 /// Save a `payload` corresponding to the given marker and locale.
22 ///
23 /// Takes non-mut self as it can be called concurrently.
24 fn put_payload(
25 &self,
26 marker: DataMarkerInfo,
27 id: DataIdentifierBorrowed,
28 payload: &DataPayload<ExportMarker>,
29 ) -> Result<(), DataError>;
30
31 /// Function called for singleton markers.
32 ///
33 /// Takes non-mut self as it can be called concurrently.
34 fn flush_singleton(
35 &self,
36 marker: DataMarkerInfo,
37 payload: &DataPayload<ExportMarker>,
38 metadata: FlushMetadata,
39 ) -> Result<(), DataError> {
40 self.put_payload(marker, Default::default(), payload)?;
41 self.flush(marker, metadata)
42 }
43
44 /// Function called after a non-singleton marker has been fully enumerated.
45 ///
46 /// Takes non-mut self as it can be called concurrently.
47 fn flush(&self, _marker: DataMarkerInfo, _metadata: FlushMetadata) -> Result<(), DataError> {
48 Ok(())
49 }
50
51 /// This function has to be called before the object is dropped (after all
52 /// markers have been fully dumped). This conceptually takes ownership, so
53 /// clients *may not* interact with this object after close has been called.
54 fn close(&mut self) -> Result<ExporterCloseMetadata, DataError> {
55 Ok(ExporterCloseMetadata::default())
56 }
57 }
58
59 #[derive(Debug, Default)]
60 #[allow(clippy::exhaustive_structs)] // newtype
61 /// Contains information about a successful export.
62 pub struct ExporterCloseMetadata(pub Option<Box<dyn core::any::Any>>);
63
64 /// Metadata for [`DataExporter::flush`]
65 #[non_exhaustive]
66 #[derive(Debug, Copy, Clone, Default)]
67 pub struct FlushMetadata {
68 /// Whether the data was generated in such a way that a [`DryDataProvider`] implementation
69 /// makes sense.
70 pub supports_dry_provider: bool,
71 /// The checksum to return with this data marker.
72 pub checksum: Option<u64>,
73 }
74
75 impl DataExporter for Box<dyn DataExporter> {
76 fn put_payload(
77 &self,
78 marker: DataMarkerInfo,
79 id: DataIdentifierBorrowed,
80 payload: &DataPayload<ExportMarker>,
81 ) -> Result<(), DataError> {
82 (**self).put_payload(marker, id, payload)
83 }
84
85 fn flush_singleton(
86 &self,
87 marker: DataMarkerInfo,
88 payload: &DataPayload<ExportMarker>,
89 metadata: FlushMetadata,
90 ) -> Result<(), DataError> {
91 (**self).flush_singleton(marker, payload, metadata)
92 }
93
94 fn flush(&self, marker: DataMarkerInfo, metadata: FlushMetadata) -> Result<(), DataError> {
95 (**self).flush(marker, metadata)
96 }
97
98 fn close(&mut self) -> Result<ExporterCloseMetadata, DataError> {
99 (**self).close()
100 }
101 }
102
103 /// A [`DynamicDataProvider`] that can be used for exporting data.
104 ///
105 /// Use [`make_exportable_provider`] to implement this.
106 pub trait ExportableProvider:
107 crate::data_provider::IterableDynamicDataProvider<ExportMarker> + Sync
108 {
109 /// Returns the set of supported markers
110 fn supported_markers(&self) -> BTreeSet<DataMarkerInfo>;
111 }
112
113 impl ExportableProvider for Box<dyn ExportableProvider> {
114 fn supported_markers(&self) -> BTreeSet<DataMarkerInfo> {
115 (**self).supported_markers()
116 }
117 }
118
119 /// This macro can be used on a data provider to allow it to be exported by `ExportDriver`.
120 ///
121 /// Data generation 'compiles' data by using this data provider (which usually translates data from
122 /// different sources and doesn't have to be efficient) to generate data structs, and then writing
123 /// them to an efficient format like `BlobDataProvider` or `BakedDataProvider`. The requirements
124 /// for `make_exportable_provider` are:
125 /// * The data struct has to implement [`serde::Serialize`](::serde::Serialize) and [`databake::Bake`]
126 /// * The provider needs to implement [`IterableDataProvider`] for all specified [`DataMarker`]s.
127 /// This allows the generating code to know which [`DataIdentifierCow`]s to export.
128 #[macro_export]
129 #[doc(hidden)] // macro
130 macro_rules! __make_exportable_provider {
131 ($provider:ty, [ $($(#[$cfg:meta])? $struct_m:ty),+, ]) => {
132 impl $crate::export::ExportableProvider for $provider {
133 fn supported_markers(&self) -> alloc::collections::BTreeSet<$crate::DataMarkerInfo> {
134 alloc::collections::BTreeSet::from_iter([
135 $(
136 $(#[$cfg])?
137 <$struct_m>::INFO,
138 )+
139 ])
140 }
141 }
142
143 $crate::dynutil::impl_dynamic_data_provider!(
144 $provider,
145 [ $($(#[$cfg])? $struct_m),+, ],
146 $crate::export::ExportMarker
147 );
148
149 $crate::dynutil::impl_iterable_dynamic_data_provider!(
150 $provider,
151 [ $($(#[$cfg])? $struct_m),+, ],
152 $crate::export::ExportMarker
153 );
154 };
155 }
156 #[doc(inline)]
157 pub use __make_exportable_provider as make_exportable_provider;
158
159 /// A `DataExporter` that forks to multiple `DataExporter`s.
160 #[derive(Default)]
161 pub struct MultiExporter(Vec<Box<dyn DataExporter>>);
162
163 impl MultiExporter {
164 /// Creates a `MultiExporter` for the given exporters.
165 pub const fn new(exporters: Vec<Box<dyn DataExporter>>) -> Self {
166 Self(exporters)
167 }
168 }
169
170 impl core::fmt::Debug for MultiExporter {
171 fn fmt(&self, f: &mut alloc::fmt::Formatter<'_>) -> alloc::fmt::Result {
172 f.debug_struct("MultiExporter")
173 .field("0", &format!("vec[len = {}]", self.0.len()))
174 .finish()
175 }
176 }
177
178 impl DataExporter for MultiExporter {
179 fn put_payload(
180 &self,
181 marker: DataMarkerInfo,
182 id: DataIdentifierBorrowed,
183 payload: &DataPayload<ExportMarker>,
184 ) -> Result<(), DataError> {
185 self.0
186 .iter()
187 .try_for_each(|e| e.put_payload(marker, id, payload))
188 }
189
190 fn flush_singleton(
191 &self,
192 marker: DataMarkerInfo,
193 payload: &DataPayload<ExportMarker>,
194 metadata: FlushMetadata,
195 ) -> Result<(), DataError> {
196 self.0
197 .iter()
198 .try_for_each(|e| e.flush_singleton(marker, payload, metadata))
199 }
200
201 fn flush(&self, marker: DataMarkerInfo, metadata: FlushMetadata) -> Result<(), DataError> {
202 self.0.iter().try_for_each(|e| e.flush(marker, metadata))
203 }
204
205 fn close(&mut self) -> Result<ExporterCloseMetadata, DataError> {
206 Ok(ExporterCloseMetadata(Some(Box::new(
207 self.0.iter_mut().try_fold(vec![], |mut m, e| {
208 m.push(e.close()?.0);
209 Ok::<_, DataError>(m)
210 })?,
211 ))))
212 }
213 }