more-config 2.0.0

Provides support for configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use crate::{util::fmt_debug_view, *};
use cfg_if::cfg_if;
use std::any::Any;
use std::borrow::Borrow;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter, Result as FormatResult};
use std::ops::Deref;
use tokens::{ChangeToken, CompositeChangeToken, SharedChangeToken};

cfg_if! {
    if #[cfg(feature = "async")] {
        use std::sync::Arc;

        type Pc<T> = std::sync::Arc<T>;
        type Mut<T> = std::sync::RwLock<T>;
        type Ref<'a, T> = Arc<std::sync::RwLockReadGuard<'a, T>>;
    } else {
        use std::cell::Ref;

        type Pc<T> = std::rc::Rc<T>;
        type Mut<T> = std::cell::RefCell<T>;
    }
}

struct ProviderItem<'a> {
    index: usize,
    name: String,
    items: Ref<'a, Vec<Box<dyn ConfigurationProvider + 'a>>>,
}

impl<'a> ProviderItem<'a> {
    fn new(
        items: Ref<'a, Vec<Box<dyn ConfigurationProvider + 'a>>>,
        index: usize,
        name: String,
    ) -> Self {
        Self { index, name, items }
    }
}

impl ConfigurationProvider for ProviderItem<'_> {
    fn get(&self, key: &str) -> Option<Value> {
        self.items[self.index].get(key)
    }

    fn child_keys(&self, earlier_keys: &mut Vec<String>, parent_path: Option<&str>) {
        self.items[self.index].child_keys(earlier_keys, parent_path)
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        self.items[self.index].reload_token()
    }
}

struct ProviderIter<'a> {
    head: usize,
    tail: usize,
    items: Ref<'a, Vec<Box<dyn ConfigurationProvider>>>,
}

impl<'a> ProviderIter<'a> {
    fn new(items: Ref<'a, Vec<Box<dyn ConfigurationProvider>>>) -> Self {
        Self {
            head: 0,
            tail: items.len(),
            items,
        }
    }
}

impl<'a> Iterator for ProviderIter<'a> {
    type Item = Box<dyn ConfigurationProvider + 'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.head < self.items.len() {
            let i = self.head;
            let name = self.items[i].name().to_owned();
            self.head += 1;

            cfg_if! {
                if #[cfg(feature = "async")] {
                    Some(Box::new(ProviderItem::new(
                        self.items.clone(),
                        i,
                        name,
                    )))
                } else {
                    Some(Box::new(ProviderItem::new(
                        Ref::clone(&self.items),
                        i,
                        name,
                    )))
                }
            }
        } else {
            None
        }
    }
}

impl ExactSizeIterator for ProviderIter<'_> {
    fn len(&self) -> usize {
        self.items.len()
    }
}

impl DoubleEndedIterator for ProviderIter<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.tail > 0 {
            self.tail -= 1;
            let name = self.items[self.tail].name().to_owned();

            cfg_if! {
                if #[cfg(feature = "async")] {
                    Some(Box::new(ProviderItem::new(
                        self.items.clone(),
                        self.tail,
                        name,
                    )))
                } else {
                    Some(Box::new(ProviderItem::new(
                        Ref::clone(&self.items),
                        self.tail,
                        name,
                    )))
                }
            }
        } else {
            None
        }
    }
}

impl<'a> ConfigurationProviderIterator<'a> for ProviderIter<'a> {}

/// Represents the root of a configuration.
#[derive(Clone)]
pub struct DefaultConfigurationRoot {
    token: SharedChangeToken<CompositeChangeToken>,
    providers: Pc<Mut<Vec<Box<dyn ConfigurationProvider>>>>,
}

