nettext 0.4.1

A text-based data format for cryptographic network protocols
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
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
//! Functions to decode nettext and helpers to map it to data structures

mod decode;
mod error;

use std::collections::HashMap;

use crate::debug;

pub use decode::*;
pub use error::*;

/// A parsed nettext term, with many helpers for destructuring
///
/// Lifetime 'a is the lifetime of the buffer containing the encoded data.
///
/// Lifetime 'b is the lifetime of another Term from which this one is borrowed, when it
/// is returned by one of the helper functions, or 'static when first returned from
/// `decode()`
#[derive(Eq, PartialEq, Debug)]
pub struct Term<'a, 'b>(pub(crate) AnyTerm<'a, 'b>);

#[derive(Eq, PartialEq, Clone)]
pub(crate) enum AnyTerm<'a, 'b> {
    Str(&'a [u8]),
    Dict(&'a [u8], HashMap<&'a [u8], AnyTerm<'a, 'b>>),
    DictRef(&'a [u8], &'b HashMap<&'a [u8], AnyTerm<'a, 'b>>),
    List(&'a [u8], Vec<AnyTerm<'a, 'b>>),
    ListRef(&'a [u8], &'b [AnyTerm<'a, 'b>]),
    Seq(&'a [u8], Vec<NonSeqTerm<'a, 'b>>),
    SeqRef(&'a [u8], &'b [NonSeqTerm<'a, 'b>]),
}

#[derive(Eq, PartialEq, Clone)]
pub(crate) enum NonSeqTerm<'a, 'b> {
    Str(&'a [u8]),
    Dict(&'a [u8], HashMap<&'a [u8], AnyTerm<'a, 'b>>),
    DictRef(&'a [u8], &'b HashMap<&'a [u8], AnyTerm<'a, 'b>>),
    List(&'a [u8], Vec<AnyTerm<'a, 'b>>),
    ListRef(&'a [u8], &'b [AnyTerm<'a, 'b>]),
}

impl<'a, 'b> From<NonSeqTerm<'a, 'b>> for AnyTerm<'a, 'b> {
    fn from(x: NonSeqTerm<'a, 'b>) -> AnyTerm<'a, 'b> {
        match x {
            NonSeqTerm::Str(s) => AnyTerm::Str(s),
            NonSeqTerm::Dict(raw, d) => AnyTerm::Dict(raw, d),
            NonSeqTerm::DictRef(raw, d) => AnyTerm::DictRef(raw, d),
            NonSeqTerm::List(raw, l) => AnyTerm::List(raw, l),
            NonSeqTerm::ListRef(raw, l) => AnyTerm::ListRef(raw, l),
        }
    }
}

impl<'a, 'b> TryFrom<AnyTerm<'a, 'b>> for NonSeqTerm<'a, 'b> {
    type Error = ();
    fn try_from(x: AnyTerm<'a, 'b>) -> Result<NonSeqTerm<'a, 'b>, ()> {
        match x {
            AnyTerm::Str(s) => Ok(NonSeqTerm::Str(s)),
            AnyTerm::Dict(raw, d) => Ok(NonSeqTerm::Dict(raw, d)),
            AnyTerm::DictRef(raw, d) => Ok(NonSeqTerm::DictRef(raw, d)),
            AnyTerm::List(raw, l) => Ok(NonSeqTerm::List(raw, l)),
            AnyTerm::ListRef(raw, l) => Ok(NonSeqTerm::ListRef(raw, l)),
            _ => Err(()),
        }
    }
}

impl<'a> From<AnyTerm<'a, 'static>> for Term<'a, 'static> {
    fn from(x: AnyTerm<'a, 'static>) -> Term<'a, 'static> {
        Term(x)
    }
}

// ---- PUBLIC IMPLS ----

impl<'a, 'b> Term<'a, 'b> {
    // ---- STRUCTURAL MAPPINGS ----

    /// Get the term's raw representation
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"hello world").unwrap();
    /// assert_eq!(term.raw(), b"hello world");
    /// ```
    pub fn raw(&self) -> &'a [u8] {
        self.0.raw()
    }

    /// Get the term's raw representation as an str
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"hello { a = x; b = y }").unwrap();
    /// assert_eq!(term.raw_str().unwrap(), "hello { a = x; b = y }");
    /// ```
    pub fn raw_str(&self) -> Result<&'a str, TypeError> {
        Ok(std::str::from_utf8(self.0.raw())?)
    }

    /// If the term is a single string, get that string
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term1 = decode(b"hello").unwrap();
    /// assert_eq!(term1.str().unwrap(), "hello");
    ///
    /// let term2 = decode(b"hello world").unwrap();
    /// assert!(term2.str().is_err());
    /// ```
    pub fn str(&self) -> Result<&'a str, TypeError> {
        match &self.0 {
            AnyTerm::Str(s) => Ok(std::str::from_utf8(s)?),
            _ => Err(TypeError::WrongType("STR")),
        }
    }

    /// If the term is a single string, or a sequence containing only strings,
    /// get its raw representation
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term1 = decode(b"hello world").unwrap();
    /// assert_eq!(term1.string().unwrap(), "hello world");
    ///
    /// let term2 = decode(b"hello { a= 5}").unwrap();
    /// assert!(term2.string().is_err());
    /// ```
    pub fn string(&self) -> Result<&'a str, TypeError> {
        match &self.0 {
            AnyTerm::Str(s) => Ok(std::str::from_utf8(s)?),
            AnyTerm::Seq(r, l) if l.iter().all(|x| matches!(x, NonSeqTerm::Str(_))) => {
                Ok(std::str::from_utf8(r)?)
            }
            _ => Err(TypeError::WrongType("STRING")),
        }
    }

