-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtypes.rs
1909 lines (1773 loc) · 72.5 KB
/
types.rs
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashMap;
use std::hash::Hasher;
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use std::fmt;
use std::error::Error;
use std::fmt::Display;
use std::str::FromStr;
use std::borrow::Cow;
use internals::parser::Parser;
use nom::IResult;
/// Conveys the result of a parse operation on a TOML document
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum ParseResult<'a> {
/// The entire input was parsed without error.
Full,
/// The entire input was parsed, but there were errors. Contains an `Rc<RefCell<Vec>>` of `ParseError`s.
FullError(Rc<RefCell<Vec<ParseError<'a>>>>),
/// Part of the input was parsed successfully without any errors. Contains a `Cow<str>`, with the leftover, unparsed
/// input, the line number and column (currently column reporting is unimplemented and will always report `0`) where
/// parsing stopped.
Partial(Cow<'a, str>, usize, usize),
/// Part of the input was parsed successfully with errors. Contains a `Cow<str>`, with the leftover, unparsed input,
/// the line number and column (currently column reporting is unimplemented and will always report `0`) where parsing
/// stopped, and an `Rc<RefCell<Vec>>` of `ParseError`s.
PartialError(Cow<'a, str>, usize, usize, Rc<RefCell<Vec<ParseError<'a>>>>),
/// The parser failed to parse any of the input as a complete TOML document. Contains the line number and column
/// (currently column reporting is unimplemented and will always report `0`) where parsing stopped.
Failure(usize, usize),
}
/// Represents a non-failure error encountered while parsing a TOML document.
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum ParseError<'a> {
/// An `Array` containing different types was encountered. Contains the `String` key that points to the `Array` and
/// the line number and column (currently column reporting is unimplemented and will always report `0`) where the
/// `Array` was found. The `Array` can be retrieved and/or changed by its key using `TOMLParser::get_value` and
/// `TOMLParser::set_value` methods.
MixedArray(String, usize, usize),
/// A duplicate key was encountered. Contains the `String` key that was duplicated in the document, the line number
/// and column (currently column reporting is unimplemented and will always report `0`) where the duplicate key was
/// found, and the `Value` that the key points to.
DuplicateKey(String, usize, usize, Value<'a>),
/// An invalid table was encountered. Either the key\[s\] that make up the table are invalid or a duplicate table was
/// found. Contains the `String` key of the invalid table, the line number and column (currently column reporting is
/// unimplemented and will always report `0`) where the invalid table was found, `RefCell<HashMap<String, Value>>`
/// that contains all the keys and values belonging to that table.
InvalidTable(String, usize, usize, RefCell<HashMap<String, Value<'a>>>),
/// An invalid `DateTime` was encountered. This could be a `DateTime` with:
///
/// * 0 for year
/// * 0 for month or greater than 12 for month
/// * 0 for day or greater than, 28, 29, 30, or 31 for day depending on the month and if the year is a leap year
/// * Greater than 23 for hour
/// * Greater than 59 for minute
/// * Greater than 59 for second
/// * Greater than 23 for offset hour
/// * Greater than 59 for offset minute
///
/// Contains the `String` key of the invalid `DateTime`, the line number and column (currently column reporting is
/// unimplemented and will always report `0`) where the invalid `DateTime` was found, and a Cow<str> containing the
/// invalid `DateTime` string.
InvalidDateTime(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when an integer overflow is detected.
IntegerOverflow(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when an integer underflow is detected.
IntegerUnderflow(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when an invalid integer representation is detected.
InvalidInteger(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when a float value of infinity is detected.
Infinity(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when a float value of negative infinity is detected.
NegativeInfinity(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when a float string conversion to an `f64` would result in a loss
/// of precision.
LossOfPrecision(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when an invalid float representation is detected.
InvalidFloat(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when an invalid `true` or `false` string is detected.
InvalidBoolean(String, usize, usize, Cow<'a, str>),
/// *Currently unimplemented*. Reserved for future use when an invalid string representation is detected.
InvalidString(String, usize, usize, Cow<'a, str>, StrType),
/// *Currently unimplemented*. Reserved for future use when new error types are added without resorting to a breaking
/// change.
GenericError(String, usize, usize, Option<Cow<'a, str>>, String),
}
// Represents the 7 different types of values that can exist in a TOML document.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Value<'a> {
/// An integer value. Contains a `Cow<str>` representing the integer since integers can contain underscores.
Integer(Cow<'a, str>),
/// A float value. Contains a `Cow<str>` representing the float since floats can be formatted many different ways and
/// can contain underscores.
Float(Cow<'a, str>),
/// A boolean value. Contains a `bool` value since only `true` and `false` are allowed.
Boolean(bool),
/// A `DateTime` value. Contains a `DateTime` struct that has a date and optionally a time, fractional seconds, and
/// offset from UTC.
DateTime(DateTime<'a>),
/// A string value. Contains a `Cow<str>` with the string contents (without quotes) and `StrType` indicating whether
/// the string is a basic string, multi-line basic string, literal string or multi-line literal string.
String(Cow<'a, str>, StrType),
/// An array value. Contains an `Rc<Vec>` of `Value`s contained in the `Array`.
Array(Rc<Vec<Value<'a>>>),
/// An inline table value. Contains an `Rc<Vec>` of tuples that contain a `Cow<str>` representing a key, and `Value`
/// that the key points to.
InlineTable(Rc<Vec<(Cow<'a, str>, Value<'a>)>>)
}
/// Represents the 4 different types of strings that are allowed in TOML documents.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum StrType {
/// String is a basic string.
Basic,
/// String is a multi-line basic string.
MLBasic,
/// String is a literal string.
Literal,
/// String is a multi-line literal string.
MLLiteral,
}
/// Represents the child keys of a key in a parsed TOML document.
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum Children {
/// Contains a `Cell<usize>` with the amount of child keys the key has. The key has children that are indexed with an
/// integer starting at 0. `Array`s and array of tables use integer for their child keys. For example:
///
/// ```text
/// Array = ["A", "B", "C", "D", "E"]
/// [[array_of_table]]
/// key = "val 1"
/// [[array_of_table]]
/// key = "val 2"
/// [[array_of_table]]
/// key = "val 3"
/// ```
///
/// "Array" has 5 children. The key of "D" is "Array[3]" because it is fourth element in "Array" and indexing starts
/// at 0.
/// "array_of_table" has 3 children. The key of "val 3" is "array_of_table[2].key" because it is in the third
/// sub-table of "array_of_table" and indexing starts at 0.
Count(Cell<usize>),
/// Contains a `RefCell<Vec>` of `String`s with every sub-key of the key. The key has children that are indexed with a
/// sub-key. Tables and inline-tables use sub-keys for their child keys. For example:
///
/// ```text
/// InlineTable = {subkey1 = "A", subkey2 = "B"}
/// [table]
/// a_key = "val 1"
/// b_key = "val 2"
/// c_key = "val 3"
/// ```
///
/// "InlineTable" has 2 children, "subkey1" and "subkey2". The key of "B" is "InlineTable.subkey2".
/// "table" has 3 children, "a_key", "b_key", and "c_key". The key of "val 3" is "table.c_key".
Keys(RefCell<Vec<String>>)
}
/// Contains convenience functions to combine base keys with child keys to make a full key.
impl Children {
/// Combines string type `base_key` with a string type `child_key` to form a full key.
///
/// # Examples
///
/// ```
/// use tomllib::TOMLParser;
/// use tomllib::types::Children;
/// let toml_doc = r#"
/// [dependencies]
/// nom = {version = "^1.2.0", features = ["regexp"]}
/// regex = {version = "^0.1.48"}
/// log = {version = "^0.3.5"}
/// "#;
/// let parser = TOMLParser::new();
/// let (parser, result) = parser.parse(toml_doc);
/// let deps = parser.get_children("dependencies");
/// if let &Children::Keys(ref subkeys) = deps.unwrap() {
/// assert_eq!("dependencies.nom",
/// Children::combine_keys("dependencies", &subkeys.borrow()[0]));
/// }
/// ```
pub fn combine_keys<S>(base_key: S, child_key: S) -> String where S: Into<String> {
let mut full_key;
let base = base_key.into();
let child = child_key.into();
if base != "" {
full_key = base.clone();
full_key.push('.');
full_key.push_str(&child);
} else {
full_key = child.clone();
}
return full_key;
}
/// Combines string type `base_key` with an integer type `child_key` to form a full key.
///
/// # Examples
///
/// ```
/// use tomllib::TOMLParser;
/// use tomllib::types::Children;
/// let toml_doc = r#"
/// keywords = ["toml", "parser", "encode", "decode", "nom"]
/// "#;
/// let parser = TOMLParser::new();
/// let (parser, result) = parser.parse(toml_doc);
/// let kw = parser.get_children("keywords");
/// if let &Children::Count(ref subkeys) = kw.unwrap() {
/// assert_eq!("keywords[4]", Children::combine_keys_index("keywords", subkeys.get() - 1));
/// }
/// # else {
/// # assert!(false, "{:?}", kw.unwrap());
/// # }
/// ```
pub fn combine_keys_index<S>(base_key: S, child_key: usize) -> String where S: Into<String> {
return format!("{}[{}]", base_key.into(), child_key);
}
/// Combines string type `base_key` with all subkeys of an instance of `Children` to form a `Vec` of full keys
///
/// # Examples
///
/// ```
/// use tomllib::TOMLParser;
/// use tomllib::types::Children;
/// let toml_doc = r#"
/// keywords = ["toml", "parser"]
/// numbers = {first = 1, second = 2}
/// "#;
/// let parser = TOMLParser::new();
/// let (parser, result) = parser.parse(toml_doc);
/// let kw = parser.get_children("keywords");
/// assert_eq!(vec!["keywords[0]".to_string(), "keywords[1]".to_string()],
/// kw.unwrap().combine_child_keys("keywords"));
/// let num = parser.get_children("numbers");
/// assert_eq!(vec!["numbers.first".to_string(), "numbers.second".to_string()],
/// num.unwrap().combine_child_keys("numbers"));
/// ```
pub fn combine_child_keys<S>(&self, base_key: S) -> Vec<String> where S: Into<String> {
let mut all_keys = vec![];
let base = base_key.into();
match self {
&Children::Count(ref c) => {
for i in 0..c.get() {
all_keys.push(format!("{}[{}]", base, i));
}
},
&Children::Keys(ref hs_rc) => {
for subkey in hs_rc.borrow().iter() {
if base != "" {
let mut full_key = base.clone();
full_key.push('.');
full_key.push_str(&subkey);
all_keys.push(full_key);
} else {
all_keys.push(subkey.clone());
}
}
},
}
return all_keys;
}
}
/// Formats a `Value` for display. Uses default rust formatting for for `i64` for `Integer`s, `f64` for `Float`s, bool
/// for `Boolean`s. The default formatting for `Array`s and `InlineTable`s is No whitespace after/before
/// opening/closing braces, no whitespace before and one space after all commas, no comments on the same line as the
/// `Array` or `InlineTable`, and one space before and after an equals sign in an `InlineTable`.
impl<'a> Display for Value<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Value::Integer(ref v) | &Value::Float(ref v) =>
write!(f, "{}", v),
&Value::Boolean(ref b) => write!(f, "{}", b),
&Value::DateTime(ref v) => write!(f, "{}", v),
&Value::Array(ref arr) => {
try!(write!(f, "["));
for i in 0..arr.len() - 1 {
try!(write!(f, "{}, ", arr[i]));
}
if arr.len() > 0 {
try!(write!(f, "{}", arr[arr.len()-1]));
}
write!(f, "]")
},
&Value::String(ref s, ref t) => {
match t {
&StrType::Basic => write!(f, "\"{}\"", s),
&StrType::MLBasic => write!(f, "\"\"\"{}\"\"\"", s),
&StrType::Literal => write!(f, "'{}'", s),
&StrType::MLLiteral => write!(f, "'''{}'''", s),
}
},
&Value::InlineTable(ref it) => {
try!(write!(f, "{{"));
for i in 0..it.len() - 1 {
try!(write!(f, "{} = {}, ", it[i].0, it[i].1));
}
if it.len() > 0 {
try!(write!(f, "{} = {}", it[it.len()-1].0, it[it.len()-1].1));
}
write!(f, "}}")
}
}
}
}
impl<'a> Value<'a> {
/// Convenience function for creating an `Value::Integer` from an `i64`. Cannot fail since `i64` maps directly onto
/// TOML integers.
///
/// # Examples
///
/// ```
/// use tomllib::types::Value;
///
/// assert_eq!(Value::Integer("100".into()), Value::int(100));
/// ```
pub fn int(int: i64) -> Value<'a> {
Value::Integer(format!("{}", int).into())
}
/// Convenience function for creating an `Value::Integer` from an string type. Returns `Ok(Integer)` on success and
/// `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::Value;
///
/// assert_eq!(Value::Integer("200".into()), Value::int_from_str("200").unwrap());
/// ```
pub fn int_from_str<S>(int: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
let result = Value::Integer(int.clone().into().into());
if result.validate() {
return Result::Ok(result);
} else {
return Result::Err(TOMLError::new(format!("Error parsing int. Argument: {}", int.into())));
}
}
/// Convenience function for creating a `Value::Float` from a `f64`. Cannot fail since `f64` maps directly onto TOML
/// floats.
///
/// # Examples
///
/// ```
/// use tomllib::types::Value;
///
/// assert_eq!(Value::Float("300.3".into()), Value::float(300.3));
/// ```
pub fn float(float: f64) -> Value<'a> {
Value::Float(format!("{}", float).into())
}
/// Convenience function for creating a `Value::Float` from an string type. Returns `Ok(Float)` on success and
/// `Err(TOMLError)`
/// on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::Value;
///
/// assert_eq!(Value::Float("400.4".into()), Value::float_from_str("400.4").unwrap());
/// ```
pub fn float_from_str<S>(float: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
let result = Value::Float(float.clone().into().into());
if result.validate() {
return Result::Ok(result);
} else {
return Result::Err(TOMLError::new(format!("Error parsing float. Argument: {}", float.into())));
}
}
/// Convenience function for creating a `Value::Boolean` from a `bool`. Cannot fail since `bool` maps directly onto
/// TOML booleans.
///
/// # Examples
///
/// ```
/// use tomllib::types::Value;
///
/// assert_eq!(Value::Boolean(true), Value::bool(true));
/// ```
pub fn bool(b: bool) -> Value<'a> {
Value::Boolean(b)
}
pub fn bool_from_str<S>(b: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
let lower = b.clone().into().to_lowercase();
if lower == "true" {
Result::Ok(Value::Boolean(true))
} else if lower == "false" {
Result::Ok(Value::Boolean(false))
} else {
return Result::Err(TOMLError::new(
format!("Error parsing bool. Argument: {}", b.into())
))
}
}
/// Convenience function for creating a `Value::DateTime` containing only a date from integer values. Returns
/// `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2010", "04", "10").unwrap(), None)),
/// Value::date_from_int(2010, 4, 10).unwrap());
/// ```
pub fn date_from_int(year: usize, month: usize, day: usize) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
match Date::from_str(y, m, d) {
Ok(date) => {
Ok(Value::DateTime(DateTime::new(date, None)))
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing only a date from string values. Returns
/// `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2011", "05", "11").unwrap(), None)),
/// Value::date_from_str("2011", "05", "11").unwrap());
/// ```
pub fn date_from_str<S>(year: S, month: S, day: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
match Date::from_str(year.clone().into(), month.clone().into(), day.clone().into()) {
Ok(date) => {
Ok(Value::DateTime(DateTime::new(date, None)))
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time from integer values. Returns
/// `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2010", "04", "10").unwrap(),
/// Some(Time::from_str("01", "02", "03", None, None).unwrap()))),
/// Value::datetime_from_int(2010, 4, 10, 1, 2, 3).unwrap());
/// ```
pub fn datetime_from_int(year: usize, month: usize, day: usize, hour: usize, minute: usize, second: usize) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
let h = format!("{:0>2}", hour);
let min = format!("{:0>2}", minute);
let s = format!("{:0>2}", second);
match Date::from_str(y, m, d) {
Ok(date) => {
match Time::from_str(h, min, s, None, None) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time from string values. Returns
/// `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2011", "05", "11").unwrap(),
/// Some(Time::from_str("02", "03", "04", None, None).unwrap()))),
/// Value::datetime_from_str("2011", "05", "11", "02", "03", "04").unwrap());
/// ```
pub fn datetime_from_str<S>(year: S, month: S, day: S, hour: S, minute: S, second: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
match Date::from_str(year.clone().into(), month.clone().into(), day.clone().into()) {
Ok(date) => {
match Time::from_str(hour.clone().into(), minute.clone().into(), second.clone().into(), None, None) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with fractional seconds from
/// integer values. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure. Note, you can't represent
/// leading zeros on the fractional part this way for example: `2016-03-15T08:05:22.00055` is not possible using this
/// function.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2010", "04", "10").unwrap(),
/// Some(Time::from_str("01", "02", "03", Some("5432".into()), None).unwrap()))),
/// Value::datetime_frac_from_int(2010, 4, 10, 1, 2, 3, 5432).unwrap());
/// ```
pub fn datetime_frac_from_int(year: usize, month: usize, day: usize, hour: usize, minute: usize, second: usize, frac: usize) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
let h = format!("{:0>2}", hour);
let min = format!("{:0>2}", minute);
let s = format!("{:0>2}", second);
let f = format!("{}", frac);
match Date::from_str(y, m, d) {
Ok(date) => {
match Time::from_str(h, min, s, Some(f), None) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with fractional seconds from
/// string values. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2011", "05", "11").unwrap(),
/// Some(Time::from_str("02", "03", "04", Some("0043".into()), None).unwrap()))),
/// Value::datetime_frac_from_str("2011", "05", "11", "02", "03", "04", "0043").unwrap());
/// ```
pub fn datetime_frac_from_str<S>(year: S, month: S, day: S, hour: S, minute: S, second: S, frac: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone{
match Date::from_str(year.clone().into(), month.clone().into(), day.clone().into()) {
Ok(date) => {
match Time::from_str(hour.clone().into(), minute.clone().into(), second.clone().into(), Some(frac.clone().into()), None) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with a timezone offset from UTC
/// from integer values, except for the plus/minus sign which is passed as a char `'+'` or `'-'`. Returns
/// `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset, TimeOffsetAmount};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2010", "04", "10").unwrap(),
/// Some(Time::from_str("01", "02", "03", None, Some(TimeOffset::Time(TimeOffsetAmount::from_str(
/// "+", "08", "00"
/// ).unwrap()))).unwrap()))),
/// Value::datetime_offset_from_int(2010, 4, 10, 1, 2, 3, '+', 8, 0).unwrap());
/// ```
pub fn datetime_offset_from_int(year: usize, month: usize, day: usize, hour: usize, minute: usize, second: usize, posneg: char, off_hour: usize, off_minute: usize) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
let h = format!("{:0>2}", hour);
let min = format!("{:0>2}", minute);
let s = format!("{:0>2}", second);
let oh = format!("{:0>2}", off_hour);
let omin = format!("{:0>2}", off_minute);
let mut pn = "".to_string();
pn.push(posneg);
match Date::from_str(y, m, d) {
Ok(date) => {
match TimeOffsetAmount::from_str(pn, oh, omin) {
Ok(offset) => {
match Time::from_str(h, min, s, None, Some(TimeOffset::Time(offset))) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Result::Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with a timezone offset from UTC
/// from string values. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset, TimeOffsetAmount};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2011", "05", "11").unwrap(),
/// Some(Time::from_str("02", "03", "04", None, Some(TimeOffset::Time(TimeOffsetAmount::from_str(
/// "+", "09", "30"
/// ).unwrap()))).unwrap()))),
/// Value::datetime_offset_from_str("2011", "05", "11", "02", "03", "04", "+", "09", "30").unwrap());
/// ```
pub fn datetime_offset_from_str<S>(year: S, month: S, day: S, hour: S, minute: S, second: S, posneg: S, off_hour: S, off_minute: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone{
match Date::from_str(year.clone().into(), month.clone().into(), day.clone().into()) {
Ok(date) => {
match TimeOffsetAmount::from_str(posneg.clone().into(), off_hour.clone().into(), off_minute.clone().into()) {
Ok(offset) => {
match Time::from_str(hour.clone().into(), minute.clone().into(), second.clone().into(), None, Some(
TimeOffset::Time(offset)
)) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Result::Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with a timezone of Zulu from
/// integer values. Returns Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2010", "04", "10").unwrap(),
/// Some(Time::from_str("01", "02", "03", None, Some(TimeOffset::Zulu)).unwrap()))),
/// Value::datetime_zulu_from_int(2010, 4, 10, 1, 2, 3).unwrap());
/// ```
pub fn datetime_zulu_from_int(year: usize, month: usize, day: usize, hour: usize, minute: usize, second: usize) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
let h = format!("{:0>2}", hour);
let min = format!("{:0>2}", minute);
let s = format!("{:0>2}", second);
match Date::from_str(y, m, d) {
Ok(date) => {
match Time::from_str(h, min, s, None, Some(TimeOffset::Zulu)) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with a timezone of Zulu from
/// string values. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2011", "05", "11").unwrap(),
/// Some(Time::from_str("02", "03", "04", None, Some(TimeOffset::Zulu)).unwrap()))),
/// Value::datetime_zulu_from_str("2011", "05", "11", "02", "03", "04").unwrap());
/// ```
pub fn datetime_zulu_from_str<S>(year: S, month: S, day: S, hour: S, minute: S, second: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
match Date::from_str(year.clone().into(), month.clone().into(), day.clone().into()) {
Ok(date) => {
match Time::from_str(hour.clone().into(), minute.clone().into(), second.clone().into(), None, Some(
TimeOffset::Zulu
)) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with fractional seconds and a
/// timezone of Zulu from integer values, except for the plus/minus sign which is passed as a string value `"+"` or
/// "-"`. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure. Note, you can't represent leading zeros
/// on the fractional part this way for example: `2016-03-15T08:05:22.00055Z` is not possible using this function.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2010", "04", "10").unwrap(),
/// Some(Time::from_str("01", "02", "03", Some("5678".into()), Some(TimeOffset::Zulu)).unwrap()))),
/// Value::datetime_full_zulu_from_int(2010, 4, 10, 1, 2, 3, 5678).unwrap());
/// ```
pub fn datetime_full_zulu_from_int(year: usize, month: usize, day: usize, hour: usize, minute: usize, second: usize, frac: u64) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
let h = format!("{:0>2}", hour);
let min = format!("{:0>2}", minute);
let s = format!("{:0>2}", second);
let f = format!("{}", frac);
match Date::from_str(y, m, d) {
Ok(date) => {
match Time::from_str(h, min, s, Some(f), Some(TimeOffset::Zulu)) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with fractional seconds and a
/// timezone of Zulu from string values. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2011", "05", "11").unwrap(),
/// Some(Time::from_str("02", "03", "04", None, Some(TimeOffset::Zulu)).unwrap()))),
/// Value::datetime_zulu_from_str("2011", "05", "11", "02", "03", "04").unwrap());
/// ```
pub fn datetime_full_zulu_from_str<S>(year: S, month: S, day: S, hour: S, minute: S, second: S, frac: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
match Date::from_str(year.clone().into(), month.clone().into(), day.clone().into()) {
Ok(date) => {
match Time::from_str(hour.clone().into(), minute.clone().into(), second.clone().into(), Some(frac.clone().into()), Some(
TimeOffset::Zulu
)) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with fractional seconds and a
/// timezone offset from UTC from integer values, except for the plus/minus sign which is passed as a char `"+"` or
/// `"-"`. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure. Note, you can't represent
/// leading zeros on the fractional part this way for example: `2016-03-15T08:05:22.00055-11:00` is not possible using
/// this function.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset, TimeOffsetAmount};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2010", "04", "10").unwrap(),
/// Some(Time::from_str("01", "02", "03", Some("135".into()), Some(TimeOffset::Time(TimeOffsetAmount::from_str(
/// "-", "11", "00"
/// ).unwrap()))).unwrap()))),
/// Value::datetime_full_from_int(2010, 4, 10, 1, 2, 3, 135, '-', 11, 0).unwrap());
/// ```
pub fn datetime_full_from_int(year: usize, month: usize, day: usize, hour: usize, minute: usize, second: usize, frac: u64, posneg: char, off_hour: usize, off_minute: usize) -> Result<Value<'a>, TOMLError> {
let y = format!("{:0>4}", year);
let m = format!("{:0>2}", month);
let d = format!("{:0>2}", day);
let h = format!("{:0>2}", hour);
let min = format!("{:0>2}", minute);
let s = format!("{:0>2}", second);
let f = format!("{}", frac);
let oh = format!("{:0>2}", off_hour);
let omin = format!("{:0>2}", off_minute);
let mut pn = "".to_string();
pn.push(posneg);
match Date::from_str(y, m, d) {
Ok(date) => {
match TimeOffsetAmount::from_str(pn, oh, omin) {
Ok(offset) => {
match Time::from_str(h, min, s, Some(f), Some(TimeOffset::Time(offset))) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` containing a date and time with fractional seconds and a
/// timezone offset from UTC from string values. Returns `Ok(DateTime)` on success and `Err(TOMLError)` on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset, TimeOffsetAmount};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2011", "05", "11").unwrap(),
/// Some(Time::from_str("02", "03", "04", Some("0864".into()), Some(TimeOffset::Time(TimeOffsetAmount::from_str(
/// "+", "09", "30"
/// ).unwrap()))).unwrap()))),
/// Value::datetime_full_from_str("2011", "05", "11", "02", "03", "04", "0864","+", "09", "30").unwrap());
/// ```
pub fn datetime_full_from_str<S>(year: S, month: S, day: S, hour: S, minute: S, second: S, frac: S, posneg: S, off_hour: S, off_minute: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
match Date::from_str(year.clone().into(), month.clone().into(), day.clone().into()) {
Ok(date) => {
match TimeOffsetAmount::from_str(posneg.clone().into(), off_hour.clone().into(), off_minute.clone().into()) {
Ok(offset) => {
match Time::from_str(hour.clone().into(), minute.clone().into(), second.clone().into(), Some(frac.clone().into()), Some(
TimeOffset::Time(offset)
)) {
Ok(time) => Ok(Value::DateTime(DateTime::new(date, Some(time)))),
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
},
Err(error) => Err(error),
}
}
/// Convenience function for creating a `Value::DateTime` from a sinle string value.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, DateTime, Date, Time, TimeOffset, TimeOffsetAmount};
///
/// assert_eq!(Value::DateTime(DateTime::new(Date::from_str("2012", "06", "12").unwrap(),
/// Some(Time::from_str("02", "03", "04", Some("0864".into()), Some(TimeOffset::Time(TimeOffsetAmount::from_str(
/// "+", "10", "30"
/// ).unwrap()))).unwrap()))),
/// Value::datetime_parse("2012-06-12T02:03:04.0864+10:30").unwrap());
/// ```
pub fn datetime_parse<S>(dt: S) -> Result<Value<'a>, TOMLError> where S: Into<&'a str> {
let datetime = dt.into();
let p = Parser::new();
match p.date_time(datetime) {
(_, IResult::Done(i, o)) => {
let result = Value::DateTime(o);
if i.len() > 0 || !result.validate() {
return Result::Err(TOMLError::new(format!("Error parsing string as datetime. Argument: {}", datetime)));
} else {
return Result::Ok(result);
}
},
(_,_) => return Result::Err(TOMLError::new(format!("Error parsing string as datetime. Argument: {}", datetime))),
}
}
/// Convenience function for creating a `Value::String` with `StrType::Basic`. Returns Ok() on success and Err() on
/// failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, StrType};
///
/// assert_eq!(Value::String("foobar".into(), StrType::Basic), Value::basic_string("foobar").unwrap());
/// ```
pub fn basic_string<S>(s: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
let result = Value::String(s.clone().into().into(), StrType::Basic);
if result.validate() {
return Result::Ok(result);
} else {
return Result::Err(TOMLError::new(format!("Error parsing string as basic_string. Argument: {}", s.into())));
}
}
/// Convenience function for creating a `Value::String` with `StrType::MLBasic`. Returns Ok() on success and Err() on
/// failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, StrType};
///
/// assert_eq!(Value::String("foo\nbar".into(), StrType::MLBasic), Value::ml_basic_string("foo\nbar").unwrap());
/// ```
pub fn ml_basic_string<S>(s: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
let result = Value::String(s.clone().into().into(), StrType::MLBasic);
if result.validate() {
return Result::Ok(result);
} else {
return Result::Err(TOMLError::new(format!("Error parsing string as ml_basic_string. Argument: {}", s.into())));
}
}
/// Convenience function for creating a `Value::String` with `StrType::Literal`. Returns Ok() on success and Err() on
/// failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, StrType};
///
/// assert_eq!(Value::String("\"foobar\"".into(), StrType::Literal), Value::literal_string("\"foobar\"").unwrap());
/// ```
pub fn literal_string<S>(s: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
let result = Value::String(s.clone().into().into(), StrType::Literal);
if result.validate() {
return Result::Ok(result);
} else {
return Result::Err(TOMLError::new(format!("Error parsing string as literal_string. Argument: {}", s.into())));
}
}
/// Convenience function for creating a `Value::String` with `StrType::MLLiteral`. Returns Ok() on success and Err()
/// on failure.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value, StrType};
///
/// assert_eq!(Value::String("\"foo\nbar\"".into(), StrType::MLLiteral),
/// Value::ml_literal_string("\"foo\nbar\"").unwrap());
/// ```
pub fn ml_literal_string<S>(s: S) -> Result<Value<'a>, TOMLError> where S: Into<String> + Clone {
let result = Value::String(s.clone().into().into(), StrType::MLLiteral);
if result.validate() {
return Result::Ok(result);
} else {
return Result::Err(TOMLError::new(format!("Error parsing string as ml_literal_string. Argument: {}", s.into())));
}
}
/// Parses and validates a `Value`, returns true if the value is valid and false if it is invalid.
///
/// # Examples
///
/// ```
/// use tomllib::types::{Value};
///
/// assert!(!Value::Integer("_989_721_".into()).validate()); // Integers may have underscores but they must be
/// // surrounded by digits
/// assert!(Value::Float("7.62".into()).validate());
/// ```
pub fn validate(&self) -> bool{
match self {
&Value::Integer(ref s) => {
let p = Parser::new();
match p.integer(s) {
(_, IResult::Done(_, _)) => true,
(_,_) => false,
}
},
&Value::Float(ref s) => {
let p = Parser::new();
match p.float(s) {
(_, IResult::Done(_, _)) => true,
(_,_) => false,
}
},
&Value::DateTime(ref dt) => {dt.validate()},
&Value::String(ref s, st) => {
match st {
StrType::Basic => {
match Parser::quoteless_basic_string(s) {
IResult::Done(i,_) => i.len() == 0,
_ => false,
}
},
StrType::MLBasic => {
match Parser::quoteless_ml_basic_string(s) {
IResult::Done(i,_) => i.len() == 0,
_ => false,
}
},
StrType::Literal => {
match Parser::quoteless_literal_string(s) {
IResult::Done(i,_) => i.len() == 0,
_ => false,
}
},
StrType::MLLiteral => {
match Parser::quoteless_ml_literal_string(s) {
IResult::Done(i,_) => i.len() == 0,
_ => false,
}
},
}
},
_ => true,
}
}
}
/// Error type returned by `Value` creation convenience functions on invalid input.
#[derive(Debug)]
pub struct TOMLError {
message: String,