Skip to main content

php_std/
yaml.rs

1//! `yaml_parse()` (ext-yaml 2.3 over libyaml 0.2.5) with the default ini
2//! settings: timestamps, `!!binary` and `!php/object` stay strings.
3//!
4//! Documents are split into events by libyaml itself (`unsafe-libyaml`, the
5//! C library translated to Rust), so exactly the same inputs are accepted and
6//! refused; the events are turned into PHP values as ext-yaml's `parse.c`
7//! and `detect.c` do: YAML 1.1 booleans (`yes`, `off`, `y`), integers in
8//! binary, octal (`0755`), hexadecimal, sexagesimal (`1:20`) and with `_` or
9//! `,` separators, floats whose exponent has a sign, merge keys (`<<`), and
10//! keys converted like array offsets.
11//!
12//! PHP: anchors are PHP references. An alias of a node that is still being
13//! built (a recursive structure) has no value here: it is refused as an
14//! unknown alias.
15//!
16//! Nesting deeper than [`MAX_DEPTH`] refuses the document, as the other
17//! codecs in this crate do. ext-yaml has no limit, and walking an unbounded
18//! document recurses until the stack overflows, which aborts the process.
19
20use std::collections::HashMap;
21use std::mem::MaybeUninit;
22
23use crate::format::{dval_to_lval, str_to_float, str_to_int};
24use crate::{Array, ArrayKey, Str, Value};
25
26const NULL_TAG: &[u8] = b"tag:yaml.org,2002:null";
27const BOOL_TAG: &[u8] = b"tag:yaml.org,2002:bool";
28const INT_TAG: &[u8] = b"tag:yaml.org,2002:int";
29const FLOAT_TAG: &[u8] = b"tag:yaml.org,2002:float";
30const TIMESTAMP_TAG: &[u8] = b"tag:yaml.org,2002:timestamp";
31const MERGE_TAG: &[u8] = b"tag:yaml.org,2002:merge";
32const NONSPECIFIC_TAG: &[u8] = b"!";
33
34/// The deepest nesting of mappings and sequences [`parse`] reads. A deeper
35/// document is refused (`None`) instead of recursing until the stack
36/// overflows. Real configuration files stay far below it. At this depth a
37/// release build needs under 768 KB of stack, well inside a 2 MB coroutine.
38pub const MAX_DEPTH: usize = 512;
39
40/// A parser event, copied out of libyaml.
41#[derive(Debug, Clone, PartialEq)]
42enum Event {
43    StreamStart,
44    StreamEnd,
45    DocumentStart,
46    DocumentEnd,
47    Alias(Vec<u8>),
48    Scalar(Scalar),
49    SequenceStart(Option<Vec<u8>>),
50    SequenceEnd,
51    MappingStart(Option<Vec<u8>>),
52    MappingEnd,
53    /// No event: what libyaml returns after an error or the end of the stream.
54    Nothing,
55}
56
57#[derive(Debug, Clone, PartialEq)]
58struct Scalar {
59    anchor: Option<Vec<u8>>,
60    tag: Option<Vec<u8>>,
61    value: Vec<u8>,
62    plain_implicit: bool,
63    quoted_implicit: bool,
64    /// Plain (or any) style: not quoted, literal or folded.
65    plain: bool,
66}
67
68impl Scalar {
69    fn tag_is(&self, tag: &[u8]) -> bool {
70        self.tag.as_deref() == Some(tag)
71    }
72
73    fn not_implicit_and_tag_is(&self, tag: &[u8]) -> bool {
74        !self.quoted_implicit && !self.plain_implicit && self.tag_is(tag)
75    }
76
77    fn not_quoted_or_tag_is(&self, tag: &[u8]) -> bool {
78        self.plain && (self.plain_implicit || self.tag_is(tag))
79    }
80}
81
82/// libyaml's parser over one input.
83struct Parser<'a> {
84    parser: Box<MaybeUninit<unsafe_libyaml::yaml_parser_t>>,
85    _input: &'a [u8],
86}
87
88/// A C string of libyaml, copied.
89///
90/// # Safety
91///
92/// `p` is null or points at a NUL-terminated string.
93unsafe fn c_bytes(p: *const u8) -> Option<Vec<u8>> {
94    if p.is_null() {
95        return None;
96    }
97    // SAFETY: the caller guarantees a NUL-terminated string.
98    let s = unsafe { std::ffi::CStr::from_ptr(p.cast()) };
99    Some(s.to_bytes().to_vec())
100}
101
102impl<'a> Parser<'a> {
103    fn new(input: &'a [u8]) -> Option<Self> {
104        let mut parser = Box::new(MaybeUninit::<unsafe_libyaml::yaml_parser_t>::uninit());
105        // SAFETY: `yaml_parser_initialize` initialises the parser it is given;
106        // the input outlives the parser (`_input` borrows it).
107        unsafe {
108            if unsafe_libyaml::yaml_parser_initialize(parser.as_mut_ptr()).fail {
109                return None;
110            }
111            unsafe_libyaml::yaml_parser_set_input_string(parser.as_mut_ptr(), input.as_ptr(), input.len() as _);
112        }
113        Some(Self { parser, _input: input })
114    }
115
116    /// The next event, or `None` on a reader, scanner or parser error.
117    fn next(&mut self) -> Option<Event> {
118        let mut raw = MaybeUninit::<unsafe_libyaml::yaml_event_t>::uninit();
119        // SAFETY: the parser was initialised in `new`; on success the event is
120        // initialised, read according to its type, then deleted once.
121        unsafe {
122            if unsafe_libyaml::yaml_parser_parse(self.parser.as_mut_ptr(), raw.as_mut_ptr()).fail {
123                return None;
124            }
125            let event = raw.as_mut_ptr();
126            let converted = match (*event).type_ {
127                unsafe_libyaml::YAML_STREAM_START_EVENT => Event::StreamStart,
128                unsafe_libyaml::YAML_STREAM_END_EVENT => Event::StreamEnd,
129                unsafe_libyaml::YAML_DOCUMENT_START_EVENT => Event::DocumentStart,
130                unsafe_libyaml::YAML_DOCUMENT_END_EVENT => Event::DocumentEnd,
131                unsafe_libyaml::YAML_ALIAS_EVENT => {
132                    Event::Alias(c_bytes((*event).data.alias.anchor).unwrap_or_default())
133                }
134                unsafe_libyaml::YAML_SCALAR_EVENT => {
135                    let s = (*event).data.scalar;
136                    let value = if s.value.is_null() {
137                        Vec::new()
138                    } else {
139                        std::slice::from_raw_parts(s.value, s.length as usize).to_vec()
140                    };
141                    Event::Scalar(Scalar {
142                        anchor: c_bytes(s.anchor),
143                        tag: c_bytes(s.tag),
144                        value,
145                        plain_implicit: s.plain_implicit,
146                        quoted_implicit: s.quoted_implicit,
147                        plain: matches!(
148                            s.style,
149                            unsafe_libyaml::YAML_PLAIN_SCALAR_STYLE | unsafe_libyaml::YAML_ANY_SCALAR_STYLE
150                        ),
151                    })
152                }
153                unsafe_libyaml::YAML_SEQUENCE_START_EVENT => {
154                    Event::SequenceStart(c_bytes((*event).data.sequence_start.anchor))
155                }
156                unsafe_libyaml::YAML_SEQUENCE_END_EVENT => Event::SequenceEnd,
157                unsafe_libyaml::YAML_MAPPING_START_EVENT => {
158                    Event::MappingStart(c_bytes((*event).data.mapping_start.anchor))
159                }
160                unsafe_libyaml::YAML_MAPPING_END_EVENT => Event::MappingEnd,
161                _ => Event::Nothing,
162            };
163            unsafe_libyaml::yaml_event_delete(event);
164            Some(converted)
165        }
166    }
167}
168
169impl Drop for Parser<'_> {
170    fn drop(&mut self) {
171        // SAFETY: the parser was initialised in `new` and is deleted once.
172        unsafe { unsafe_libyaml::yaml_parser_delete(self.parser.as_mut_ptr()) }
173    }
174}
175
176/// A node as ext-yaml builds it: its value, whether PHP holds it as a
177/// reference (it has an anchor or is an alias), and which of its direct
178/// children are references (a merge key merges only those).
179struct Node {
180    value: Value,
181    is_ref: bool,
182    child_refs: Vec<ArrayKey>,
183}
184
185impl Node {
186    fn plain(value: Value) -> Self {
187        Node { value, is_ref: false, child_refs: Vec::new() }
188    }
189}
190
191struct State<'a> {
192    parser: Parser<'a>,
193    /// The last event read; `None` after an error.
194    event: Option<Event>,
195    aliases: HashMap<Vec<u8>, Value>,
196    /// Mappings and sequences currently open.
197    depth: usize,
198    /// Set when a node would nest deeper than [`MAX_DEPTH`]. A mapping
199    /// returns what it has so far when a value fails, so the refusal is
200    /// recorded here and checked once the document is read.
201    too_deep: bool,
202}
203
204impl State<'_> {
205    fn next(&mut self) -> bool {
206        self.event = self.parser.next();
207        self.event.is_some()
208    }
209
210    /// `get_next_element()`: the next node, `None` at a halting event or
211    /// on failure.
212    fn element(&mut self) -> Option<Node> {
213        if !self.next() {
214            return None;
215        }
216        match self.event.clone()? {
217            Event::DocumentEnd | Event::MappingEnd | Event::SequenceEnd | Event::StreamEnd => None,
218            Event::DocumentStart => self.document(),
219            Event::MappingStart(anchor) => self.nested(|state| state.mapping(anchor)),
220            Event::SequenceStart(anchor) => self.nested(|state| state.sequence(anchor)),
221            Event::Scalar(scalar) => {
222                let value = eval_scalar(&scalar);
223                if let Some(anchor) = scalar.anchor {
224                    self.aliases.insert(anchor, value.clone());
225                    return Some(Node { value, is_ref: true, child_refs: Vec::new() });
226                }
227                Some(Node::plain(value))
228            }
229            Event::Alias(anchor) => {
230                let value = self.aliases.get(&anchor)?.clone();
231                Some(Node { value, is_ref: true, child_refs: Vec::new() })
232            }
233            Event::StreamStart | Event::Nothing => None,
234        }
235    }
236
237    /// Reads a mapping or sequence one level deeper, or refuses it past
238    /// [`MAX_DEPTH`].
239    fn nested(&mut self, read: impl FnOnce(&mut Self) -> Option<Node>) -> Option<Node> {
240        if self.depth >= MAX_DEPTH {
241            self.too_deep = true;
242            return None;
243        }
244        self.depth += 1;
245        let node = read(self);
246        self.depth -= 1;
247        node
248    }
249
250    fn document(&mut self) -> Option<Node> {
251        self.aliases.clear();
252        self.depth = 0;
253        self.too_deep = false;
254        let node = self.element();
255        if self.too_deep {
256            return None;
257        }
258        // The end of the document must follow; an error reading it is
259        // ignored, as ext-yaml does.
260        if self.next() && self.event != Some(Event::DocumentEnd) {
261            return None;
262        }
263        node
264    }
265
266    fn mapping(&mut self, anchor: Option<Vec<u8>>) -> Option<Node> {
267        let mut array = Array::default();
268        let mut refs: Vec<ArrayKey> = Vec::new();
269        while let Some(key) = self.element() {
270            let key_event = self.event.clone();
271            // ext-yaml 2.3 returns what it has so far when a value fails
272            // (an unknown alias, an error), without reading the mapping's end.
273            let Some(value) = self.element() else {
274                return Some(self.anchored(anchor, Value::Array(array), refs));
275            };
276            let merge_key = matches!(&key_event, Some(Event::Scalar(s)) if s.not_quoted_or_tag_is(MERGE_TAG))
277                && matches!(&key.value, Value::Str(s) if s.as_bytes() == b"<<");
278            if merge_key && matches!(value.value, Value::Array(_)) {
279                let Value::Array(source) = &value.value else { unreachable!() };
280                if matches!(self.event, Some(Event::Alias(_))) {
281                    merge(&mut array, source);
282                } else {
283                    for (k, v) in source.iter() {
284                        if let Value::Array(inner) = v
285                            && value.child_refs.iter().any(|r| r.as_ref() == k)
286                        {
287                            merge(&mut array, inner);
288                        }
289                    }
290                }
291                continue;
292            }
293            let offset = match &key.value {
294                Value::Float(f) => ArrayKey::Int(dval_to_lval(*f)),
295                Value::Bool(b) => ArrayKey::Int(i64::from(*b)),
296                Value::Int(i) => ArrayKey::Int(*i),
297                Value::Null => ArrayKey::Str(Str::default()),
298                Value::Str(s) => ArrayKey::normalize(s.clone()),
299                // Illegal offset type: the pair is dropped (PHP warns).
300                _ => continue,
301            };
302            refs.retain(|r| *r != offset);
303            if value.is_ref {
304                refs.push(offset.clone());
305            }
306            array.set(offset, value.value);
307        }
308        if self.event != Some(Event::MappingEnd) {
309            return None;
310        }
311        Some(self.anchored(anchor, Value::Array(array), refs))
312    }
313
314    fn sequence(&mut self, anchor: Option<Vec<u8>>) -> Option<Node> {
315        let mut array = Array::default();
316        let mut refs = Vec::new();
317        while let Some(node) = self.element() {
318            if node.is_ref {
319                refs.push(ArrayKey::Int(array.len() as i64));
320            }
321            let _ = array.push(node.value);
322        }
323        if self.event != Some(Event::SequenceEnd) {
324            return None;
325        }
326        Some(self.anchored(anchor, Value::Array(array), refs))
327    }
328
329    fn anchored(&mut self, anchor: Option<Vec<u8>>, value: Value, child_refs: Vec<ArrayKey>) -> Node {
330        match anchor {
331            Some(anchor) => {
332                self.aliases.insert(anchor, value.clone());
333                Node { value, is_ref: true, child_refs }
334            }
335            None => Node { value, is_ref: false, child_refs },
336        }
337    }
338}
339
340/// `zend_hash_merge($target, $source, overwrite: false)`: adds the entries
341/// whose key `target` lacks.
342fn merge(target: &mut Array, source: &Array) {
343    for (k, v) in source.iter() {
344        let key = k.to_owned();
345        if !target.contains_key(&key) {
346            target.set(key, v.clone());
347        }
348    }
349}
350
351/// `yaml_parse($input)`: the first document of `input` as a PHP value, or
352/// `None` where PHP returns `false` (and warns): a malformed document or an
353/// unknown alias, or nesting deeper than [`MAX_DEPTH`]. An input without a
354/// document is `null`.
355///
356/// PHP: `yaml_parse($input)` with `yaml.decode_timestamp`, `decode_binary`
357/// and `decode_php` off (their defaults). Only the first document is read:
358/// errors after it are not reported.
359///
360/// ```
361/// use php_std::{Value, yaml};
362///
363/// let Some(Value::Array(config)) = yaml::parse(b"enabled: yes\nmode: 0755\nratio: 1.5\n") else { panic!() };
364/// assert_eq!(config.get_str("enabled"), Some(&Value::Bool(true)));
365/// assert_eq!(config.get_str("mode"), Some(&Value::Int(493)));
366/// assert_eq!(config.get_str("ratio"), Some(&Value::Float(1.5)));
367/// assert_eq!(yaml::parse(b"a: *missing"), None);
368/// ```
369///
370/// ```php
371/// $config = yaml_parse("enabled: yes\nmode: 0755\nratio: 1.5\n");
372/// var_dump($config['enabled'], $config['mode'], $config['ratio']); // bool(true) int(493) float(1.5)
373/// var_dump(@yaml_parse('a: *missing')); // bool(false)
374/// ```
375pub fn parse(input: &[u8]) -> Option<Value> {
376    let parser = Parser::new(input)?;
377    let mut state = State { parser, event: None, aliases: HashMap::new(), depth: 0, too_deep: false };
378    loop {
379        if !state.next() {
380            return None;
381        }
382        match state.event {
383            Some(Event::StreamEnd) => return Some(Value::Null),
384            Some(Event::DocumentStart) => return state.document().map(|n| n.value),
385            Some(Event::Nothing) | None => return None,
386            _ => {}
387        }
388    }
389}
390
391/// `eval_scalar()`: a scalar's PHP value.
392fn eval_scalar(s: &Scalar) -> Value {
393    let value = &s.value;
394    let string = || Value::Str(Str::copy_from(value));
395    if s.tag_is(NONSPECIFIC_TAG) || s.quoted_implicit {
396        return string();
397    }
398    if is_null(s) {
399        return Value::Null;
400    }
401    if let Some(b) = is_bool(s) {
402        return Value::Bool(b);
403    }
404    if s.plain_implicit || s.tag_is(INT_TAG) || s.tag_is(FLOAT_TAG) {
405        match numeric(value) {
406            Some(Number::Int(i)) if !s.plain_implicit && s.tag_is(FLOAT_TAG) => return Value::Float(i as f64),
407            Some(Number::Float(f)) if !s.plain_implicit && s.tag_is(INT_TAG) => {
408                return Value::Int(dval_to_lval(f));
409            }
410            Some(Number::Int(i)) => return Value::Int(i),
411            Some(Number::Float(f)) => return Value::Float(f),
412            None if s.not_implicit_and_tag_is(FLOAT_TAG) => return Value::Float(str_to_float(value)),
413            None if s.not_implicit_and_tag_is(INT_TAG) => return Value::Int(str_to_int(value)),
414            None => {}
415        }
416    }
417    // Timestamps, binary and PHP objects stay strings with the default ini.
418    let _ = s.not_implicit_and_tag_is(TIMESTAMP_TAG);
419    string()
420}
421
422/// `scalar_is_null()`.
423fn is_null(s: &Scalar) -> bool {
424    if s.quoted_implicit {
425        return false;
426    }
427    if s.plain_implicit {
428        let v = s.value.as_slice();
429        return v.is_empty() || v == b"~" || v == b"NULL" || v == b"Null" || v == b"null";
430    }
431    s.tag_is(NULL_TAG)
432}
433
434/// `scalar_is_bool()`: `Some(bool)`, or `None` when the scalar is not one.
435fn is_bool(s: &Scalar) -> Option<bool> {
436    let v = s.value.as_slice();
437    if s.not_quoted_or_tag_is(BOOL_TAG) {
438        const TRUE: &[&[u8]] = &[b"Y", b"y", b"YES", b"Yes", b"yes", b"TRUE", b"True", b"true", b"ON", b"On", b"on"];
439        const FALSE: &[&[u8]] =
440            &[b"N", b"n", b"NO", b"No", b"no", b"FALSE", b"False", b"false", b"OFF", b"Off", b"off"];
441        if TRUE.contains(&v) {
442            return Some(true);
443        }
444        if FALSE.contains(&v) {
445            return Some(false);
446        }
447        return None;
448    }
449    if s.not_implicit_and_tag_is(BOOL_TAG) {
450        return Some(!(v.is_empty() || v == b"0"));
451    }
452    None
453}
454
455enum Number {
456    Int(i64),
457    Float(f64),
458}
459
460/// C's `strtol(s, NULL, base)` as musl implements it: optional whitespace,
461/// sign and (base 16) `0x` prefix; saturates on overflow.
462fn strtol(s: &[u8], base: u32) -> i64 {
463    let mut i = 0;
464    while i < s.len() && (s[i] == b' ' || (b'\t'..=b'\r').contains(&s[i])) {
465        i += 1;
466    }
467    let negative = s.get(i) == Some(&b'-');
468    if matches!(s.get(i), Some(b'-' | b'+')) {
469        i += 1;
470    }
471    if base == 16 && s.get(i) == Some(&b'0') && matches!(s.get(i + 1), Some(b'x' | b'X')) {
472        i += 2;
473    }
474    let mut n: i128 = 0;
475    while let Some(d) = s.get(i).and_then(|&c| (c as char).to_digit(base)) {
476        n = (n * i128::from(base) + i128::from(d)).min(i128::from(u64::MAX) + 1);
477        i += 1;
478    }
479    let n = if negative { -n } else { n };
480    n.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
481}
482
483/// C's `atol` as musl implements it: optional whitespace and sign, then
484/// digits accumulated with wrapping.
485fn atol(s: &[u8]) -> i64 {
486    let mut i = 0;
487    while i < s.len() && (s[i] == b' ' || (b'\t'..=b'\r').contains(&s[i])) {
488        i += 1;
489    }
490    let negative = s.get(i) == Some(&b'-');
491    if matches!(s.get(i), Some(b'-' | b'+')) {
492        i += 1;
493    }
494    let mut n: i64 = 0;
495    while let Some(&c) = s.get(i).filter(|c| c.is_ascii_digit()) {
496        n = n.wrapping_mul(10).wrapping_sub(i64::from(c - b'0'));
497        i += 1;
498    }
499    if negative { n } else { n.wrapping_neg() }
500}
501
502/// `zend_strtod` of the leading decimal number.
503fn strtod(s: &[u8]) -> f64 {
504    str_to_float(s)
505}
506
507fn sexagesimal_l(buf: &[u8]) -> i64 {
508    let mut n: i64 = 0;
509    for part in buf.split(|c| !c.is_ascii_digit()).filter(|p| !p.is_empty()) {
510        n = n.wrapping_mul(60).wrapping_add(strtol(part, 10));
511    }
512    n
513}
514
515fn sexagesimal_d(buf: &[u8]) -> f64 {
516    let mut d = 0.0;
517    let mut i = 0;
518    loop {
519        while i < buf.len() && buf[i] != b'.' && !buf[i].is_ascii_digit() {
520            i += 1;
521        }
522        if i >= buf.len() || buf[i] == b'.' {
523            return d;
524        }
525        d = d * 60.0 + strtod(&buf[i..]);
526        while i < buf.len() && buf[i].is_ascii_digit() {
527            i += 1;
528        }
529    }
530}
531
532/// `scalar_is_numeric()`: the number a plain scalar spells, if any.
533fn numeric(input: &[u8]) -> Option<Number> {
534    let mut v = input;
535    while let Some((&last, rest)) = v.split_last() {
536        if last == b' ' || last == b'\t' {
537            v = rest;
538        } else {
539            break;
540        }
541    }
542    while let Some((&first, rest)) = v.split_first() {
543        if first == b' ' || first == b'\t' {
544            v = rest;
545        } else {
546            break;
547        }
548    }
549    if v.is_empty() || v == b"." {
550        return None;
551    }
552    if v == b".NAN" || v == b".NaN" || v == b".nan" {
553        return Some(Number::Float(f64::NAN));
554    }
555    let negative = v[0] == b'-';
556    if v[0] == b'+' || v[0] == b'-' {
557        v = &v[1..];
558    }
559    if v.is_empty() {
560        return None;
561    }
562    if v == b".INF" || v == b".Inf" || v == b".inf" {
563        return Some(Number::Float(if negative { f64::NEG_INFINITY } else { f64::INFINITY }));
564    }
565    // Bytes past the end read as the NUL terminator, as in C.
566    let at = |i: usize| v.get(i).copied().unwrap_or(0);
567    let end = v.len();
568    let mut buf: Vec<u8> = Vec::with_capacity(end + 3);
569    if negative {
570        buf.push(b'-');
571    }
572    let mut i = 0;
573
574    #[derive(PartialEq)]
575    enum Kind {
576        Binary,
577        Octal,
578        Hex,
579        Decimal,
580        SexaInt,
581        SexaFloat,
582        Float,
583    }
584
585    let kind;
586    // Where to continue: sexagesimal or float checks.
587    let mut goto_sexa = false;
588    let mut goto_float = false;
589    if at(0) == b'0' {
590        buf.push(b'0');
591        i = 1;
592        if i == end {
593            return Some(Number::Int(0));
594        }
595        match at(i) {
596            b'b' => {
597                buf.push(b'b');
598                i += 1;
599                if i == end {
600                    return None;
601                }
602                while i < end && (at(i) == b'_' || at(i) == b'0') {
603                    i += 1;
604                }
605                if i == end {
606                    return Some(Number::Int(0));
607                }
608                while i < end {
609                    match at(i) {
610                        b'_' => i += 1,
611                        c @ (b'0' | b'1') => {
612                            buf.push(c);
613                            i += 1;
614                        }
615                        _ => return None,
616                    }
617                }
618                kind = Kind::Binary;
619            }
620            b'x' => {
621                buf.push(b'x');
622                i += 1;
623                if i == end {
624                    return None;
625                }
626                while i < end && (at(i) == b'_' || at(i) == b'0') {
627                    i += 1;
628                }
629                if i == end {
630                    return Some(Number::Int(0));
631                }
632                while i < end {
633                    match at(i) {
634                        b'_' => i += 1,
635                        c if c.is_ascii_hexdigit() => {
636                            buf.push(c);
637                            i += 1;
638                        }
639                        _ => return None,
640                    }
641                }
642                kind = Kind::Hex;
643            }
644            c if c == b'_' || (b'0'..=b'7').contains(&c) => {
645                while i < end {
646                    match at(i) {
647                        b'_' => i += 1,
648                        c @ b'0'..=b'7' => {
649                            buf.push(c);
650                            i += 1;
651                        }
652                        _ => return None,
653                    }
654                }
655                kind = Kind::Octal;
656            }
657            b'.' => {
658                goto_float = true;
659                kind = Kind::Float;
660            }
661            b':' => {
662                goto_sexa = true;
663                kind = Kind::SexaInt;
664            }
665            _ => return None,
666        }
667    } else if (b'1'..=b'9').contains(&at(0)) {
668        buf.push(at(0));
669        i = 1;
670        let mut k = Kind::Decimal;
671        while i < end {
672            match at(i) {
673                b'_' | b',' => i += 1,
674                c if c.is_ascii_digit() => {
675                    buf.push(c);
676                    i += 1;
677                }
678                b':' => {
679                    goto_sexa = true;
680                    k = Kind::SexaInt;
681                    break;
682                }
683                b'.' => {
684                    goto_float = true;
685                    k = Kind::Float;
686                    break;
687                }
688                _ => return None,
689            }
690        }
691        kind = k;
692    } else if at(0) == b':' {
693        goto_sexa = true;
694        kind = Kind::SexaInt;
695    } else if at(0) == b'.' {
696        buf.push(b'0');
697        goto_float = true;
698        kind = Kind::Float;
699    } else {
700        return None;
701    }
702
703    let mut kind = kind;
704    if goto_sexa {
705        let mut float = false;
706        while i < end {
707            if at(i) == b'.' {
708                float = true;
709                break;
710            }
711            if at(i) != b':' {
712                return None;
713            }
714            buf.push(at(i));
715            i += 1;
716            if at(i + 1) == b':' || at(i + 1) == b'.' || i + 1 == end {
717                if at(i).is_ascii_digit() {
718                    buf.push(at(i));
719                    i += 1;
720                } else {
721                    return None;
722                }
723            } else if (b'0'..=b'5').contains(&at(i)) && at(i + 1).is_ascii_digit() {
724                buf.push(at(i));
725                buf.push(at(i + 1));
726                i += 2;
727            } else {
728                return None;
729            }
730        }
731        if float || at(i) == b'.' {
732            kind = Kind::SexaFloat;
733            goto_float = true;
734        } else if i == end {
735            kind = Kind::SexaInt;
736        } else {
737            return None;
738        }
739    }
740    if goto_float {
741        buf.push(at(i));
742        i += 1;
743        if kind == Kind::SexaFloat {
744            let mut e = end;
745            while i < e && (v[e - 1] == b'_' || v[e - 1] == b'0') {
746                e -= 1;
747            }
748            if i == e {
749                buf.push(b'0');
750            }
751            while i < e {
752                match at(i) {
753                    b'_' => i += 1,
754                    c if c.is_ascii_digit() => {
755                        buf.push(c);
756                        i += 1;
757                    }
758                    _ => return None,
759                }
760            }
761        } else {
762            while i < end {
763                match at(i) {
764                    b'_' => i += 1,
765                    c if c.is_ascii_digit() => {
766                        buf.push(c);
767                        i += 1;
768                    }
769                    b'E' | b'e' => {
770                        buf.push(at(i));
771                        i += 1;
772                        if i == end || (at(i) != b'+' && at(i) != b'-') {
773                            return None;
774                        }
775                        buf.push(at(i));
776                        i += 1;
777                        if i == end || !at(i).is_ascii_digit() || (at(i) == b'0' && i + 1 == end) {
778                            return None;
779                        }
780                        buf.push(at(i));
781                        i += 1;
782                        while i < end {
783                            if at(i).is_ascii_digit() {
784                                buf.push(at(i));
785                                i += 1;
786                            } else {
787                                return None;
788                            }
789                        }
790                    }
791                    _ => return None,
792                }
793            }
794            kind = Kind::Float;
795        }
796    }
797
798    Some(match kind {
799        Kind::Binary => {
800            let digits = &buf[if negative { 3 } else { 2 }..];
801            let n = strtol(digits, 2);
802            Number::Int(if negative { n.wrapping_neg() } else { n })
803        }
804        Kind::Octal => Number::Int(strtol(&buf, 8)),
805        Kind::Hex => Number::Int(strtol(&buf, 16)),
806        Kind::SexaInt => {
807            let n = sexagesimal_l(&buf);
808            Number::Int(if negative { n.wrapping_neg() } else { n })
809        }
810        Kind::SexaFloat => {
811            let d = sexagesimal_d(&buf);
812            Number::Float(if negative { -d } else { d })
813        }
814        Kind::Decimal => Number::Int(atol(&buf)),
815        Kind::Float => Number::Float(strtod(&buf)),
816    })
817}
818
819#[cfg(test)]
820mod tests {
821    use super::*;
822
823    fn int(s: &str) -> Option<i64> {
824        match numeric(s.as_bytes()) {
825            Some(Number::Int(i)) => Some(i),
826            _ => None,
827        }
828    }
829
830    #[test]
831    fn numbers() {
832        assert_eq!(int("99999999999999999999"), Some(7766279631452241919));
833        assert_eq!(int("0x7FFFFFFFFFFFFFFFFF"), Some(i64::MAX));
834        assert_eq!(int("1,000"), Some(1000));
835        assert_eq!(int("1:20:30"), Some(4830));
836        assert_eq!(int("-0b11"), Some(-3));
837        assert_eq!(int("0o17"), None);
838        assert_eq!(int("08"), None);
839        assert!(matches!(numeric(b"190:20:30.15"), Some(Number::Float(f)) if (f - 685230.15).abs() < 1e-9));
840        assert!(numeric(b"1e3").is_none());
841    }
842
843    /// The stack a coroutine gets, which reading up to [`MAX_DEPTH`] must fit.
844    const STACK_BUDGET: usize = 2 * 1024 * 1024;
845
846    fn nested_sequences(depth: usize) -> Vec<u8> {
847        [vec![b'['; depth], vec![b']'; depth]].concat()
848    }
849
850    #[test]
851    fn nesting_up_to_the_limit_is_read() {
852        let Some(Value::Array(mut array)) = parse(&nested_sequences(MAX_DEPTH)) else { panic!() };
853        for _ in 1..MAX_DEPTH {
854            let Some(Value::Array(inner)) = array.get(&ArrayKey::Int(0)).cloned() else { panic!() };
855            array = inner;
856        }
857        assert_eq!(array.len(), 0);
858
859        // Mappings take the deepest frames. The limit has to fit the 2 MB a
860        // coroutine gets: a release build needs under 768 KB at this depth and
861        // a debug build, which the tests run, under 1.5 MB.
862        let flow = [b"{a: ".repeat(MAX_DEPTH), b"1".to_vec(), b"}".repeat(MAX_DEPTH)].concat();
863        let handle = std::thread::Builder::new().stack_size(STACK_BUDGET).spawn(move || parse(&flow)).unwrap();
864        assert!(matches!(handle.join().unwrap(), Some(Value::Array(_))));
865    }
866
867    #[test]
868    fn nesting_past_the_limit_is_refused() {
869        assert_eq!(parse(&nested_sequences(MAX_DEPTH + 1)), None);
870        let mappings = [b"a: ".repeat(MAX_DEPTH + 1), b"1".to_vec()].concat();
871        assert_eq!(parse(&mappings), None);
872        // A failure inside a mapping value used to come back as the part
873        // read so far: the refusal covers the whole document.
874        let flow = [b"{a: ".repeat(MAX_DEPTH + 1), b"1".to_vec(), b"}".repeat(MAX_DEPTH + 1)].concat();
875        assert_eq!(parse(&flow), None);
876    }
877
878    #[test]
879    fn a_document_far_past_the_limit_does_not_overflow_the_stack() {
880        // About 24 KB of brackets overflowed the stack before the limit.
881        let handle =
882            std::thread::Builder::new().stack_size(STACK_BUDGET).spawn(|| parse(&nested_sequences(100_000))).unwrap();
883        assert_eq!(handle.join().unwrap(), None);
884    }
885}