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
use crate::{
InnerError, ParseType, ParsedArgs, ParsedEnv, ProgramOption,
introspection::{ConfigLogger, ValueSource as PublicValueSource},
str_to_bool,
};
use clap::parser::ValueSource;
use core::fmt::Debug;
use std::{
cell::RefCell,
ffi::{OsStr, OsString},
};
// Data about the source of a value returned by ConfContext functions
// This is mainly used to render help if something fails in the value parser later
// It is generic over a string type so that it can accommodate owned and borrowed data.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum ConfValueSource<S>
where
S: Clone + Debug + Eq + PartialEq + Ord + PartialOrd,
{
Args,
Env(S),
Document(S),
Default,
}
impl ConfValueSource<&str> {
pub fn into_owned(self) -> ConfValueSource<String> {
match self {
Self::Args => ConfValueSource::Args,
Self::Env(s) => ConfValueSource::Env(s.to_owned()),
Self::Document(s) => ConfValueSource::Document(s.to_owned()),
Self::Default => ConfValueSource::Default,
}
}
pub fn is_default(&self) -> bool {
matches!(self, Self::Default)
}
/// Convert to the public ValueSource type used in introspection
pub fn to_public_value_source(&self) -> PublicValueSource<'_> {
match self {
Self::Args => PublicValueSource::Args {},
Self::Env(var) => PublicValueSource::Env { var },
Self::Document(name) => PublicValueSource::Document { name },
Self::Default => PublicValueSource::Default {},
}
}
}
impl From<ValueSource> for ConfValueSource<&str> {
fn from(src: ValueSource) -> Self {
match &src {
ValueSource::CommandLine => Self::Args,
ValueSource::DefaultValue => Self::Default,
ValueSource::EnvVariable => unreachable!("clap should not be parsing env here"),
_ => panic!("this is an unknown value source from clap: {src:?}"),
}
}
}
// Data stored when we start parsing a flattened-optional field.
// This is used in error messages about why a field became required.
#[doc(hidden)]
#[derive(Clone, Debug)]
pub(crate) struct FlattenedOptionalDebugInfo<'a> {
pub struct_name: &'static str,
pub id_prefix: String,
pub option_appeared: &'a ProgramOption,
pub value_source: ConfValueSource<&'a str>,
}
// Conf context stores everything that is needed to figure out if a user-defined
// program option in a (possibly flattened) struct was specified, and what string
// value to parse if so.
// It stores the results of CLI argument parsing, the env, and any prefixing
// that has been applied to the context so far.
// It provides getters which take care of the prefixing, aliases, etc.
// so that the generated code doesn't have to.
//
// Many of the APIs which take an id (or list of ids) will panic if the id is not found.
// This is okay because this is not a user facing object, and it's okay to panic for internal logic
// errors like that.
#[doc(hidden)]
pub struct ConfContext<'a> {
args: ParsedArgs<'a>,
env: &'a ParsedEnv,
program_options: &'a [ProgramOption],
id_prefix: String,
flattened_optional_debug_info: Option<FlattenedOptionalDebugInfo<'a>>,
config_logger: Option<&'a RefCell<ConfigLogger<'a>>>,
pub(crate) serde_source_is_present: bool,
}
impl<'a> ConfContext<'a> {
pub(crate) fn new(
args: ParsedArgs<'a>,
env: &'a ParsedEnv,
program_options: &'a [ProgramOption],
config_logger: Option<&'a RefCell<ConfigLogger<'a>>>,
) -> Self {
Self {
args,
env,
program_options,
id_prefix: String::default(),
flattened_optional_debug_info: None,
config_logger,
serde_source_is_present: false,
}
}
/// Get a program option by its ID (will prepend the context's id_prefix)
#[doc(hidden)]
pub fn get_program_option_by_id(&self, id: &str) -> Option<&ProgramOption> {
let full_id = self.id_prefix.clone() + id;
self.args.get_program_option(&full_id)
}
fn get_env_os(&self, env_name: &'a str) -> Option<&'a OsStr> {
self.env
.get(env_name)
.map(|os_string| os_string.as_os_str())
}
fn get_env(
&self,
env_name: &'a str,
opt: &'a ProgramOption,
) -> Result<Option<&'a str>, InnerError> {
if let Some(val) = self.get_env_os(env_name) {
return Ok(Some(val.to_str().ok_or_else(|| {
if opt.is_secret() {
InnerError::invalid_utf8_env(env_name, opt, None)
} else {
InnerError::invalid_utf8_env(env_name, opt, self.env.get(env_name))
}
})?));
}
Ok(None)
}
/// Check if a boolean program option was set to true, using any of its aliases or env value
pub fn get_boolean_opt(
&self,
id: &str,
) -> Result<(ConfValueSource<&'a str>, bool), InnerError> {
let id = self.id_prefix.clone() + id;
if self.args.arg_matches.get_flag(&id) {
return Ok((ConfValueSource::<&'a str>::Args, true));
}
let opt = self.args.get_program_option(&id).unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({id}), this is an internal_error. Available IDs: {available:?}")
});
if let Some(env_form) = opt.env_form.as_deref() {
if let Some(val) = self.get_env(env_form, opt)? {
return Ok((ConfValueSource::<&'a str>::Env(env_form), str_to_bool(val)));
}
}
Ok((ConfValueSource::Default, false))
}
/// Get a program option if it was set, using any of its aliases or env value.
/// Returns the value as OsStr to preserve non-UTF-8 data from command-line arguments.
/// Returns an error if it was set multiple times via args. If args and env are set, args
/// shadows env.
#[allow(clippy::type_complexity)]
pub fn get_osstring_opt(
&self,
id: &str,
) -> Result<
(
Option<(ConfValueSource<&'a str>, &'a OsStr)>,
&'a ProgramOption,
),
InnerError,
> {
let id = self.id_prefix.clone() + id;
let opt = self.args.get_program_option(&id).unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({id}), this is an internal_error. Available IDs: {available:?}")
});
if opt.has_args_source() {
if let Some(val_os) = self.args.arg_matches.get_one::<OsString>(&id) {
let value_source = self
.args
.arg_matches
.value_source(&id)
.expect("Id not found, this is an internal error");
// Note: We don't support user-defined default value on this one right now, and we
// don't give default values to clap so this should be the only possibility
assert_eq!(value_source, ValueSource::CommandLine);
let val_and_source = Some((value_source.into(), val_os.as_os_str()));
// Args take precedence over env, so return now if we got args.
return Ok((val_and_source, opt));
}
}
for env_form in opt.env_form.iter().chain(opt.env_aliases.iter()) {
if let Some(val) = self.get_env_os(env_form) {
let value_source = ConfValueSource::<&str>::Env(env_form);
let val_and_source = Some((value_source, val));
return Ok((val_and_source, opt));
}
}
// Note: default values are NOT returned here. The proc-macro generates the fallback
// to default logic in the initializer code, not ConfContext.
Ok((None, opt))
}
/// Get a string program option if it was set, using any of its aliases or env value.
/// Returns the value as &str. If the value from command-line arguments contains invalid UTF-8,
/// returns an error.
/// Returns an error if it was set multiple times via args. If args and env are set, args
/// shadows env.
#[allow(clippy::type_complexity)]
pub fn get_string_opt(
&self,
id: &str,
) -> Result<
(
Option<(ConfValueSource<&'a str>, &'a str)>,
&'a ProgramOption,
),
InnerError,
> {
let (maybe_val, opt) = self.get_osstring_opt(id)?;
if let Some((value_source, val_os)) = maybe_val {
// Convert OsStr to str, handling UTF-8 errors
let val_str = val_os.to_str().ok_or_else(|| {
InnerError::invalid_value_os(value_source, val_os, opt, "Invalid UTF-8")
})?;
Ok((Some((value_source, val_str)), opt))
} else {
Ok((None, opt))
}
}
/// Get a repeat program option if it was set, using any of its aliases.
/// Returns values as OsStr to preserve non-UTF-8 data from command-line arguments.
/// No delimiter parsing is performed for env values - they are returned as a single value.
/// If args and env are set, args shadows env.
/// NOTE: This should only be used when value_parser_os is specified. Otherwise use get_repeat_opt.
#[allow(clippy::type_complexity)]
pub fn get_repeat_osstring_opt(
&self,
id: &str,
env_delimiter: Option<char>,
) -> Result<
(
Option<(ConfValueSource<&'a str>, Vec<&'a OsStr>)>,
&'a ProgramOption,
),
InnerError,
> {
let id = self.id_prefix.clone() + id;
let opt = self.args.get_program_option(&id).unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({id}), this is an internal_error. Available IDs: {available:?}")
});
// Only try to access arg_matches if this option has a short or long form, or is positional.
// Options with only env (no short/long/positional) are not registered with clap.
if opt.has_args_source() {
if let Some(val_os) = self.args.arg_matches.get_many::<OsString>(&id) {
let value_source = self
.args
.arg_matches
.value_source(&id)
.expect("Id not found, this is an internal error");
// Note: We don't support user-defined default value on this one right now, and we don't
// give default values to clap so this should be the only possibility
assert_eq!(value_source, ValueSource::CommandLine);
// Return as OsStr, no conversion to str
let results: Vec<&'a OsStr> = val_os.map(|os| os.as_os_str()).collect();
return Ok((Some((value_source.into(), results)), opt));
}
}
for env_form in opt.env_form.iter().chain(opt.env_aliases.iter()) {
if let Some(val) = self.get_env_os(env_form) {
let value_source = ConfValueSource::<&str>::Env(env_form);
return Ok(if let Some(delim) = env_delimiter {
(Some((value_source, split_osstr(val, delim).collect())), opt)
} else {
(Some((value_source, vec![val])), opt)
});
}
}
// Note: default values are NOT returned here. The proc-macro generates the fallback
// to default logic in the initializer code, not ConfContext.
Ok((None, opt))
}
/// Get a repeat program option if it was set, using any of its aliases.
/// Returns values as &str. If any value from command-line arguments contains invalid UTF-8,
/// returns an error.
/// If env is set, env is parsed via the delimiter (char), if a delimiter is provided.
/// If args and env are set, args shadows env.
#[allow(clippy::type_complexity)]
pub fn get_repeat_opt(
&self,
id: &str,
env_delimiter: Option<char>,
) -> Result<
(
Option<(ConfValueSource<&'a str>, Vec<&'a str>)>,
&'a ProgramOption,
),
InnerError,
> {
let id = self.id_prefix.clone() + id;
let opt = self.args.get_program_option(&id).unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({id}), this is an internal_error. Available IDs: {available:?}")
});
// Only try to access arg_matches if this option has a short or long form, or is positional.
// Options with only env (no short/long/positional) are not registered with clap.
if opt.has_args_source() {
if let Some(val_os) = self.args.arg_matches.get_many::<OsString>(&id) {
let value_source = self
.args
.arg_matches
.value_source(&id)
.expect("Id not found, this is an internal error");
// Note: We don't support user-defined default value on this one right now, and we don't
// give default values to clap so this should be the only possibility
assert_eq!(value_source, ValueSource::CommandLine);
// Convert each OsStr to str, handling UTF-8 errors
let strs: Result<Vec<&'a str>, InnerError> = val_os
.map(|os| {
os.to_str().ok_or_else(|| {
InnerError::invalid_value_os(
value_source.into(),
os.as_os_str(),
opt,
"Invalid UTF-8",
)
})
})
.collect();
return Ok((Some((value_source.into(), strs?)), opt));
}
}
for env_form in opt.env_form.iter().chain(opt.env_aliases.iter()) {
if let Some(val) = self.get_env_os(env_form) {
let value_source = ConfValueSource::<&str>::Env(env_form);
// Convert to str for delimiter splitting
let val_str = val.to_str().ok_or_else(|| {
InnerError::invalid_utf8_env(env_form, opt, self.env.get(env_form))
})?;
return Ok(if let Some(delim) = env_delimiter {
// Split by delimiter
(Some((value_source, val_str.split(delim).collect())), opt)
} else {
// Return as single value
(Some((value_source, vec![val_str])), opt)
});
}
}
// Note: default values are NOT returned here. The proc-macro generates the fallback
// to default logic in the initializer code, not ConfContext.
Ok((None, opt))
}
/// Check if a given option appears in cli args or env (not defaulted)
/// The id should be relative to this context's prefix.
/// This is used to implement any_program_options_appeared which supports flatten-optional
pub fn option_appears(&self, id: &str) -> Result<Option<ConfValueSource<&'a str>>, InnerError> {
if let Some(value_source) = self.get_value_source(id)? {
Ok(match value_source {
ConfValueSource::Default => None,
other => Some(other),
})
} else {
Ok(None)
}
}
/// Returns the value source of a given program option id (relative to our prefix), if it has a
/// value
fn get_value_source(&self, id: &str) -> Result<Option<ConfValueSource<&'a str>>, InnerError> {
let prefixed_id = self.id_prefix.clone() + id;
let opt = self
.args
.get_program_option(&prefixed_id)
.unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({prefixed_id}), this is an internal_error. Available IDs: {available:?}")
});
Ok(match opt.parse_type {
ParseType::Flag => {
let (src, _val) = self.get_boolean_opt(id)?;
Some(src)
}
ParseType::Parameter => {
let (maybe, _opt) = self.get_string_opt(id)?;
maybe.map(|(src, _val)| src)
}
ParseType::Repeat => {
// Hack: don't supply delimiter char even if it exists, since it won't matter for
// this function
let (maybe, _opt) = self.get_repeat_opt(id, None)?;
maybe.map(|(src, _val)| src)
}
})
}
/// Create a new context from self, for use with a flattened substructure.
///
/// Pass the id prefix that the substructure was configured with.
/// That prefix will be concatenated to the prefixes already stored in this context.
#[inline]
pub fn for_flattened(&self, sub_id_prefix: &str) -> ConfContext<'a> {
ConfContext {
args: self.args.clone(),
env: self.env,
program_options: self.program_options,
id_prefix: self.id_prefix.clone() + sub_id_prefix,
flattened_optional_debug_info: self.flattened_optional_debug_info.clone(),
config_logger: self.config_logger,
serde_source_is_present: self.serde_source_is_present,
}
}
/// Create a new context from self, for use with a flattened-optional substructure.
///
/// This preserves context about what optional group we are entering, and why it was enabled,
/// for error messages.
#[inline]
pub fn for_flattened_optional(
&self,
sub_id_prefix: &str,
struct_name: &'static str,
option_appeared_result: (&str, ConfValueSource<&'a str>),
) -> ConfContext<'a> {
let id_prefix = self.id_prefix.clone() + sub_id_prefix;
let (option_appeared_absolute_id, value_source) = option_appeared_result;
let option_appeared = self
.args
.get_program_option(option_appeared_absolute_id)
.unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({option_appeared_absolute_id}), this is an internal_error. Available IDs: {available:?}")
});
let flattened_optional_debug_info = Some(FlattenedOptionalDebugInfo {
struct_name,
id_prefix: id_prefix.clone(),
option_appeared,
value_source,
});
ConfContext {
args: self.args.clone(),
env: self.env,
program_options: self.program_options,
id_prefix,
flattened_optional_debug_info,
config_logger: self.config_logger,
serde_source_is_present: self.serde_source_is_present,
}
}
/// Create a new context from self, for parsing subcommand objects, if clap found a subcommand.
#[inline]
pub fn for_subcommand(&self) -> Option<(String, ConfContext<'a>)> {
self.args.get_subcommand().map(|(name, args)| {
(
name,
ConfContext {
args,
env: self.env,
program_options: self.program_options,
id_prefix: self.id_prefix.clone(),
flattened_optional_debug_info: self.flattened_optional_debug_info.clone(),
config_logger: self.config_logger,
serde_source_is_present: self.serde_source_is_present,
},
)
})
}
/// Get the id prefix of this conf context
pub fn get_id_prefix(&self) -> &str {
&self.id_prefix
}
/// Get all program options that are relevant to this context (i.e., whose id starts with the current prefix)
/// Returns tuples of (relative_id, program_option) where relative_id has the prefix stripped
pub fn get_relevant_program_options(
&self,
) -> impl Iterator<Item = (&'a str, &'a ProgramOption)> {
let prefix = &self.id_prefix;
self.program_options.iter().filter_map(move |opt| {
opt.id
.strip_prefix(prefix)
.map(|relative_id| (relative_id, opt))
})
}
/// Generate a "missing_required_parameter" error
///
/// This error includes context if we are within a flattened optional group
pub fn missing_required_parameter_error(&self, opt: &ProgramOption) -> InnerError {
InnerError::missing_required_parameter(
opt,
self.flattened_optional_debug_info.clone(),
self.serde_source_is_present,
)
}
/// Generate a "too_few_arguments" error
///
/// This should contain the ids of all "single options" in this constraint, as well as all
/// flattened options in this constraint. This error includes context if we are within a
/// flattened optional group
pub fn too_few_arguments_error(
&self,
struct_name: &'static str,
constraint_single_option_ids: &[&str],
constraint_flattened_ids: &[&str],
) -> InnerError {
let single_options = constraint_single_option_ids
.iter()
.map(|id| {
let prefixed_id = self.id_prefix.clone() + id;
self.args
.get_program_option(&prefixed_id)
.unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({prefixed_id}), this is an internal_error. Available IDs: {available:?}")
})
})
.collect::<Vec<&ProgramOption>>();
InnerError::too_few_arguments(
struct_name,
&self.id_prefix,
single_options,
constraint_flattened_ids,
self.flattened_optional_debug_info.clone(),
self.serde_source_is_present,
)
}
/// Generate a "too_many_arguments" error
///
/// To use this function correctly, constraint_single_option_ids can be the relative id of any
/// field in the constraint. (So, it's field name on the current struct.) Whether or not
/// that one actually appeared and is contributing to the error, `ConfContext` will figure that
/// out, and filter out any that shouldn't be in the error report.
///
/// constraint_flattened_ids should include the id of the flattened optional struct contributing
/// to the error, and the result of Conf::any_program_options_appeared on the inner struct.
/// This includes enough detail to render an error for at least one option that enabled that
/// flattened optional struct. If the result is None then conf context will filter that out, so
/// that the proc macro doesn't have to.
#[allow(clippy::type_complexity)]
pub fn too_many_arguments_error(
&self,
struct_name: &'static str,
constraint_single_option_ids: &[&str],
constraint_flattened_ids: Vec<(&str, Option<(&str, ConfValueSource<&'a str>)>)>,
) -> InnerError {
let single_options = constraint_single_option_ids
.iter()
.filter_map(|id| {
let prefixed_id = self.id_prefix.clone() + id;
let opt = self
.args
.get_program_option(&prefixed_id)
.unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({prefixed_id}), this is an internal_error. Available IDs: {available:?}")
});
self.get_value_source(id)
.expect("internal error")
.and_then(|value_source| {
if matches!(&value_source, ConfValueSource::Default) {
None
} else {
Some((opt, value_source))
}
})
})
.collect::<Vec<(&ProgramOption, ConfValueSource<&'a str>)>>();
let flattened_options = constraint_flattened_ids
.into_iter()
.filter_map(|(flattened_field, maybe_appearing_option)| {
maybe_appearing_option.map(|(absolute_id, value_source)| {
let opt = self
.args
.get_program_option(absolute_id)
.unwrap_or_else(|| {
panic!(
"Option not found by id ({absolute_id}), this is an internal_error"
)
});
(flattened_field, opt, value_source)
})
})
.collect::<Vec<(&str, &ProgramOption, ConfValueSource<&'a str>)>>();
InnerError::too_many_arguments(
struct_name,
&self.id_prefix,
single_options,
flattened_options,
)
}
/// Log a configuration event to the config logger if one is present.
/// This should be called when a leaf field (flag, parameter, or repeat) is successfully initialized.
pub fn log_config_event(&self, id: &str, value_source: ConfValueSource<&str>) {
if let Some(logger_cell) = self.config_logger {
let id = self.id_prefix.clone() + id;
let opt = self.args.get_program_option(&id).unwrap_or_else(|| {
let available = self.args.get_available_ids();
panic!("Option not found by id ({id}), this is an internal error. Available IDs: {available:?}")
});
// Create a config event implementation
struct ConfigEventImpl<'a> {
option: &'a ProgramOption,
value_source: ConfValueSource<&'a str>,
}
impl<'a> crate::introspection::Sealed for ConfigEventImpl<'a> {}
impl<'a> crate::introspection::ConfigEvent for ConfigEventImpl<'a> {
fn program_option(&self) -> &dyn crate::introspection::ProgramOptionMeta {
self.option
}
fn value_source(&self) -> PublicValueSource<'_> {
self.value_source.to_public_value_source()
}
}
let event = ConfigEventImpl {
option: opt,
value_source,
};
logger_cell.borrow_mut()(&event);
}
}
}
#[allow(unsafe_code)]
fn split_osstr(s: &OsStr, delim: char) -> impl Iterator<Item = &OsStr> {
assert!(
delim.is_ascii(),
"when splitting OsStr, the delimiter must be ascii if present"
);
let delim = delim as u8;
// SAFETY:
// Because delim is ASCII, it is encoded uniquely as 1 byte, in UTF-8 and WTF-8, and any
// self-synchronizing superset of ASCII.
// Therefore if we see a byte matching `delim` within `s`, and `s` is well-formed, then
// the split of s at that byte must also be well-formed.
//
// See also docu and examples here:
// https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.from_encoded_bytes_unchecked
s.as_encoded_bytes()
.split(move |b| *b == delim)
.map(|bytes| unsafe { OsStr::from_encoded_bytes_unchecked(bytes) })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_split_osstr_with_ascii_delimiter() {
let s = OsStr::new("a,b,c");
let parts: Vec<_> = split_osstr(s, ',').collect();
assert_eq!(parts.len(), 3);
assert_eq!(parts[0], "a");
assert_eq!(parts[1], "b");
assert_eq!(parts[2], "c");
}
#[test]
fn test_split_osstr_with_colon_delimiter() {
let s = OsStr::new("/usr/bin:/usr/local/bin:/home/user/bin");
let parts: Vec<_> = split_osstr(s, ':').collect();
assert_eq!(parts.len(), 3);
assert_eq!(parts[0], "/usr/bin");
assert_eq!(parts[1], "/usr/local/bin");
assert_eq!(parts[2], "/home/user/bin");
}
#[test]
#[should_panic(expected = "when splitting OsStr, the delimiter must be ascii if present")]
fn test_split_osstr_non_ascii_delimiter_panics() {
let s = OsStr::new("a日b日c");
// Using a non-ASCII delimiter should panic
let _ = split_osstr(s, '日').collect::<Vec<_>>();
}
}