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
//! Contains the [`Value`] and [`ValueInner`] containers into which all toml
//! contents can be deserialized into and either used directly or fed into
//! [`crate::Deserialize`] or your own constructs to deserialize into your own
//! types

use crate::{Error, ErrorKind, Span};
use std::{borrow::Cow, fmt};

/// A deserialized [`ValueInner`] with accompanying [`Span`] information for where
/// it was located in the toml document
pub struct Value<'de> {
    value: Option<ValueInner<'de>>,
    /// The location of the value in the toml document
    pub span: Span,
}

impl<'de> Value<'de> {
    /// Creates a new [`Value`] with an empty [`Span`]
    #[inline]
    pub fn new(value: ValueInner<'de>) -> Self {
        Self::with_span(value, Span::default())
    }

    /// Creates a new [`Value`] with the specified [`Span`]
    #[inline]
    pub fn with_span(value: ValueInner<'de>, span: Span) -> Self {
        Self {
            value: Some(value),
            span,
        }
    }

    /// Takes the inner [`ValueInner`]
    ///
    /// This panics if the inner value has already been taken.
    ///
    /// Typically paired with [`Self::set`]
    #[inline]
    pub fn take(&mut self) -> ValueInner<'de> {
        self.value.take().expect("the value has already been taken")
    }

    /// Sets the inner [`ValueInner`]
    ///
    /// This is typically done when the value is taken with [`Self::take`],
    /// processed, and returned
    #[inline]
    pub fn set(&mut self, value: ValueInner<'de>) {
        self.value = Some(value);
    }

    /// Returns true if the value is a table and is non-empty
    #[inline]
    pub fn has_keys(&self) -> bool {
        self.value.as_ref().map_or(false, |val| {
            if let ValueInner::Table(table) = val {
                !table.is_empty()
            } else {
                false
            }
        })
    }

    /// Returns true if the value is a table and has the specified key
    #[inline]
    pub fn has_key(&self, key: &str) -> bool {
        self.value.as_ref().map_or(false, |val| {
            if let ValueInner::Table(table) = val {
                table.contains_key(&key.into())
            } else {
                false
            }
        })
    }

    /// Takes the value as a string, returning an error with either a default
    /// or user supplied message
    #[inline]
    pub fn take_string(&mut self, msg: Option<&'static str>) -> Result<Cow<'de, str>, Error> {
        match self.take() {
            ValueInner::String(s) => Ok(s),
            other => Err(Error {
                kind: ErrorKind::Wanted {
                    expected: msg.unwrap_or("a string"),
                    found: other.type_str(),
                },
                span: self.span,
                line_info: None,
            }),
        }
    }

    /// Returns a borrowed string if this is a [`ValueInner::String`]
    #[inline]
    pub fn as_str(&self) -> Option<&str> {
        self.value.as_ref().and_then(|v| v.as_str())
    }

    /// Returns a borrowed table if this is a [`ValueInner::Table`]
    #[inline]
    pub fn as_table(&self) -> Option<&Table<'de>> {
        self.value.as_ref().and_then(|v| v.as_table())
    }

    /// Returns a borrowed array if this is a [`ValueInner::Array`]
    #[inline]
    pub fn as_array(&self) -> Option<&Array<'de>> {
        self.value.as_ref().and_then(|v| v.as_array())
    }

    /// Returns an `i64` if this is a [`ValueInner::Integer`]
    #[inline]
    pub fn as_integer(&self) -> Option<i64> {
        self.value.as_ref().and_then(|v| v.as_integer())
    }

    /// Returns an `f64` if this is a [`ValueInner::Float`]
    #[inline]
    pub fn as_float(&self) -> Option<f64> {
        self.value.as_ref().and_then(|v| v.as_float())
    }

    /// Returns a `bool` if this is a [`ValueInner::Boolean`]
    #[inline]
    pub fn as_bool(&self) -> Option<bool> {
        self.value.as_ref().and_then(|v| v.as_bool())
    }

    /// Uses JSON pointer-like syntax to lookup a specific [`Value`]
    ///
    /// The basic format is:
    ///
    /// - The path starts with `/`
    /// - Each segment is separated by a `/`
    /// - Each segment is either a key name, or an integer array index
    ///
    /// ```rust
    /// let data = "[x]\ny = ['z', 'zz']";
    /// let value = toml_span::parse(data).unwrap();
    /// assert_eq!(value.pointer("/x/y/1").unwrap().as_str().unwrap(), "zz");
    /// assert!(value.pointer("/a/b/c").is_none());
    /// ```
    ///
    /// Note that this is JSON pointer**-like** because `/` is not supported in
    /// key names because I don't see the point. If you want this it is easy to
    /// implement.
    pub fn pointer(&self, pointer: &'de str) -> Option<&Self> {
        if pointer.is_empty() {
            return Some(self);
        } else if !pointer.starts_with('/') {
            return None;
        }

        pointer
            .split('/')
            .skip(1)
            // Don't support / or ~ in key names unless someone actually opens
            // an issue about it
            //.map(|x| x.replace("~1", "/").replace("~0", "~"))
            .try_fold(self, |target, token| {
                (match &target.value {
                    Some(ValueInner::Table(tab)) => tab.get(&token.into()),
                    Some(ValueInner::Array(list)) => parse_index(token).and_then(|x| list.get(x)),
                    _ => None,
                })
                .filter(|v| v.value.is_some())
            })
    }

    /// The `mut` version of [`Self::pointer`]
    pub fn pointer_mut(&mut self, pointer: &'de str) -> Option<&mut Self> {
        if pointer.is_empty() {
            return Some(self);
        } else if !pointer.starts_with('/') {
            return None;
        }

        pointer
            .split('/')
            .skip(1)
            // Don't support / or ~ in key names unless someone actually opens
            // an issue about it
            //.map(|x| x.replace("~1", "/").replace("~0", "~"))
            .try_fold(self, |target, token| {
                (match &mut target.value {
                    Some(ValueInner::Table(tab)) => tab.get_mut(&token.into()),
                    Some(ValueInner::Array(list)) => {
                        parse_index(token).and_then(|x| list.get_mut(x))
                    }
                    _ => None,
                })
                .filter(|v| v.value.is_some())
            })
    }
}