impl DefaultConfigurationRoot {
    /// Initializes a new root configuration.
    ///
    /// # Arguments
    ///
    /// * `providers` - The [`ConfigurationProvider`](crate::ConfigurationProvider) list used in the configuration
    pub fn new(mut providers: Vec<Box<dyn ConfigurationProvider>>) -> Result<Self, ReloadError> {
        let mut errors = Vec::new();
        let mut tokens = Vec::with_capacity(providers.len());

        for provider in providers.iter_mut() {
            let result = provider.load();

            if let Err(error) = result {
                errors.push((provider.name().to_owned(), error));
            }

            tokens.push(provider.reload_token());
        }

        if errors.is_empty() {
            Ok(Self {
                token: SharedChangeToken::new(CompositeChangeToken::new(tokens.into_iter())),
                providers: Pc::new(providers.into()),
            })
        } else {
            Err(ReloadError::Provider(errors))
        }
    }
}

impl ConfigurationRoot for DefaultConfigurationRoot {
    fn reload(&mut self) -> ReloadResult {
        let borrowed = (Pc::strong_count(&self.providers) - 1) + Pc::weak_count(&self.providers);

        cfg_if! {
            if #[cfg(feature = "async")] {
                let result = self.providers.try_write();
            } else {
                let result = self.providers.try_borrow_mut();
            }
        }

        if let Ok(mut providers) = result {
            let mut errors = Vec::new();
            let mut tokens = Vec::with_capacity(providers.len());

            for provider in providers.iter_mut() {
                let result = provider.load();

                if let Err(error) = result {
                    errors.push((provider.name().to_owned(), error));
                }

                tokens.push(provider.reload_token());
            }

            let new_token = SharedChangeToken::new(CompositeChangeToken::new(tokens.into_iter()));
            let old_token = std::mem::replace(&mut self.token, new_token);

            old_token.notify();

            if errors.is_empty() {
                Ok(())
            } else {
                Err(ReloadError::Provider(errors))
            }
        } else {
            Err(ReloadError::Borrowed(Some(borrowed)))
        }
    }

    fn providers(&self) -> Box<dyn ConfigurationProviderIterator + '_> {
        cfg_if! {
            if #[cfg(feature = "async")] {
                Box::new(ProviderIter::new(self.providers.deref().read().unwrap().into()))
            } else {
                Box::new(ProviderIter::new(self.providers.deref().borrow()))
            }
        }
    }

    fn as_config(&self) -> Box<dyn Configuration> {
        Box::new(self.clone())
    }
}

impl Configuration for DefaultConfigurationRoot {
    fn get(&self, key: &str) -> Option<Value> {
        for provider in self.providers().rev() {
            if let Some(value) = provider.get(key) {
                return Some(value);
            }
        }

        None
    }

    fn section(&self, key: &str) -> Box<dyn ConfigurationSection> {
        Box::new(DefaultConfigurationSection::new(
            Box::new(self.clone()),
            key,
        ))
    }

    fn children(&self) -> Vec<Box<dyn ConfigurationSection>> {
        self.providers()
            .fold(Vec::new(), |mut earlier_keys, provider| {
                provider.child_keys(&mut earlier_keys, None);
                earlier_keys
            })
            .into_iter()
            .collect::<HashSet<_>>()
            .iter()
            .map(|key| self.section(key))
            .collect()
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        Box::new(self.token.clone())
    }

    fn iter(&self, path: Option<ConfigurationPath>) -> Box<dyn Iterator<Item = (String, Value)>> {
        Box::new(ConfigurationIterator::new(
            self,
            path.unwrap_or(ConfigurationPath::Absolute),
        ))
    }
}

impl Debug for DefaultConfigurationRoot {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FormatResult {
        fmt_debug_view(self, formatter)
    }
}

impl<'a> AsRef<dyn Configuration + 'a> for DefaultConfigurationRoot {
    fn as_ref(&self) -> &(dyn Configuration + 'a) {
        self
    }
}

impl<'a> Borrow<dyn Configuration + 'a> for DefaultConfigurationRoot {
    fn borrow(&self) -> &(dyn Configuration + 'a) {
        self
    }
}

impl Deref for DefaultConfigurationRoot {
    type Target = dyn Configuration;

    fn deref(&self) -> &Self::Target {
        self
    }
}