    /// Return a sequence of terms made from this term.
    /// If it is a str or a dict, returns a seq of a single term.
    /// If it is a sequence, that's the seq of terms we return.
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term1 = decode(b"hello").unwrap();
    /// let seq1 = term1.seq();
    /// assert_eq!(seq1.len(), 1);
    /// assert_eq!(seq1[0].str().unwrap(), "hello");
    ///
    /// let term2 = decode(b"hello world").unwrap();
    /// let seq2 = term2.seq();
    /// assert_eq!(seq2.len(), 2);
    /// assert_eq!(seq2[0].str().unwrap(), "hello");
    /// assert_eq!(seq2[1].str().unwrap(), "world");
    /// ```
    pub fn seq(&self) -> Vec<Term<'a, '_>> {
        match self.0.mkref() {
            AnyTerm::SeqRef(_r, l) => l.iter().map(|x| Term(x.mkref().into())).collect::<Vec<_>>(),
            x => vec![Term(x)],
        }
    }

    /// Same as `.seq()`, but deconstructs it in a const length array,
    /// dynamically checking if there are the correct number of items.
    /// This allows to directly bind the resulting seq into discrete variables.
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term1 = decode(b"hello").unwrap();
    /// let [s1] = term1.seq_of().unwrap();
    /// assert_eq!(s1.str().unwrap(), "hello");
    ///
    /// let term2 = decode(b"hello world").unwrap();
    /// let [s2a, s2b] = term2.seq_of().unwrap();
    /// assert_eq!(s2a.str().unwrap(), "hello");
    /// assert_eq!(s2b.str().unwrap(), "world");
    /// ```
    pub fn seq_of<const N: usize>(&self) -> Result<[Term<'a, '_>; N], TypeError> {
        let seq = self.seq();
        let seq_len = seq.len();
        seq.try_into()
            .map_err(|_| TypeError::WrongLength(seq_len, N))
    }

