Skip to main content

rig_core/
json_utils.rs

1use serde::Deserialize;
2use serde::de::Deserializer;
3use std::cmp::Ordering;
4use std::sync::LazyLock;
5
6/// The numeric order of two JSON numbers, exact: integers compare as
7/// integers and an integer against a float rounds neither, so `5` equals
8/// `5.0` but `2^53 + 1` does not equal `2^53` as a float. With serde_json's
9/// `arbitrary_precision`, numbers compare by their literal's decimal value.
10pub(crate) fn compare_numbers(a: &serde_json::Number, b: &serde_json::Number) -> Option<Ordering> {
11    if holds_literals() {
12        return Some(compare_literals(&a.to_string(), &b.to_string()));
13    }
14    let integer = |n: &serde_json::Number| {
15        n.as_i64()
16            .map(i128::from)
17            .or_else(|| n.as_u64().map(i128::from))
18    };
19    match (integer(a), integer(b)) {
20        (Some(a), Some(b)) => Some(a.cmp(&b)),
21        (Some(a), None) => compare_integer_float(a, b.as_f64()?),
22        (None, Some(b)) => compare_integer_float(b, a.as_f64()?).map(Ordering::reverse),
23        (None, None) => a.as_f64()?.partial_cmp(&b.as_f64()?),
24    }
25}
26
27/// Whether a [`serde_json::Number`] keeps the literal it was read from, as
28/// it does with `arbitrary_precision`, which a dependent crate can turn on.
29fn holds_literals() -> bool {
30    static HOLDS: LazyLock<bool> = LazyLock::new(|| {
31        serde_json::from_str::<serde_json::Number>("1.50").is_ok_and(|n| n.to_string() == "1.50")
32    });
33    *HOLDS
34}
35
36/// A JSON number literal as `sign * 0.digits * 10^(exponent + shift)`.
37/// `digits` has no leading or trailing zero, so one value has one form. The
38/// exponent stays text, since a literal's can be any length.
39struct Literal<'a> {
40    sign: i8,
41    exponent_sign: i128,
42    exponent: &'a str,
43    shift: i128,
44    digits: String,
45}
46
47impl<'a> Literal<'a> {
48    fn new(text: &'a str) -> Self {
49        let (sign, text) = text.strip_prefix('-').map_or((1, text), |text| (-1, text));
50        let (mantissa, exponent) = text.split_once(['e', 'E']).unwrap_or((text, ""));
51        let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
52        let digits = format!("{whole}{fraction}");
53        let digits = digits.trim_start_matches('0');
54        let (exponent_sign, exponent) = match exponent.strip_prefix('-') {
55            Some(exponent) => (-1, exponent),
56            None => (1, exponent.trim_start_matches('+')),
57        };
58        let zero = digits.is_empty();
59        Self {
60            sign: if zero { 0 } else { sign },
61            exponent_sign,
62            exponent: if zero { "" } else { exponent },
63            shift: if zero {
64                0
65            } else {
66                digits.len() as i128 - fraction.len() as i128
67            },
68            digits: digits.trim_end_matches('0').to_owned(),
69        }
70    }
71
72    /// This exponent's signed decimal digits, left-padded to `width`.
73    fn exponent_digits(&self, width: usize) -> impl Iterator<Item = i128> {
74        let padding = std::iter::repeat_n(0, width.saturating_sub(self.exponent.len()));
75        let digits = self.exponent.chars().filter_map(|digit| digit.to_digit(10));
76        padding
77            .chain(digits)
78            .map(|digit| i128::from(digit) * self.exponent_sign)
79    }
80
81    /// This exponent minus `other`'s, held at a size no `shift` can reach
82    /// once past it: each further digit only moves it further away.
83    fn exponent_gap(&self, other: &Self) -> i128 {
84        const FAR: i128 = 1_000_000_000_000_000_000_000_000_000_000_000_000;
85        let width = self.exponent.len().max(other.exponent.len());
86        let digits = self
87            .exponent_digits(width)
88            .zip(other.exponent_digits(width));
89        digits.fold(0, |gap, (a, b)| (gap * 10 + a - b).clamp(-FAR, FAR))
90    }
91}
92
93/// Two JSON number literals in the order of their exact decimal values.
94pub(crate) fn compare_literals(a: &str, b: &str) -> Ordering {
95    let (a, b) = (Literal::new(a), Literal::new(b));
96    a.sign.cmp(&b.sign).then_with(|| {
97        let power = a.exponent_gap(&b) + a.shift - b.shift;
98        let magnitude = power.cmp(&0).then_with(|| a.digits.cmp(&b.digits));
99        if a.sign < 0 {
100            magnitude.reverse()
101        } else {
102            magnitude
103        }
104    })
105}
106
107/// `integer` against `float` without rounding. Inside `i128`'s range a
108/// float's whole part converts exactly. The bound is a literal because
109/// `i128::MAX as f64` rounds up to it.
110fn compare_integer_float(integer: i128, float: f64) -> Option<Ordering> {
111    const LIMIT: f64 = 170_141_183_460_469_231_731_687_303_715_884_105_728.0;
112    if float < -LIMIT {
113        return Some(Ordering::Greater);
114    }
115    if float >= LIMIT {
116        return Some(Ordering::Less);
117    }
118    match integer.cmp(&(float.trunc() as i128)) {
119        Ordering::Equal => 0.0_f64.partial_cmp(&float.fract()),
120        unequal => Some(unequal),
121    }
122}
123
124/// `value` with lexicographically sorted object keys at every depth,
125/// independent of serde_json's `preserve_order` feature. Array order is retained.
126pub fn canonical(value: serde_json::Value) -> serde_json::Value {
127    match value {
128        serde_json::Value::Object(map) => {
129            let mut entries: Vec<_> = map.into_iter().collect();
130            entries.sort_by(|(left, _), (right, _)| left.cmp(right));
131            let entries = entries
132                .into_iter()
133                .map(|(key, value)| (key, canonical(value)));
134            serde_json::Value::Object(entries.collect())
135        }
136        serde_json::Value::Array(items) => {
137            serde_json::Value::Array(items.into_iter().map(canonical).collect())
138        }
139        other => other,
140    }
141}
142
143/// Renders [`canonical`] JSON compactly.
144pub fn to_canonical_string(value: &serde_json::Value) -> String {
145    canonical(value.clone()).to_string()
146}
147
148/// Removes `key` from `map`, returning its value or `None` if absent.
149/// Remaining entries keep their relative iteration order with or without
150/// serde_json's `preserve_order` feature.
151pub fn remove_preserving_order(
152    map: &mut serde_json::Map<String, serde_json::Value>,
153    key: &str,
154) -> Option<serde_json::Value> {
155    let mut removed = None;
156    map.retain(|candidate, value| {
157        if candidate == key {
158            removed = Some(value.take());
159            false
160        } else {
161            true
162        }
163    });
164    removed
165}
166
167/// `b`'s top-level keys over `a`'s when both are objects, each replacing the
168/// whole value it covers; otherwise `a`. [`deep_merge`] merges nested objects.
169pub fn merge(a: serde_json::Value, b: serde_json::Value) -> serde_json::Value {
170    match (a, b) {
171        (serde_json::Value::Object(mut a_map), serde_json::Value::Object(b_map)) => {
172            b_map.into_iter().for_each(|(key, value)| {
173                a_map.insert(key, value);
174            });
175            serde_json::Value::Object(a_map)
176        }
177        (a, _) => a,
178    }
179}
180
181/// Merges `upper` into `body` in place: objects key by key, recursively; any
182/// other value, `null` and arrays included, replaces.
183pub fn deep_merge(
184    body: &mut serde_json::Map<String, serde_json::Value>,
185    upper: serde_json::Map<String, serde_json::Value>,
186) {
187    for (key, value) in upper {
188        match (body.get_mut(&key), value) {
189            (Some(serde_json::Value::Object(lower)), serde_json::Value::Object(upper)) => {
190                deep_merge(lower, upper)
191            }
192            (_, value) => {
193                body.insert(key, value);
194            }
195        }
196    }
197}
198
199/// The byte length of `value`'s JSON text, counted as it is written without
200/// building the string; 0 when `value` does not serialize.
201pub fn json_len(value: &impl serde::Serialize) -> usize {
202    struct Len(usize);
203    impl std::io::Write for Len {
204        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
205            self.0 += bytes.len();
206            Ok(bytes.len())
207        }
208
209        fn flush(&mut self) -> std::io::Result<()> {
210            Ok(())
211        }
212    }
213    let mut len = Len(0);
214    serde_json::to_writer(&mut len, value).map_or(0, |()| len.0)
215}
216
217/// The field names `T`'s derived `Deserialize` reads, as the input spells
218/// them. Empty for a type that does not deserialize as a plain struct, such
219/// as an enum or a struct with a flattened field.
220pub fn struct_fields<T: serde::de::DeserializeOwned>() -> &'static [&'static str] {
221    let mut fields: &'static [&'static str] = &[];
222    // The deserializer only records the field list and then fails, so the
223    // error is expected.
224    let _ = T::deserialize(FieldNames(&mut fields));
225    fields
226}
227
228/// A deserializer that records the field names a struct asks for.
229struct FieldNames<'a>(&'a mut &'static [&'static str]);
230
231impl<'de> Deserializer<'de> for FieldNames<'_> {
232    type Error = serde::de::value::Error;
233
234    fn deserialize_any<V: serde::de::Visitor<'de>>(self, _: V) -> Result<V::Value, Self::Error> {
235        Err(serde::de::Error::custom(
236            "only a struct's field names are read",
237        ))
238    }
239
240    fn deserialize_struct<V: serde::de::Visitor<'de>>(
241        self,
242        _: &'static str,
243        fields: &'static [&'static str],
244        _: V,
245    ) -> Result<V::Value, Self::Error> {
246        *self.0 = fields;
247        Err(serde::de::Error::custom(
248            "only a struct's field names are read",
249        ))
250    }
251
252    serde::forward_to_deserialize_any! {
253        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
254        bytes byte_buf option unit unit_struct newtype_struct seq tuple
255        tuple_struct map enum identifier ignored_any
256    }
257}
258
259/// Applies a request builder's `additional_params` call: `None` clears, and a
260/// value merges over the parameters earlier calls set. Merging combines JSON
261/// objects key by key; earlier parameters that are not an object are kept.
262pub(crate) fn merge_params(
263    existing: Option<serde_json::Value>,
264    params: Option<serde_json::Value>,
265) -> Option<serde_json::Value> {
266    Some(match (existing, params?) {
267        (Some(existing), params) => merge(existing, params),
268        (None, params) => params,
269    })
270}
271
272/// Normalize a provider-wire field that may contain encoded JSON in a string.
273///
274/// This deliberately unwraps [`serde_json::Value::String`] and is only for
275/// provider decoding, before a value enters Rig's canonical message model.
276pub fn value_to_json_string(value: &serde_json::Value) -> String {
277    match value {
278        serde_json::Value::String(s) => s.clone(),
279        other => other.to_string(),
280    }
281}
282
283/// Parse tool arguments from a streamed string payload.
284/// Some providers emit an empty string for parameterless tool calls; normalize that to `{}`.
285pub fn parse_tool_arguments(arguments: &str) -> serde_json::Result<serde_json::Value> {
286    if arguments.trim().is_empty() {
287        return Ok(serde_json::Value::Object(serde_json::Map::new()));
288    }
289
290    serde_json::from_str(arguments)
291}
292
293/// Whether `arguments` are a whole JSON object ([`parse_tool_arguments`]).
294/// Only a text that ends in `}` (or says nothing) can be one, so no other
295/// is parsed.
296pub fn is_whole_object(arguments: &str) -> bool {
297    let end = arguments.trim_end();
298    (end.is_empty() || end.ends_with('}'))
299        && matches!(
300            parse_tool_arguments(arguments),
301            Ok(serde_json::Value::Object(_))
302        )
303}
304
305/// The longest object a cut-off JSON text `text` still states: open strings,
306/// arrays and objects are closed and a dangling key or separator dropped, as
307/// pi's streaming JSON parse does. `None` when no prefix states an object.
308pub fn parse_partial_object(text: &str) -> Option<serde_json::Map<String, serde_json::Value>> {
309    // Bounds the work on a large cut-off input: the last valid cut is
310    // almost always near its end.
311    const MAX_ATTEMPTS: usize = 256;
312    let mut stack = Vec::new();
313    let mut in_string = false;
314    let mut escaped = false;
315    // Prefix lengths a value just ended at, with the containers open there.
316    let mut cuts: Vec<(usize, Vec<u8>, bool)> = Vec::new();
317    let bytes = text.as_bytes();
318    for (at, byte) in bytes.iter().enumerate() {
319        if in_string {
320            match (escaped, *byte) {
321                (true, _) => escaped = false,
322                (false, b'\\') => escaped = true,
323                (false, b'"') => {
324                    in_string = false;
325                    cuts.push((at + 1, stack.clone(), false));
326                }
327                (false, _) => {}
328            }
329            continue;
330        }
331        match byte {
332            b'"' => in_string = true,
333            b'{' | b'[' => {
334                stack.push(*byte);
335                cuts.push((at + 1, stack.clone(), false));
336            }
337            b'}' | b']' => {
338                stack.pop();
339                cuts.push((at + 1, stack.clone(), false));
340            }
341            b if b.is_ascii_alphanumeric() || *b == b'.' || *b == b'-' || *b == b'+' => {
342                let next = bytes.get(at + 1).copied();
343                if !next.is_some_and(|n| {
344                    n.is_ascii_alphanumeric() || n == b'.' || n == b'-' || n == b'+'
345                }) {
346                    cuts.push((at + 1, stack.clone(), false));
347                }
348            }
349            _ => {}
350        }
351    }
352    if in_string {
353        let at = text.len() - usize::from(escaped);
354        cuts.push((at, stack.clone(), true));
355    }
356    cuts.iter()
357        .rev()
358        .take(MAX_ATTEMPTS)
359        .find_map(|(at, open, quote)| {
360            let mut candidate = text.get(..*at)?.to_owned();
361            if *quote {
362                candidate.push('"');
363            }
364            for container in open.iter().rev() {
365                candidate.push(if *container == b'{' { '}' } else { ']' });
366            }
367            match serde_json::from_str(&candidate) {
368                Ok(serde_json::Value::Object(object)) => Some(object),
369                _ => None,
370            }
371        })
372}
373
374/// The best object a tool call's argument text states so far, for showing a
375/// call while it streams. It never fails: complete JSON parses as is, text
376/// with raw control characters or invalid escapes is repaired first, a
377/// cut-off prefix keeps the longest object it states
378/// ([`parse_partial_object`]), and anything else is an empty object, as is
379/// a top level that is not an object.
380///
381/// It is for display only. A call's arguments are what its end states, and
382/// only those are validated and executed.
383///
384/// ```
385/// use rig_core::streaming::parse_partial_arguments;
386///
387/// let partial = parse_partial_arguments(r#"{"path": "notes.md", "content": "Hel"#);
388/// assert_eq!(partial["path"], "notes.md");
389/// assert_eq!(partial["content"], "Hel");
390/// ```
391pub fn parse_partial_arguments(text: &str) -> serde_json::Map<String, serde_json::Value> {
392    if text.trim().is_empty() {
393        return serde_json::Map::new();
394    }
395    let repaired = repair_json(text);
396    let complete = serde_json::from_str(text)
397        .ok()
398        .or_else(|| serde_json::from_str(&repaired).ok());
399    if let Some(value) = complete {
400        return match value {
401            serde_json::Value::Object(object) => object,
402            _ => serde_json::Map::new(),
403        };
404    }
405    let cut = without_partial_escape(&repaired);
406    parse_partial_object(cut)
407        .or_else(|| parse_partial_object(text))
408        .unwrap_or_default()
409}
410
411/// `text` with raw control characters inside strings escaped and each
412/// backslash that starts no valid escape doubled, as models sometimes write
413/// them.
414fn repair_json(text: &str) -> String {
415    let mut repaired = String::with_capacity(text.len());
416    let mut in_string = false;
417    let mut chars = text.chars().peekable();
418    while let Some(c) = chars.next() {
419        if !in_string {
420            in_string = c == '"';
421            repaired.push(c);
422            continue;
423        }
424        match c {
425            '"' => {
426                in_string = false;
427                repaired.push(c);
428            }
429            '\\' => match chars.peek() {
430                Some('"' | '\\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' | 'u') => {
431                    repaired.push(c);
432                    if let Some(next) = chars.next() {
433                        repaired.push(next);
434                    }
435                }
436                // A trailing backslash may begin an escape the next fragment ends.
437                None => repaired.push(c),
438                Some(_) => repaired.push_str("\\\\"),
439            },
440            '\n' => repaired.push_str("\\n"),
441            '\r' => repaired.push_str("\\r"),
442            '\t' => repaired.push_str("\\t"),
443            c if c.is_control() => {
444                use std::fmt::Write as _;
445                // Writing to a `String` cannot fail.
446                let _ = write!(repaired, "\\u{:04x}", u32::from(c));
447            }
448            c => repaired.push(c),
449        }
450    }
451    repaired
452}
453
454/// `text` without a `\u` escape its end cuts short, which would otherwise
455/// cost the whole string it ends.
456fn without_partial_escape(text: &str) -> &str {
457    let bytes = text.as_bytes();
458    let tail = bytes.len().saturating_sub(5);
459    let Some(at) = (tail..bytes.len())
460        .rev()
461        .find(|at| bytes.get(*at..*at + 2) == Some(b"\\u"))
462    else {
463        return text;
464    };
465    let digits = bytes.get(at + 2..).unwrap_or_default();
466    // A preceding backslash run of odd length escapes this backslash itself.
467    let escaping = bytes
468        .get(..at)
469        .unwrap_or_default()
470        .iter()
471        .rev()
472        .take_while(|byte| **byte == b'\\')
473        .count();
474    if digits.len() < 4 && digits.iter().all(u8::is_ascii_hexdigit) && escaping % 2 == 0 {
475        text.get(..at).unwrap_or(text)
476    } else {
477        text
478    }
479}
480
481/// Deserializes `T`, mapping an explicit `null` to `T::default()`.
482///
483/// Driven through `deserialize_option` rather than `deserialize_any`; the two
484/// agree only for self-describing formats, which is all rig decodes (JSON).
485pub fn null_or_default<'de, T, D>(deserializer: D) -> Result<T, D::Error>
486where
487    T: Deserialize<'de> + Default,
488    D: Deserializer<'de>,
489{
490    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
491}
492
493/// Deserializes `T` through a [`serde_json::Value`]: the reader for a field
494/// holding floats that serde may buffer, under `#[serde(flatten)]` or in a
495/// tagged or untagged enum. With serde_json's `arbitrary_precision` on
496/// anywhere in a build, a buffered float is a map that only a `Value` reads;
497/// the `Value` then gives `T` each number as written. A format that is not
498/// human-readable, such as bincode, reads `T` directly. An `Option` field
499/// using it also needs `#[serde(default)]` to read a missing field as `None`,
500/// which also lets a shorter array read; where that would widen what a type
501/// reads, give `floats` to the field holding the type instead.
502pub fn floats<'de, T, D>(deserializer: D) -> Result<T, D::Error>
503where
504    T: serde::de::DeserializeOwned,
505    D: Deserializer<'de>,
506{
507    if !deserializer.is_human_readable() {
508        return T::deserialize(deserializer);
509    }
510    T::deserialize(serde_json::Value::deserialize(deserializer)?).map_err(serde::de::Error::custom)
511}
512
513/// Reads `T` from `value` as it would read from the value's JSON text. With
514/// serde_json's `arbitrary_precision` on, a `Value` cannot hand an integer
515/// beyond u64 or i64 to serde's buffer for a tagged, untagged or flattened
516/// type, while the text can. Only a value holding such an integer is read
517/// from its text, so a build without the feature reads `value` directly.
518///
519/// # Errors
520///
521/// When `value` does not read as a `T`.
522pub fn from_value<T: serde::de::DeserializeOwned>(
523    value: &serde_json::Value,
524) -> serde_json::Result<T> {
525    from_value_seed(std::marker::PhantomData, value)
526}
527
528/// [`from_value`] for a seed, such as a reflection deserializer: reads
529/// `value` through `seed` as it would read the value's JSON text.
530///
531/// # Errors
532///
533/// When `value` does not read through `seed`.
534pub fn from_value_seed<S, V>(seed: S, value: &serde_json::Value) -> serde_json::Result<V>
535where
536    S: for<'de> serde::de::DeserializeSeed<'de, Value = V>,
537{
538    if !holds_wide_integer(value) {
539        return seed.deserialize(value);
540    }
541    let text = value.to_string();
542    let mut deserializer = serde_json::Deserializer::from_str(&text);
543    let read = seed.deserialize(&mut deserializer)?;
544    deserializer.end()?;
545    Ok(read)
546}
547
548/// Whether `value` holds an integer beyond u64 and i64.
549pub(crate) fn holds_wide_integer(value: &serde_json::Value) -> bool {
550    match value {
551        serde_json::Value::Number(number) => {
552            !number.is_u64()
553                && !number.is_i64()
554                && (number.as_u128().is_some() || number.as_i128().is_some())
555        }
556        serde_json::Value::Array(items) => items.iter().any(holds_wide_integer),
557        serde_json::Value::Object(fields) => fields.values().any(holds_wide_integer),
558        _ => false,
559    }
560}
561
562#[cfg(test)]
563mod tests;
564
565/// Lenient reads of a provider reply: each accessor gives `None`, or an
566/// empty slice, for a field that is missing or of another type, and never
567/// fails. Decoders read replies through it, so a field no block or finish
568/// needs can never fail a reply.
569///
570/// ```
571/// use rig_core::json_utils::Lenient;
572/// use serde_json::json;
573///
574/// let reply = json!({"id": "r1", "usage": {"input_tokens": "7"}, "output": null});
575/// assert_eq!(reply.str("id"), Some("r1"));
576/// assert_eq!(reply.at("/usage/input_tokens").and_then(Lenient::as_u64_lenient), Some(7));
577/// assert!(reply.arr("output").is_empty());
578/// ```
579pub trait Lenient {
580    /// The string at `key`.
581    fn str(&self, key: &str) -> Option<&str>;
582    /// The unsigned integer at `key`, from a number or a numeric string.
583    fn u64(&self, key: &str) -> Option<u64>;
584    /// The number at `key`, from a number or a numeric string.
585    fn f64(&self, key: &str) -> Option<f64>;
586    /// The boolean at `key`.
587    fn bool(&self, key: &str) -> Option<bool>;
588    /// The object at `key`.
589    fn obj(&self, key: &str) -> Option<&serde_json::Map<String, serde_json::Value>>;
590    /// The array at `key`, empty when absent or of another type.
591    fn arr(&self, key: &str) -> &[serde_json::Value];
592    /// The value at a JSON pointer, `None` for `null`.
593    fn at(&self, pointer: &str) -> Option<&serde_json::Value>;
594    /// This value as an unsigned integer, from a number or a numeric string.
595    fn as_u64_lenient(&self) -> Option<u64>;
596}
597
598impl Lenient for serde_json::Value {
599    fn str(&self, key: &str) -> Option<&str> {
600        self.get(key)?.as_str()
601    }
602
603    fn u64(&self, key: &str) -> Option<u64> {
604        self.get(key)?.as_u64_lenient()
605    }
606
607    fn f64(&self, key: &str) -> Option<f64> {
608        match self.get(key)? {
609            serde_json::Value::Number(number) => number.as_f64(),
610            serde_json::Value::String(text) => text.trim().parse().ok(),
611            _ => None,
612        }
613    }
614
615    fn bool(&self, key: &str) -> Option<bool> {
616        self.get(key)?.as_bool()
617    }
618
619    fn obj(&self, key: &str) -> Option<&serde_json::Map<String, serde_json::Value>> {
620        self.get(key)?.as_object()
621    }
622
623    fn arr(&self, key: &str) -> &[serde_json::Value] {
624        self.get(key)
625            .and_then(serde_json::Value::as_array)
626            .map_or(&[], Vec::as_slice)
627    }
628
629    fn at(&self, pointer: &str) -> Option<&serde_json::Value> {
630        self.pointer(pointer).filter(|value| !value.is_null())
631    }
632
633    fn as_u64_lenient(&self) -> Option<u64> {
634        match self {
635            serde_json::Value::Number(number) => number.as_u64().or_else(|| {
636                number
637                    .as_f64()
638                    .filter(|float| *float >= 0.0 && float.fract() == 0.0)
639                    .map(|float| float as u64)
640            }),
641            serde_json::Value::String(text) => text.trim().parse().ok(),
642            _ => None,
643        }
644    }
645}