cfg_if! {
    if #[cfg(feature = "async")] {
        unsafe impl Send for DefaultConfigurationRoot {}
        unsafe impl Sync for DefaultConfigurationRoot {}
    }
}

/// Represent a configuration section.
pub struct DefaultConfigurationSection {
    root: Box<dyn ConfigurationRoot>,
    path: String,
}

impl DefaultConfigurationSection {
    /// Initializes a new configuration section.
    ///
    /// # Arguments
    ///
    /// * `root` - A reference to the [`ConfigurationRoot`](crate::ConfigurationRoot)
    /// * `path` - The path of the configuration section
    pub fn new(root: Box<dyn ConfigurationRoot>, path: &str) -> Self {
        Self {
            root,
            path: path.to_owned(),
        }
    }

    #[inline]
    fn subkey(&self, key: &str) -> String {
        ConfigurationPath::combine(&[&self.path, key])
    }
}

impl Configuration for DefaultConfigurationSection {
    fn get(&self, key: &str) -> Option<Value> {
        self.root.get(&self.subkey(key))
    }

    fn section(&self, key: &str) -> Box<dyn ConfigurationSection> {
        self.root.section(&self.subkey(key))
    }

    fn children(&self) -> Vec<Box<dyn ConfigurationSection>> {
        self.root
            .providers()
            .fold(Vec::new(), |mut earlier_keys, provider| {
                provider.child_keys(&mut earlier_keys, Some(&self.path));
                earlier_keys
            })
            .into_iter()
            .collect::<HashSet<_>>()
            .iter()
            .map(|key| self.section(key))
            .collect()
    }

    fn reload_token(&self) -> Box<dyn ChangeToken> {
        self.root.reload_token()
    }

    fn as_section(&self) -> Option<&dyn ConfigurationSection> {
        Some(self)
    }

    fn iter(&self, path: Option<ConfigurationPath>) -> Box<dyn Iterator<Item = (String, Value)>> {
        Box::new(ConfigurationIterator::new(
            self,
            path.unwrap_or(ConfigurationPath::Absolute),
        ))
    }
}

impl ConfigurationSection for DefaultConfigurationSection {
    fn key(&self) -> &str {
        ConfigurationPath::section_key(&self.path)
    }

    fn path(&self) -> &str {
        &self.path
    }

    fn value(&self) -> Value {
        self.root.get(&self.path).unwrap_or_default()
    }
}

impl<'a> AsRef<dyn Configuration + 'a> for DefaultConfigurationSection {
    fn as_ref(&self) -> &(dyn Configuration + 'a) {
        self
    }
}

impl<'a> Borrow<dyn Configuration + 'a> for DefaultConfigurationSection {
    fn borrow(&self) -> &(dyn Configuration + 'a) {
        self
    }
}

impl Deref for DefaultConfigurationSection {
    type Target = dyn Configuration;

    fn deref(&self) -> &Self::Target {
        self
    }
}

/// Represents a configuration builder.
#[derive(Default)]
pub struct DefaultConfigurationBuilder {
    /// Gets the associated configuration sources.
    pub sources: Vec<Box<dyn ConfigurationSource>>,

    /// Gets the properties that can be passed to configuration sources.
    pub properties: HashMap<String, Box<dyn Any>>,
}

impl DefaultConfigurationBuilder {
    /// Initializes a new, default configuration builder.
    pub fn new() -> Self {
        Self::default()
    }
}

impl ConfigurationBuilder for DefaultConfigurationBuilder {
    fn properties(&self) -> &HashMap<String, Box<dyn Any>> {
        &self.properties
    }

    fn sources(&self) -> &[Box<dyn ConfigurationSource>] {
        &self.sources
    }

    fn add(&mut self, source: Box<dyn ConfigurationSource>) {
        self.sources.push(source)
    }

    fn build(&self) -> Result<Box<dyn ConfigurationRoot>, ReloadError> {
        Ok(Box::new(DefaultConfigurationRoot::new(
            self.sources.iter().map(|s| s.build(self)).collect(),
        )?))
    }
}