    /// Same as `.seq_of()`, but only binds the first N-1 terms.
    /// If there are exactly N terms, the last one is bound to the Nth return variable.
    /// If there are more then N terms, the remaining terms are bound to a new seq term
    /// that is returned as the Nth return variable.
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term1 = decode(b"hello world").unwrap();
    /// let [s1a, s1b] = term1.seq_of_first().unwrap();
    /// assert_eq!(s1a.str().unwrap(), "hello");
    /// assert_eq!(s1b.str().unwrap(), "world");
    ///
    /// let term2 = decode(b"hello mighty world").unwrap();
    /// let [s2a, s2b] = term2.seq_of_first().unwrap();
    /// assert_eq!(s2a.str().unwrap(), "hello");
    /// assert_eq!(s2b.seq().len(), 2);
    /// assert_eq!(s2b.raw(), b"mighty world");
    /// ```
    pub fn seq_of_first<const N: usize>(&self) -> Result<[Term<'a, '_>; N], TypeError> {
        match self.0.mkref() {
            AnyTerm::SeqRef(raw, seq) => match seq.len().cmp(&N) {
                std::cmp::Ordering::Less => Err(TypeError::WrongLength(seq.len(), N)),
                std::cmp::Ordering::Equal => Ok(seq
                    .iter()
                    .map(|x| Term(x.mkref().into()))
                    .collect::<Vec<_>>()
                    .try_into()
                    .unwrap()),
                std::cmp::Ordering::Greater => {
                    let mut ret = Vec::with_capacity(N);
                    for item in seq[0..N - 1].iter() {
                        ret.push(Term(item.mkref().into()));
                    }

                    let remaining_begin = seq[N - 1].raw().as_ptr() as usize;
                    let remaining_offset = remaining_begin - raw.as_ptr() as usize;
                    let remaining_raw = &raw[remaining_offset..];

                    ret.push(Term(AnyTerm::SeqRef(remaining_raw, &seq[N - 1..])));

                    Ok(ret.try_into().unwrap())
                }
            },
            x if N == 1 => Ok([Term(x)]
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .unwrap()),
            _ => Err(TypeError::WrongLength(1, N)),
        }
    }

