valid_toml 0.0.2

Provides the ability to load a TOML file with validation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/* Copyright 2016 Joshua Gentry
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */

//*************************************************************************************************
/// The states for the state machine.
enum State
{
    //---------------------------------------------------------------------------------------------
    /// The beginning of the string, we are looking for either a minus sign or a number.
    Start,

    //---------------------------------------------------------------------------------------------
    /// Reading the digits for a number.
    Number,

    //---------------------------------------------------------------------------------------------
    /// Reading the units value for the number.
    Unit
}

//*************************************************************************************************
/// A state machine for decoding a duration in the format "#d #h #m #s #ms" into the number of
/// milliseconds.
struct StateMachine
{
    //---------------------------------------------------------------------------------------------
    /// The current state of the machine.
    state : State,

    //---------------------------------------------------------------------------------------------
    /// Flag indicating we're reading a negative duration.
    negative : bool,

    //---------------------------------------------------------------------------------------------
    /// The total number of milliseconds.
    total : i64,

    //---------------------------------------------------------------------------------------------
    /// The current number we're processing.
    current : Option<i64>,

    //---------------------------------------------------------------------------------------------
    /// The current units we're processing.
    unit : String
}

impl StateMachine
{
    //*********************************************************************************************
    /// Create a new instance of the object.
    pub fn new() -> StateMachine
    {
        StateMachine {
            state    : State::Start,
            negative : false,
            total    : 0,
            current  : None,
            unit     : String::new()
        }
    }

    //*********************************************************************************************
    /// Incorporate the current value based on the value units into the total.  This method will
    /// also reset the current value to 0 and clear the units.
    ///
    /// If the units are invalid this method will return false.
    fn incorporate_current(
        &mut self
        ) -> bool
    {
        if let Some(current) = self.current.take()
        {
            let by = match self.unit.as_str()
            {
                "d"  => 24 * 60 * 60 * 1000,
                "h"  => 60 * 60 * 1000,
                "m"  => 60 * 1000,
                "s"  => 1000,
                "ms" => 1,
                _    => return false
            };

            if self.negative == false
            {
                self.total = current.saturating_mul(by).saturating_add(self.total);
            }
            else
            {
                self.total = self.total.saturating_sub(current.saturating_mul(by));
            }

            self.unit.clear();

            true
        }
        //-----------------------------------------------------------------------------------------
        // No current value.
        else
        {
            false
        }
    }

    //*********************************************************************************************
    /// Incorporates the next digit of a number into self.current.
    ///
    /// # Panics
    ///
    /// If the character is not '0' through '9' this method will panic.
    fn incorporate_val(
        &mut self,
        by : char
        )
    {
        let digit = by.to_digit(10).unwrap() as i64;

        if let Some(current) = self.current
        {
            self.current = Some(current.saturating_mul(10).saturating_add(digit));
        }
        else
        {
            self.current = Some(digit);
        }
    }

    //*********************************************************************************************
    /// Processes a character when we're in the start state.  If there is an error this method
    /// will return false.
    fn start(
        &mut self,
        ch : char
        ) -> bool
    {
        //-----------------------------------------------------------------------------------------
        // Found a negative sign, set the negative flag and start looking for numbers.
        if ch == '-'
        {
            self.negative = true;
            self.state    = State::Number;
            true
        }
        //-----------------------------------------------------------------------------------------
        // Ignore any spaces.
        else if ch == ' '
        {
            true
        }
        //-----------------------------------------------------------------------------------------
        // Found a digit, incorporate it into current and move the state to Number.
        else if ch.is_digit(10) == true
        {
            self.incorporate_val(ch);
            self.state = State::Number;
            true
        }
        //-----------------------------------------------------------------------------------------
        // Didn't find anything we recognize, return false.
        else
        {
            false
        }
    }

    //*********************************************************************************************
    /// Processes a character when we're in the Number state.
    fn number(
        &mut self,
        ch : char
        ) -> bool
    {
        //-----------------------------------------------------------------------------------------
        // The character is a digit, incorporate it into the current value.
        if ch.is_digit(10) == true
        {
            self.incorporate_val(ch);
        }
        //-----------------------------------------------------------------------------------------
        // If the character isn't a space add it to the unit string, and change the state to
        // Unit.
        else if ch != ' '
        {
            self.unit.push(ch);
            self.state = State::Unit;
        }

        true
    }

    //*********************************************************************************************
    /// Processes a character when we're in the Unit state.
    fn unit(
        &mut self,
        ch : char
        ) -> bool
    {
        //----------------------------------------------------------------------------------------
        // If the character is a space, then the unit designation is complete, incorporate the
        // current value into the total, and change the state to Number.
        if ch == ' '
        {
            if self.incorporate_current() == true
            {
                self.state = State::Number;
                true
            }
            else
            {
                false
            }
        }
        //----------------------------------------------------------------------------------------
        // If the character is a digit, then the unit designation is complete, incorporate the
        // current value into the total and incorporate the digit into the current.
        else if ch.is_digit(10)
        {
            if self.incorporate_current()
            {
                self.incorporate_val(ch);
                self.state = State::Number;
                true
            }
            else
            {
                false
            }
        }
        //----------------------------------------------------------------------------------------
        // Got another character push it into the units element.
        else
        {
            self.unit.push(ch);
            true
        }
    }

    //*********************************************************************************************
    /// Process the current character and advance the state.
    fn process(
        &mut self,
        ch : char
        ) -> bool
    {
        match self.state
        {
            State::Start => self.start(ch),
            State::Number => self.number(ch),
            State::Unit => self.unit(ch)
        }
    }