fn parse_index(s: &str) -> Option<usize> {
    if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
        return None;
    }
    s.parse().ok()
}

impl<'de> AsRef<ValueInner<'de>> for Value<'de> {
    fn as_ref(&self) -> &ValueInner<'de> {
        self.value
            .as_ref()
            .expect("the value has already been taken")
    }
}

impl<'de> fmt::Debug for Value<'de> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.value)
    }
}

/// A toml table key
#[derive(Clone)]
pub struct Key<'de> {
    /// The key itself, in most cases it will be borrowed, but may be owned
    /// if escape characters are present in the original source
    pub name: Cow<'de, str>,
    /// The span for the key in the original document
    pub span: Span,
}

impl<'de> From<&'de str> for Key<'de> {
    fn from(k: &'de str) -> Self {
        Self {
            name: Cow::Borrowed(k),
            span: Span::default(),
        }
    }
}

impl<'de> fmt::Debug for Key<'de> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl<'de> Ord for Key<'de> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.name.cmp(&other.name)
    }
}

impl<'de> PartialOrd for Key<'de> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<'de> PartialEq for Key<'de> {
    fn eq(&self, other: &Self) -> bool {
        self.name.eq(&other.name)
    }
}

impl<'de> Eq for Key<'de> {}

/// A toml table, always represented as a sorted map.
///
/// The original key ordering can be obtained by ordering the keys by their span
pub type Table<'de> = std::collections::BTreeMap<Key<'de>, Value<'de>>;
/// A toml array
pub type Array<'de> = Vec<Value<'de>>;

/// The core value types that toml can deserialize to
///
/// Note that this library does not support datetime values that are part of the
/// toml spec since I have no need of them, but could be added
#[derive(Debug)]
pub enum ValueInner<'de> {
    /// A string.
    ///
    /// This will be borrowed from the original toml source unless it contains
    /// escape characters
    String(Cow<'de, str>),
    /// An integer
    Integer(i64),
    /// A float
    Float(f64),
    /// A boolean
    Boolean(bool),
    /// An array
    Array(Array<'de>),
    /// A table
    Table(Table<'de>),
}

impl<'de> ValueInner<'de> {
    /// Gets the type of the value as a string
    pub fn type_str(&self) -> &'static str {
        match self {
            Self::String(..) => "string",
            Self::Integer(..) => "integer",
            Self::Float(..) => "float",
            Self::Boolean(..) => "boolean",
            Self::Array(..) => "array",
            Self::Table(..) => "table",
        }
    }

    /// Returns a borrowed string if this is a [`Self::String`]
    #[inline]
    pub fn as_str(&self) -> Option<&str> {
        if let Self::String(s) = self {
            Some(s.as_ref())
        } else {
            None
        }
    }

    /// Returns a borrowed table if this is a [`Self::Table`]
    #[inline]
    pub fn as_table(&self) -> Option<&Table<'de>> {
        if let ValueInner::Table(t) = self {
            Some(t)
        } else {
            None
        }
    }

    /// Returns a borrowed array if this is a [`Self::Array`]
    #[inline]
    pub fn as_array(&self) -> Option<&Array<'de>> {
        if let ValueInner::Array(a) = self {
            Some(a)
        } else {
            None
        }
    }

    /// Returns an `i64` if this is a [`Self::Integer`]
    #[inline]
    pub fn as_integer(&self) -> Option<i64> {
        if let ValueInner::Integer(i) = self {
            Some(*i)
        } else {
            None
        }
    }

    /// Returns an `f64` if this is a [`Self::Float`]
    #[inline]
    pub fn as_float(&self) -> Option<f64> {
        if let ValueInner::Float(f) = self {
            Some(*f)
        } else {
            None
        }
    }

    /// Returns a `bool` if this is a [`Self::Boolean`]
    #[inline]
    pub fn as_bool(&self) -> Option<bool> {
        if let ValueInner::Boolean(b) = self {
            Some(*b)
        } else {
            None
        }
    }
}