    /// Checks term is a dictionnary and returns hashmap of inner terms.
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"{ k1 = v1; k2 = v2 }").unwrap();
    /// let dict = term.dict().unwrap();
    /// assert_eq!(dict.get("k1").unwrap().str().unwrap(), "v1");
    /// assert_eq!(dict.get("k2").unwrap().str().unwrap(), "v2");
    /// ```
    pub fn dict(&self) -> Result<HashMap<&'a str, Term<'a, '_>>, TypeError> {
        match self.0.mkref() {
            AnyTerm::DictRef(_, d) => {
                let mut res = HashMap::with_capacity(d.len());
                for (k, t) in d.iter() {
                    res.insert(std::str::from_utf8(k)?, Term(t.mkref()));
                }
                Ok(res)
            }
            _ => Err(TypeError::WrongType("DICT")),
        }
    }

    /// Checks term is a dictionnary whose keys are exactly those supplied,
    /// and returns the associated values as a seq.
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"{ k1 = v1; k2 = v2; k3 = v3 }").unwrap();
    /// let [s1, s2] = term.dict_of(["k1", "k2"], true).unwrap();
    /// assert_eq!(s1.str().unwrap(), "v1");
    /// assert_eq!(s2.str().unwrap(), "v2");
    ///
    /// assert!(term.dict_of(["k1", "k2"], false).is_err());
    /// ```
    pub fn dict_of<const N: usize, T: AsRef<[u8]>>(
        &self,
        keys: [T; N],
        allow_extra_keys: bool,
    ) -> Result<[Term<'a, '_>; N], TypeError> {
        match self.0.mkref() {
            AnyTerm::DictRef(_, dict) => {
                // Check all required keys exist in dictionnary
                for k in keys.iter() {
                    if !dict.contains_key(k.as_ref()) {
                        return Err(TypeError::MissingKey(debug(k.as_ref()).to_string()));
                    }
                }
                if !allow_extra_keys {
                    // Check that dictionnary contains no extraneous keys
                    for k in dict.keys() {
                        if !keys.iter().any(|k2| k2.as_ref() == *k) {
                            return Err(TypeError::UnexpectedKey(debug(k).to_string()));
                        }
                    }
                }
                Ok(keys.map(|k| Term(dict.get(k.as_ref()).unwrap().mkref())))
            }
            _ => Err(TypeError::WrongType("DICT")),
        }
    }

    /// Checks term is a dictionnary whose keys are included in those supplied,
    /// and returns the associated values as a seq of options.
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"{ k1 = v1; k2 = v2; k4 = v4 }").unwrap();
    /// let [s1, s2, s3] = term.dict_of_opt(["k1", "k2", "k3"], true).unwrap();
    /// assert_eq!(s1.unwrap().str().unwrap(), "v1");
    /// assert_eq!(s2.unwrap().str().unwrap(), "v2");
    /// assert!(s3.is_none());
    ///
    /// assert!(term.dict_of_opt(["k1", "k2", "k3"], false).is_err());
    /// ```
    pub fn dict_of_opt<const N: usize, T: AsRef<[u8]>>(
        &self,
        keys: [T; N],
        allow_extra_keys: bool,
    ) -> Result<[Option<Term<'a, '_>>; N], TypeError> {
        match self.0.mkref() {
            AnyTerm::DictRef(_, dict) => {
                if !allow_extra_keys {
                    // Check that dictionnary contains no extraneous keys
                    for k in dict.keys() {
                        if !keys.iter().any(|x| x.as_ref() == *k) {
                            return Err(TypeError::UnexpectedKey(debug(k).to_string()));
                        }
                    }
                }
                Ok(keys.map(|k| dict.get(k.as_ref()).map(|x| Term(x.mkref()))))
            }
            _ => Err(TypeError::WrongType("DICT")),
        }
    }

    /// Checks if the term is a list, and if so, return its elements in a vec.
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term2 = decode(b"[ hello; world ]").unwrap();
    /// let seq2 = term2.list().unwrap();
    /// assert_eq!(seq2.len(), 2);
    /// assert_eq!(seq2[0].str().unwrap(), "hello");
    /// assert_eq!(seq2[1].str().unwrap(), "world");
    /// ```
    pub fn list(&self) -> Result<Vec<Term<'a, '_>>, TypeError> {
        match self.0.mkref() {
            AnyTerm::ListRef(_r, l) => {
                Ok(l.iter().map(|x| Term(x.mkref().into())).collect::<Vec<_>>())
            }
            _ => Err(TypeError::WrongType("LIST")),
        }
    }

    // ---- TYPE CASTS ----

    /// Try to interpret this str as an i64
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"42").unwrap();
    /// assert_eq!(term.int().unwrap(), 42);
    /// ```
    pub fn int(&self) -> Result<i64, TypeError> {
        self.str()?
            .parse::<i64>()
            .map_err(|_| TypeError::WrongType("INT"))
    }

    /// Try to interpret this string as base64-encoded bytes (uses URL-safe, no-padding encoding)
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"aGVsbG8sIHdvcmxkIQ").unwrap();
    /// assert_eq!(term.bytes().unwrap(), b"hello, world!");
    /// ```
    pub fn bytes(&self) -> Result<Vec<u8>, TypeError> {
        let decode = |encoded| {
            base64::decode_config(encoded, base64::URL_SAFE_NO_PAD)
                .map_err(|_| TypeError::WrongType("BYTES"))
        };
        match self.0.mkref() {
            AnyTerm::Str(encoded) => {
                if encoded == b"-" {
                    Ok(vec![])
                } else {
                    decode(encoded)
                }
            }
            AnyTerm::SeqRef(_, seq) => {
                let mut ret = Vec::with_capacity(128);
                for term in seq.iter() {
                    if let NonSeqTerm::Str(encoded) = term {
                        ret.extend(decode(encoded)?)
                    } else {
                        return Err(TypeError::WrongType("BYTES"));
                    }
                }
                Ok(ret)
            }
            _ => Err(TypeError::WrongType("BYTES")),
        }
    }

    /// Try to interpret this string as base64-encoded bytes,
    /// with a marker prefix and an exact byte length.
    /// This is typically used for cryptographic data types such as hashes,
    /// keys, signatures, ...
    ///
    /// Example:
    ///
    /// ```
    /// use nettext::dec::decode;
    ///
    /// let term = decode(b"test:aGVsbG8sIHdvcmxkIQ").unwrap();
    /// assert_eq!(&term.marked_bytes_exact::<13>("test").unwrap(), b"hello, world!");
    /// ```
    pub fn marked_bytes_exact<const N: usize>(
        &self,
        marker: &'static str,
    ) -> Result<[u8; N], TypeError> {
        let mkr = marker.as_bytes();
        match &self.0 {
            AnyTerm::Str(s)
                if s.len() >= mkr.len() + 2 && &s[..mkr.len()] == mkr && s[mkr.len()] == b':' =>
            {
                let bytes = match &s[mkr.len() + 1..] {
                    b"-" => vec![],
                    bytes => base64::decode_config(bytes, base64::URL_SAFE_NO_PAD)
                        .map_err(|_| TypeError::WrongType("BYTES"))?,
                };
                let bytes_len = bytes.len();
                bytes
                    .try_into()
                    .map_err(|_| TypeError::WrongLength(bytes_len, N))
            }
            AnyTerm::Str(_) => Err(TypeError::WrongMarker(marker)),
            _ => Err(TypeError::WrongType("BYTES")),
        }
    }
}