    //*********************************************************************************************
    /// Decode a string using the state machine.  If the string cannot be decoded returns None.
    pub fn decode<T : AsRef<str>>(
        mut self,
        value : T
        ) -> Option<i64>
    {
        //-----------------------------------------------------------------------------------------
        // Iterate over all the characters.
        for ch in value.as_ref().chars()
        {
            if self.process(ch) == false
            {
                return None;
            }
        }

        //-----------------------------------------------------------------------------------------
        // Incorporate the last value.
        if (self.current.is_some() || self.unit.len() > 0) && self.incorporate_current()
        {
            Some(self.total)
        }
        else
        {
            None
        }
    }
}

//*************************************************************************************************
/// Process a string and convert it into the number of milliseconds equivalent.
pub fn process<T : AsRef<str>>(
    value : T
    ) -> Option<i64>
{
    let decoder = StateMachine::new();

    decoder.decode(value)
}

#[cfg(test)]
mod tests
{
    //*********************************************************************************************
    /// Helper function to calculate what the decoder should end up with.
    fn verify(
        neg     : bool,
        days    : i64,
        hours   : i64,
        minutes : i64,
        seconds : i64,
        milli   : i64
        ) -> i64
    {
        if neg
        {
            days.saturating_mul(-24 * 60 * 60 * 1000)
                .saturating_sub(hours.saturating_mul(60 * 60 * 1000))
                .saturating_sub(minutes.saturating_mul(60 * 1000))
                .saturating_sub(seconds.saturating_mul(1000))
                .saturating_sub(milli)
        }
        else
        {
            days.saturating_mul(24 * 60 * 60 * 1000)
                .saturating_add(hours.saturating_mul(60 * 60 * 1000))
                .saturating_add(minutes.saturating_mul(60 * 1000))
                .saturating_add(seconds.saturating_mul(1000))
                .saturating_add(milli)
        }
    }

    //*********************************************************************************************
    /// Test days.
    #[test]
    fn days()
    {
        assert_eq!(super::process("4d").unwrap(), verify(false, 4, 0, 0, 0, 0));
        assert_eq!(super::process("-8d").unwrap(), verify(true, 8, 0, 0, 0, 0));
    }

    //*********************************************************************************************
    /// Test hours.
    #[test]
    fn hours()
    {
        assert_eq!(super::process("4h").unwrap(), verify(false, 0, 4, 0, 0, 0));
        assert_eq!(super::process("-8h").unwrap(), verify(true, 0, 8, 0, 0, 0));
    }

    //*********************************************************************************************
    /// Test minutes.
    #[test]
    fn minutes()
    {
        assert_eq!(super::process("4m").unwrap(), verify(false, 0, 0, 4, 0, 0));
        assert_eq!(super::process("-8m").unwrap(), verify(true, 0, 0, 8, 0, 0));
    }

    //*********************************************************************************************
    /// Test seconds.
    #[test]
    fn seconds()
    {
        assert_eq!(super::process("4s").unwrap(), verify(false, 0, 0, 0, 4, 0));
        assert_eq!(super::process("-8s").unwrap(), verify(true, 0, 0, 0, 8, 0));
    }

    //*********************************************************************************************
    /// Test seconds.
    #[test]
    fn milliseconds()
    {
        assert_eq!(super::process("4ms").unwrap(), verify(false, 0, 0, 0, 0, 4));
        assert_eq!(super::process("-8ms").unwrap(), verify(true, 0, 0, 0, 0, 8));
    }

    //*********************************************************************************************
    /// Test various combinations.
    #[test]
    fn combo()
    {
        assert_eq!(super::process("12d 10h 8m 6s 4ms").unwrap(), verify(false, 12, 10, 8, 6, 4));
        assert_eq!(super::process("-12d 10h 8m 6s 4ms").unwrap(), verify(true, 12, 10, 8, 6, 4));

        assert_eq!(super::process("12d 4ms").unwrap(), verify(false, 12, 0, 0, 0, 4));
        assert_eq!(super::process("-10h 6s").unwrap(), verify(true, 0, 10, 0, 6, 0));
    }

    //*********************************************************************************************
    /// Test various combinations with spaces in interesting places.
    #[test]
    fn spaces()
    {
        assert_eq!(super::process("  -6s3ms").unwrap(), verify(true, 0, 0, 0, 6, 3));
        assert_eq!(super::process("12d10h8m6s4ms").unwrap(), verify(false, 12, 10, 8, 6, 4));

        assert_eq!(super::process("12 d 4   ms").unwrap(), verify(false, 12, 0, 0, 0, 4));
        assert_eq!(super::process("-   10h 6  s").unwrap(), verify(true, 0, 10, 0, 6, 0));
    }

    //*********************************************************************************************
    /// Test bad values.
    #[test]
    fn bad()
    {
        assert!(super::process("abc").is_none());
        assert!(super::process("123").is_none());
        assert!(super::process("123u").is_none());
        assert!(super::process("12h 123").is_none());
        assert!(super::process("12u 123m").is_none());
        assert!(super::process("12u123m").is_none());
        assert!(super::process("h0").is_none());
        assert!(super::process("-3").is_none());
        assert!(super::process("-h").is_none());
        assert!(super::process("h").is_none());
        assert!(super::process("-3h-6m").is_none());
        assert!(super::process("-3h m").is_none());
    }
}