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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
|
//! Parser for the [POM file format](https://www.pom.computer/index.html).
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(missing_docs)]
#![warn(clippy::semicolon_if_nothing_returned)]
#![warn(clippy::redundant_closure_for_method_calls)]
extern crate alloc;
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use alloc::{format, vec};
use core::fmt;
use core::mem::take;
#[cfg(test)]
mod tests;
/// File and line information
#[derive(Clone, Debug)]
pub struct Location {
file: Arc<str>,
line: u64,
}
impl Location {
/// File name
#[must_use]
pub fn file(&self) -> &str {
&self.file
}
/// Line number
#[must_use]
pub fn line(&self) -> u64 {
self.line
}
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.file, self.line)
}
}
/// A string value, together with location information about where it is defined.
#[derive(Clone, Debug)]
struct Value {
value: Box<str>,
defined_at: Location,
}
/// A parsed POM configuration.
#[derive(Clone, Debug, Default)]
pub struct Configuration {
/// List of items in configuration, sorted by key.
items: Vec<(Box<str>, Value)>,
}
impl fmt::Display for Configuration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (key, value) in &self.items {
writeln!(f, "{key} = {value:?}")?;
}
Ok(())
}
}
/// A parsing or schema error.
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
/// I/O error
///
/// The first field is a description of what led to the error.
#[cfg(feature = "std")]
IO(Box<str>, std::io::Error),
/// Illegal character in POM file
///
/// Specifically, an ASCII control character other than LF, CR immediately followed by LF, and tab.
IllegalCharacter(Location, char),
/// Invalid UTF-8 in POM file
InvalidUtf8(Location),
/// Couldn't parse signed integer.
BadInt(Location, Box<str>),
/// Couldn't parse unsigned integer.
BadUInt(Location, Box<str>),
/// Couldn't parse floating-point number.
BadFloat(Location, Box<str>),
/// Couldn't parse boolean.
BadBool(Location, Box<str>),
/// Opening \[ without matching \].
UnmatchedLeftBrace(Location),
/// Key contains invalid characters.
///
/// The valid characters are anything outside of ASCII,
/// as well as `a`–`z`, `A`–`Z`, `0`-`9`, and each of `/.-*_`.
InvalidKey(Location, Box<str>),
/// Value contains a null character.
///
/// These are not allowed for interoperability with languages
/// with null-terminated strings (C).
InvalidValue(Location),
/// Line is not a `[section-header]` or `key = value`.
InvalidLine(Location),
/// Characters appear after a quoted value.
///
/// e.g. `key = "value" foo`
StrayCharsAfterString(Location),
/// String opened but never closed with a matching character.
UnterminatedString(Location, char),
/// Invalid escape sequence appears in a quoted value.
InvalidEscapeSequence(Location, Box<str>),
/// Key is defined twice in a file
DuplicateKey(Box<(Box<str>, Location, Location)>),
/// Used when there is more than one error in a file.
///
/// None of the errors in the array will be [`Error::Multiple`]'s,
/// and the array will contain at least two elements.
Multiple(Box<[Error]>),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
#[cfg(feature = "std")]
Self::IO(message, io_err) => write!(f, "{message}: {io_err}"),
Self::IllegalCharacter(location, c) => {
write!(f, "{location}: illegal character {c:?}")
}
Self::InvalidUtf8(location) => write!(f, "{location}: invalid UTF-8"),
Self::BadInt(location, value) => {
write!(f, "{location}: invalid integer: {value:?}")
}
Self::BadUInt(location, value) => {
write!(f, "{location}: invalid (unsigned) integer: {value:?}",)
}
Self::BadFloat(location, value) => {
write!(f, "{location}: invalid number: {value:?}")
}
Self::BadBool(location, value) => write!(
f,
"{location}: value {value:?} should be off/false/no or on/true/yes",
),
Self::UnmatchedLeftBrace(location) => write!(f, "{location}: [ has no matching ]"),
Self::InvalidKey(location, key) => {
write!(f, "{location}: invalid key {key:?}")
}
Self::InvalidValue(location) => write!(f, "{location}: value contains null characters"),
Self::InvalidLine(location) => write!(
f,
"{location}: line should either start with [ or contain ="
),
Self::StrayCharsAfterString(location) => {
write!(f, "{location}: stray characters after string value")
}
Self::UnterminatedString(location, delimiter) => {
write!(f, "{location}: missing {delimiter} to close string")
}
Self::InvalidEscapeSequence(location, sequence) => write!(
f,
"{location}: invalid escape sequence {sequence:?} (try using \\\\ instead of \\ maybe?)",
),
Self::DuplicateKey(info) => {
let (key, loc1, loc2) = info.as_ref();
write!(f, "{loc2}: key {key} was already defined at {loc1}")
}
Self::Multiple(errs) => {
let mut first = true;
for err in errs {
if !first {
writeln!(f)?;
}
first = false;
write!(f, "{err}")?;
}
Ok(())
}
}
}
}
impl core::error::Error for Error {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
#[cfg(feature = "std")]
if let Error::IO(_, e) = self {
return Some(e);
}
None
}
}
/// Type alias for [`std::result::Result`] with [`Error`] as the error.
pub type Result<T> = core::result::Result<T, Error>;
fn parse_int(location: &Location, string: &str) -> Result<i64> {
let bad_int = || Error::BadInt(location.clone(), string.into());
if !string
.bytes()
.all(|c| c.is_ascii_hexdigit() || c == b'x' || c == b'X' || c == b'-' || c == b'+')
{
return Err(bad_int());
}
let signless = string.strip_prefix(['-', '+']).unwrap_or(string);
let mut base = 10;
let baseless = signless
.strip_prefix("0x")
.or_else(|| signless.strip_prefix("0X"))
.unwrap_or_else(|| {
base = 16;
signless
});
for digit in baseless.bytes() {
if base == 10 && !digit.is_ascii_digit() {
return Err(bad_int());
}
}
string.parse().map_err(|_| bad_int())
}
fn parse_uint(location: &Location, string: &str) -> Result<u64> {
let bad_uint = || Error::BadUInt(location.clone(), string.into());
if !string
.bytes()
.all(|c| c.is_ascii_hexdigit() || c == b'x' || c == b'X' || c == b'+')
{
return Err(bad_uint());
}
let signless = string.strip_prefix('+').unwrap_or(string);
let mut base = 10;
let baseless = signless
.strip_prefix("0x")
.or_else(|| signless.strip_prefix("0X"))
.unwrap_or_else(|| {
base = 16;
signless
});
for digit in baseless.bytes() {
if base == 10 && !digit.is_ascii_digit() {
return Err(bad_uint());
}
}
let val = signless.parse().map_err(|_| bad_uint())?;
if val > i64::MAX as u64 {
return Err(bad_uint());
}
Ok(val)
}
fn parse_float(location: &Location, string: &str) -> Result<f64> {
let bad_float = || Error::BadFloat(location.clone(), string.into());
if !string.bytes().all(|c| {
c.is_ascii_digit() || c == b'.' || c == b'+' || c == b'-' || c == b'e' || c == b'E'
}) {
return Err(bad_float());
}
string.parse().map_err(|_| bad_float())
}
fn parse_bool(location: &Location, string: &str) -> Result<bool> {
match string {
"yes" | "on" | "true" => Ok(true),
"no" | "off" | "false" => Ok(false),
_ => Err(Error::BadBool(location.clone(), string.into())),
}
}
fn parse_list(string: &str) -> Vec<String> {
let mut list = vec![];
let mut item = String::new();
let mut chars = string.chars();
while let Some(c) = chars.next() {
if c == ',' {
list.push(item);
item = String::new();
} else if c == '\\' {
if let Some(next) = chars.next() {
if next == ',' || next == '\\' {
item.push(next);
} else {
item.push('\\');
item.push(next);
}
} else {
item.push('\\');
break;
}
} else {
item.push(c);
}
}
if !item.is_empty() {
list.push(item);
}
list
}
/// Trait for reading configurations.
///
/// Ordinarily you won't need to implement this trait, since it is
/// already implemented by any `T` implementing [`std::io::BufRead`] (or else `&str` and `&[u8]`,
/// if the `std` feature is not enabled).
pub trait Read {
/// Read up to the next line feed (or EOF), not including the line feed itself.
///
/// Puts the line in `line` and returns `Ok(true)`.
/// If the end of file has been reached, `line` is unmodified and `Ok(false)` is returned.
///
/// You don't need to check for valid UTF-8 here — that is already done in the code which uses
/// this trait.
fn read_until_lf(&mut self, line: &mut Vec<u8>) -> Result<bool>;
}
#[cfg(feature = "std")]
impl<R: std::io::BufRead> Read for R {
fn read_until_lf(&mut self, line: &mut Vec<u8>) -> Result<bool> {
self.read_until(b'\n', line)
.map_err(|e| Error::IO("read error".into(), e))?;
if line.ends_with(b"\n") {
line.pop();
Ok(true)
} else {
Ok(!line.is_empty())
}
}
}
#[cfg(not(feature = "std"))]
impl Read for &str {
fn read_until_lf(&mut self, line: &mut Vec<u8>) -> Result<bool> {
match self.split_once('\n') {
Some((pre, post)) => {
*self = post;
line.extend_from_slice(pre.as_bytes());
Ok(true)
}
None => {
if self.is_empty() {
return Ok(false);
}
line.extend_from_slice(self.as_bytes());
*self = "";
Ok(true)
}
}
}
}
#[cfg(not(feature = "std"))]
impl Read for &[u8] {
fn read_until_lf(&mut self, line: &mut Vec<u8>) -> Result<bool> {
match self.iter().position(|&c| c == b'\n') {
Some(i) => {
line.extend_from_slice(&self[..i]);
*self = &self[i + 1..];
Ok(true)
}
None => {
if self.is_empty() {
return Ok(false);
}
line.extend_from_slice(self);
*self = b"";
Ok(true)
}
}
}
}
fn is_illegal_byte(c: u8) -> bool {
(0..0x1f).contains(&c) && c != b'\t'
}
fn process_line(line_buf: &mut Vec<u8>, location: impl Fn() -> Location) -> Result<&str> {
line_buf.pop_if(|c| *c == b'\r');
for c in line_buf.iter() {
if is_illegal_byte(*c) {
return Err(Error::IllegalCharacter(location(), char::from(*c)));
}
}
str::from_utf8(line_buf).map_err(|_| Error::InvalidUtf8(location()))
}
fn parse_hex_digit(c: char) -> Option<u32> {
Some(match c {
'0'..='9' => (c as u32) - ('0' as u32),
'a'..='f' => (c as u32) - ('a' as u32) + 10,
'A'..='F' => (c as u32) - ('A' as u32) + 10,
_ => return None,
})
}
#[derive(Default)]
struct Parser {
nonfatal_errors: Vec<Error>,
}
impl Parser {
fn check_valid_key(&mut self, location: &Location, s: &str) {
if s.is_empty()
|| s.starts_with('.')
|| s.ends_with('.')
|| s.contains("..")
|| !s.bytes().all(|c| {
c >= 0x80
|| c.is_ascii_alphanumeric()
|| matches!(c, b'.' | b'_' | b'/' | b'*' | b'-')
}) {
self.nonfatal_errors
.push(Error::InvalidKey(location.clone(), s.into()));
}
}
fn parse_escape_sequence(
&mut self,
chars: &mut core::str::Chars,
value: &mut String,
location: impl Fn() -> Location,
) {
let invalid_escape = |s: String| Error::InvalidEscapeSequence(location(), s.into());
let Some(c) = chars.next() else {
self.nonfatal_errors
.push(invalid_escape("\\(newline)".into()));
return;
};
match c {
'n' => value.push('\n'),
'r' => value.push('\r'),
't' => value.push('\t'),
'\\' | '\'' | '"' | '`' => value.push(c),
',' => value.push_str("\\,"),
'x' => {
let Some(c1) = chars.next() else {
self.nonfatal_errors.push(invalid_escape("\\x".into()));
return;
};
let Some(c2) = chars.next() else {
self.nonfatal_errors
.push(invalid_escape(format!("\\x{c1}")));
return;
};
let (Some(nibble1), Some(nibble2)) = (parse_hex_digit(c1), parse_hex_digit(c2))
else {
self.nonfatal_errors
.push(invalid_escape(format!("\\x{c1}{c2}")));
return;
};
let char_code = nibble1 << 4 | nibble2;
if char_code == 0 {
self.nonfatal_errors.push(Error::InvalidValue(location()));
}
if char_code >= 0x80 {
self.nonfatal_errors
.push(invalid_escape(format!("\\x{c1}{c2}")));
}
value.push(char::try_from(char_code).unwrap());
}
'u' => {
let mut c = chars.next();
if c != Some('{') {
self.nonfatal_errors.push(invalid_escape("\\u".into()));
return;
}
let mut code = 0u32;
for i in 0..7 {
c = chars.next();
if i == 6 {
break;
}
let Some(c) = c else {
break;
};
if c == '}' {
break;
}
code <<= 4;
let Some(digit) = parse_hex_digit(c) else {
self.nonfatal_errors
.push(invalid_escape(format!("\\u{{{code:x}{c}")));
return;
};
code |= digit;
}
if c != Some('}') {
self.nonfatal_errors
.push(invalid_escape("\\u{ has no matching }".into()));
return;
}
if code == 0 {
self.nonfatal_errors.push(Error::InvalidValue(location()));
}
let Ok(c) = char::try_from(code) else {
self.nonfatal_errors
.push(invalid_escape(format!("\\u{{{code:x}}}")));
return;
};
value.push(c);
}
_ => {
self.nonfatal_errors.push(invalid_escape(format!("\\{c}")));
}
}
}
/// Returns (unquoted value, new line number)
fn read_quoted_value(
&mut self,
quoted: &str,
reader: &mut dyn Read,
start_location: &Location,
) -> Result<(String, u64)> {
let delimiter: char = quoted.chars().next().unwrap();
let mut unquoted = String::new();
let mut line_number = start_location.line;
let location = |line_number: u64| Location {
file: start_location.file.clone(),
line: line_number,
};
let mut line_buf = vec![];
let mut first = true;
loop {
let line = if first {
first = false;
"ed[1..]
} else {
line_buf.truncate(0);
if !reader.read_until_lf(&mut line_buf)? {
break;
}
line_number += 1;
process_line(&mut line_buf, || location(line_number))?
};
let mut chars = line.chars();
while let Some(c) = chars.next() {
if c == delimiter {
if !chars.all(|c| c == ' ' || c == '\t') {
self.nonfatal_errors
.push(Error::StrayCharsAfterString(location(line_number)));
}
return Ok((unquoted, line_number));
} else if c == '\\' {
self.parse_escape_sequence(&mut chars, &mut unquoted, || location(line_number));
} else if c == '\0' {
self.nonfatal_errors
.push(Error::InvalidValue(location(line_number)));
} else {
unquoted.push(c);
}
}
unquoted.push('\n');
}
Err(Error::UnterminatedString(start_location.clone(), delimiter))
}
fn load(&mut self, filename: &str, reader: &mut dyn Read) -> Result<Configuration> {
let mut items: Vec<(Box<str>, Value)> = vec![];
let mut line: Vec<u8> = vec![];
let mut line_number: u64 = 0;
let mut current_section = String::new();
let filename: Arc<str> = filename.into();
loop {
line.truncate(0);
if !reader.read_until_lf(&mut line)? {
break;
}
if line_number == 0 && line.starts_with(b"\xEF\xBB\xBF") {
line.drain(..3);
}
line_number += 1;
let location = Location {
file: filename.clone(),
line: line_number,
};
let mut line = process_line(&mut line, || location.clone())?;
line = line.trim_start_matches(['\t', ' ']);
if line.is_empty() || line.starts_with('#') {
// comment/blank line
continue;
}
if line.starts_with('[') {
// [section.header]
line = line.trim_end_matches(['\t', ' ']);
if !line.ends_with(']') {
return Err(Error::UnmatchedLeftBrace(location));
}
current_section = line[1..line.len() - 1].into();
if !current_section.is_empty() {
self.check_valid_key(&location, ¤t_section);
}
} else {
// key = value
let (mut relative_key, mut value) = line
.split_once('=')
.ok_or_else(|| Error::InvalidLine(location.clone()))?;
relative_key = relative_key.trim_end_matches(['\t', ' ']);
self.check_valid_key(&location, relative_key);
let key: String = if current_section.is_empty() {
relative_key.into()
} else {
format!("{current_section}.{relative_key}")
};
value = value.trim_start_matches(['\t', ' ']);
if value.starts_with(['`', '"']) {
let (value, new_line_number) =
self.read_quoted_value(value, reader, &location)?;
items.push((
key.into(),
Value {
value: value.into(),
defined_at: location,
},
));
line_number = new_line_number;
} else {
value = value.trim_end_matches(['\t', ' ']);
if value.contains('\0') {
return Err(Error::InvalidValue(location));
}
items.push((
key.into(),
Value {
value: value.into(),
defined_at: location,
},
));
}
}
}
items.sort_by(|(k1, _), (k2, _)| k1.cmp(k2));
for window in items.windows(2) {
if window[0].0 == window[1].0 {
// duplicate key
self.nonfatal_errors.push(Error::DuplicateKey(Box::new((
window[0].0.clone(),
window[0].1.defined_at.clone(),
window[1].1.defined_at.clone(),
))));
}
}
match self.nonfatal_errors.len() {
0 => Ok(Configuration { items }),
1 => Err(self.nonfatal_errors.pop().unwrap()),
2.. => Err(Error::Multiple(take(&mut self.nonfatal_errors).into())),
}
}
}
impl Configuration {
/// Load a configuration.
///
/// `reader` can be `&str`, `&[u8]`, or anything that implements [`std::io::BufRead`]
/// (if the `std` feature is enabled) such as `std::io::BufReader<std::fs::File>`.
///
/// `filename` is used in error messages.
pub fn load<R: Read>(filename: &str, mut reader: R) -> Result<Self> {
// avoid big code size by using dyn reference.
// the impact on performance is not really important.
Parser::default().load(filename, &mut reader)
}
/// Load a configuration from a file path.
#[cfg(feature = "std")]
pub fn load_path<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
let p = path.as_ref();
let filename = p.to_string_lossy();
let file = std::fs::File::open(p).map_err(|e| Error::IO(filename.clone().into(), e))?;
Configuration::load(&filename, std::io::BufReader::new(file))
}
/// Binary search `self.items`.
///
/// See [`std::slice::binary_search_by`].
fn binary_search_for(&self, key: &str) -> core::result::Result<usize, usize> {
self.items.binary_search_by(|(k, _)| k.as_ref().cmp(key))
}
/// Returns the index of the first key which is greater than `key` + "."
fn subkey_start_idx(&self, key: &str) -> usize {
let key_dot = format!("{key}.");
self.binary_search_for(&key_dot)
.expect_err("items should not contain a key ending in .")
}
/// Returns the index of the first key which is greater than `key` + "." + `x` for all strings `x`.
fn subkey_end_idx(&self, key: &str) -> usize {
// NB: / is the next ASCII character after .
let key_slash = format!("{key}/");
self.binary_search_for(&key_slash).unwrap_or_else(|x| x)
}
/// Extract a section out of a configuration.
///
/// More specifically, this will give you the configuration consisting of all
/// keys starting with `key.` in `self`, together with their values.
#[must_use]
pub fn section(&self, key: &str) -> Configuration {
let start_idx = self.subkey_start_idx(key);
let end_idx = self.subkey_end_idx(key);
Configuration {
items: self.items[start_idx..end_idx].to_owned(),
}
}
/// Get all “direct keys” in this configuration.
///
/// More specifically, this returns an iterator of all unique
/// first components of keys in `self`.
///
/// (So if there were keys `sheep.age`, `sheep.colour`, and `farmer-name`,
/// this would give an iterator yielding
/// `"farmer-name"` and `"sheep"` in some order.)
///
/// The order of items returned is arbitrary and may change
/// in future versions without notice.
pub fn keys(&self) -> impl '_ + Iterator<Item = &str> {
let mut prev = None;
self.items.iter().filter_map(move |(key, _)| {
let first_component: &str = key.split_once('.').map_or(key.as_ref(), |(c, _)| c);
if prev == Some(first_component) {
return None;
}
prev = Some(first_component);
Some(first_component)
})
}
/// Get all defined keys in this configuration, including nested ones,
/// and their values.
///
/// The order of items returned is arbitrary and may change
/// in future versions without notice.
pub fn iter(&self) -> ConfigurationIter<'_> {
self.into_iter()
}
/// Get the list of all “direct children” of `key` in this configuration.
///
/// More specifically, this returns an iterator of all unique
/// (*n*+1)th components of keys in `self` whose first *n* components
/// are equal to `key` (where `key` has *n* components).
///
/// (So if there were keys `sheep.age`, `sheep.colour`, and `sheep.age.unit`,
/// `subkeys("sheep")` would give an iterator yielding
/// `"age"` and `"colour"` in some order.)
///
/// The order of items returned is arbitrary and may change
/// in future versions without notice.
pub fn subkeys(&self, key: &str) -> impl '_ + Iterator<Item = &str> {
let key_dot = format!("{key}.");
let start_idx = self.subkey_start_idx(key);
(start_idx..self.items.len()).map_while(move |i| {
let this_key = &self.items[i].0;
let suffix = this_key.strip_prefix(&key_dot)?;
Some(suffix.split_once('.').map_or(suffix, |(x, _)| x))
})
}
fn get_val(&self, key: &str) -> Option<&Value> {
let idx = self.binary_search_for(key).ok()?;
Some(&self.items[idx].1)
}
/// Get value associated with `key`, if any.
#[must_use]
pub fn get(&self, key: &str) -> Option<&str> {
Some(self.get_val(key)?.value.as_ref())
}
/// Get location in the configuration file where `key` is defined, if any.
#[must_use]
pub fn location(&self, key: &str) -> Option<Location> {
if let Some(val) = self.get_val(key) {
Some(val.defined_at.clone())
} else {
// Check if `key` has any defined subkeys
let start_idx = self.subkey_start_idx(key);
let (subkey, subval) = self.items.get(start_idx)?;
if subkey.starts_with(key) && subkey[key.len()..].starts_with('.') {
Some(subval.defined_at.clone())
} else {
None
}
}
}
/// Returns `true` if `key` is defined in this configuration.
#[must_use]
pub fn has(&self, key: &str) -> bool {
self.get(key).is_some()
}
/// Get value associated with `key`, or else use `default` if it isn't defined.
#[must_use]
pub fn get_or_default<'a>(&'a self, key: &str, default: &'a str) -> &'a str {
self.get(key).unwrap_or(default)
}
/// Get value associated with `key`, and parse it as an integer.
///
/// Returns `None` if `key` is not defined,
/// and `Some(Err(…))` if `key` is defined but not an integer.
#[must_use]
pub fn get_int(&self, key: &str) -> Option<Result<i64>> {
let Value { value, defined_at } = self.get_val(key)?;
Some(parse_int(defined_at, value.as_ref()))
}
/// Get value associated with `key`, and parse it as an integer, or else use `default`.
///
/// Returns `Err(…)` if `key` is defined but not an integer.
pub fn get_int_or_default(&self, key: &str, default: i64) -> Result<i64> {
self.get_int(key).unwrap_or(Ok(default))
}
/// Get value associated with `key`, and parse it as an unsigned integer.
///
/// Returns `None` if `key` is not defined,
/// and `Some(Err(…))` if `key` is defined but not an unsigned integer.
#[must_use]
pub fn get_uint(&self, key: &str) -> Option<Result<u64>> {
let Value { value, defined_at } = self.get_val(key)?;
Some(parse_uint(defined_at, value.as_ref()))
}
/// Get value associated with `key`, and parse it as an unsinged integer, or else use `default`.
///
/// Returns `Err(…)` if `key` is defined but not an unsigned integer.
pub fn get_uint_or_default(&self, key: &str, default: u64) -> Result<u64> {
self.get_uint(key).unwrap_or(Ok(default))
}
/// Get value associated with `key`, and parse it as a float.
///
/// Returns `None` if `key` is not defined,
/// and `Some(Err(…))` if `key` is defined but not a float.
#[must_use]
pub fn get_float(&self, key: &str) -> Option<Result<f64>> {
let Value { value, defined_at } = self.get_val(key)?;
Some(parse_float(defined_at, value.as_ref()))
}
/// Get value associated with `key`, and parse it as a float, or else use `default`.
///
/// Returns `Err(…)` if `key` is defined but not a float.
pub fn get_float_or_default(&self, key: &str, default: f64) -> Result<f64> {
self.get_float(key).unwrap_or(Ok(default))
}
/// Get value associated with `key`, and parse it as a boolean.
///
/// Returns `None` if `key` is not defined,
/// and `Some(Err(…))` if `key` is defined but not equal to one of
/// `off`, `no`, `false`, `on`, `yes`, `true`.
#[must_use]
pub fn get_bool(&self, key: &str) -> Option<Result<bool>> {
let Value { value, defined_at } = self.get_val(key)?;
Some(parse_bool(defined_at, value.as_ref()))
}
/// Get value associated with `key`, and parse it as a boolean, or else use `default`.
///
/// Returns `Err(…)` if `key` is defined but not equal to one of
/// `off`, `no`, `false`, `on`, `yes`, `true`.
pub fn get_bool_or_default(&self, key: &str, default: bool) -> Result<bool> {
self.get_bool(key).unwrap_or(Ok(default))
}
/// Get value associated with `key`, and parse it as a comma-separated list.
///
/// Commas in list entries can be escaped with `\,`.
#[must_use]
pub fn get_list(&self, key: &str) -> Option<Vec<String>> {
let value = &self.get_val(key)?.value;
Some(parse_list(value.as_ref()))
}
/// Get value associated with `key`, and parse it as a comma-separated list, or else use `default`.
///
/// Commas in list entries can be escaped with `\,`.
///
/// `default` can be anything that can be converted into an iterator of strings,
/// e.g. `Vec<&str>`, `Vec<String>`, `&[&str]`, etc.
pub fn get_list_or_default<L>(&self, key: &str, default: L) -> Vec<String>
where
L: IntoIterator,
L::Item: AsRef<str>,
{
self.get_list(key)
.unwrap_or_else(|| default.into_iter().map(|s| s.as_ref().to_owned()).collect())
}
/// Merge `conf` into `self`, preferring values in `conf`.
pub fn merge(&mut self, conf: &Configuration) {
let mut must_sort = false;
for (key, value) in &conf.items {
if let Ok(i) = self.binary_search_for(key) {
self.items[i].1 = value.clone();
} else {
self.items.push((key.clone(), value.clone()));
must_sort = true;
}
}
if must_sort {
self.items.sort_by(|(k1, _), (k2, _)| k1.cmp(k2));
}
}
/// Check that `self` follows the given schema.
///
/// See the [POM specification](https://www.pom.computer/spec.html) for a description
/// of schemas.
pub fn check_against_schema(&self, schema: &Configuration) -> Result<()> {
_ = schema;
todo!()
}
}
/// Opaque type returned by [`<&Configuration>::into_iter`].
#[derive(Clone, Debug)]
pub struct ConfigurationIter<'a>(core::slice::Iter<'a, (Box<str>, Value)>);
impl<'a> Iterator for ConfigurationIter<'a> {
type Item = (&'a str, &'a str);
fn next(&mut self) -> Option<Self::Item> {
let (key, val) = self.0.next()?;
Some((key, val.value.as_ref()))
}
}
impl<'a> IntoIterator for &'a Configuration {
type IntoIter = ConfigurationIter<'a>;
type Item = (&'a str, &'a str);
/// See [`Configuration::iter`].
fn into_iter(self) -> Self::IntoIter {
ConfigurationIter(self.items.iter())
}
}
|