// ---- INTERNAL IMPLS ----

impl<'a, 'b> AnyTerm<'a, 'b> {
    fn raw(&self) -> &'a [u8] {
        match self {
            AnyTerm::Str(s) => s,
            AnyTerm::Dict(r, _)
            | AnyTerm::DictRef(r, _)
            | AnyTerm::List(r, _)
            | AnyTerm::ListRef(r, _)
            | AnyTerm::Seq(r, _)
            | AnyTerm::SeqRef(r, _) => r,
        }
    }

    pub(crate) fn mkref(&self) -> AnyTerm<'a, '_> {
        match &self {
            AnyTerm::Str(s) => AnyTerm::Str(s),
            AnyTerm::Dict(r, d) => AnyTerm::DictRef(r, d),
            AnyTerm::DictRef(r, d) => AnyTerm::DictRef(r, d),
            AnyTerm::List(r, l) => AnyTerm::ListRef(r, l),
            AnyTerm::ListRef(r, l) => AnyTerm::ListRef(r, l),
            AnyTerm::Seq(r, l) => AnyTerm::SeqRef(r, &l[..]),
            AnyTerm::SeqRef(r, l) => AnyTerm::SeqRef(r, l),
        }
    }
}

impl<'a, 'b> NonSeqTerm<'a, 'b> {
    fn raw(&self) -> &'a [u8] {
        match &self {
            NonSeqTerm::Str(s) => s,
            NonSeqTerm::Dict(r, _) | NonSeqTerm::DictRef(r, _) => r,
            NonSeqTerm::List(r, _) | NonSeqTerm::ListRef(r, _) => r,
        }
    }

    fn mkref(&self) -> NonSeqTerm<'a, '_> {
        match &self {
            NonSeqTerm::Str(s) => NonSeqTerm::Str(s),
            NonSeqTerm::Dict(r, d) => NonSeqTerm::DictRef(r, d),
            NonSeqTerm::DictRef(r, d) => NonSeqTerm::DictRef(r, d),
            NonSeqTerm::List(r, l) => NonSeqTerm::ListRef(r, l),
            NonSeqTerm::ListRef(r, l) => NonSeqTerm::ListRef(r, l),
        }
    }
}

// ---- DISPLAY REPR = Raw nettext representation ----

impl<'a, 'b> std::fmt::Display for AnyTerm<'a, 'b> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(
            f,
            "{}",
            std::str::from_utf8(self.raw()).map_err(|_| Default::default())?
        )
    }
}

impl<'a, 'b> std::fmt::Display for Term<'a, 'b> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "{}", self.0)
    }
}

// ---- DEBUG REPR ----

impl<'a, 'b> std::fmt::Debug for AnyTerm<'a, 'b> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self.mkref() {
            AnyTerm::Str(s) => write!(f, "Str(`{}`)", debug(s)),
            AnyTerm::DictRef(raw, d) => {
                write!(f, "Dict<`{}`", debug(raw))?;
                for (k, v) in d.iter() {
                    write!(f, "\n  `{}`={:?}", debug(k), v)?;
                }
                write!(f, ">")
            }
            AnyTerm::ListRef(raw, l) => {
                write!(f, "List[`{}`", debug(raw))?;
                for i in l.iter() {
                    write!(f, "\n  {:?}", i)?;
                }
                write!(f, "]")
            }
            AnyTerm::SeqRef(raw, l) => {
                write!(f, "Seq[`{}`", debug(raw))?;
                for i in l.iter() {
                    write!(f, "\n  {:?}", i)?;
                }
                write!(f, "]")
            }
            _ => unreachable!(),
        }
    }
}

impl<'a, 'b> std::fmt::Debug for NonSeqTerm<'a, 'b> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        AnyTerm::from(self.mkref()).fmt(f)
    }
}