freeswitch-types 1.5.0-beta.8

FreeSWITCH ESL protocol types: channel state, events, headers, commands, and variables
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
//! Channel variable scope and ordered key-value storage for originate commands.

use indexmap::IndexMap;
use std::fmt;
use std::str::FromStr;

use super::originate::OriginateError;

/// Scope for channel variables in an originate command.
///
/// - `Enterprise` (`<>`) -- applies across all threads (`:_:` separated)
/// - `Default` (`{}`) -- applies to all channels in this originate
/// - `Channel` (`[]`) -- applies only to one specific channel
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[non_exhaustive]
pub enum VariablesType {
    /// `<>` scope -- applies across all `:_:` separated threads.
    Enterprise,
    /// `{}` scope -- applies to all channels in this originate.
    Default,
    /// `[]` scope -- applies to one specific channel.
    Channel,
}

impl VariablesType {
    pub(super) fn delimiters(self) -> (char, char) {
        match self {
            Self::Enterprise => ('<', '>'),
            Self::Default => ('{', '}'),
            Self::Channel => ('[', ']'),
        }
    }
}

/// Ordered set of channel variables with FreeSWITCH escaping.
///
/// Backslashes are doubled, commas are escaped with `\,`, single quotes with
/// `\'`, and values with spaces are wrapped in single quotes. This form
/// round-trips through [`FromStr`]; what the switch itself decodes depends on
/// which command carries the block, and is documented in
/// `docs/dial-string-format.md`.
///
/// # Serde format
///
/// [`Default`](VariablesType::Default) scope serializes as a flat JSON map:
/// `{"key": "value", ...}`. Non-default scopes serialize as
/// `{"scope": "Enterprise", "vars": {"key": "value"}}`.
/// Deserialization accepts both formats; a flat map implies `Default` scope.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Variables {
    vars_type: VariablesType,
    inner: IndexMap<String, String>,
    /// Set by [`with_separator`](Variables::with_separator). Parsing a `^^`
    /// block does not populate it: reading one back and writing it out
    /// canonicalises to a comma, and the other form is asked for explicitly.
    separator: Option<char>,
}

/// Which command carries a dial string, and therefore how deeply its variable
/// values must be escaped.
///
/// FreeSWITCH escape-processes a bracket block a different number of times
/// depending on the command it arrived on, and the correct escaping of a value
/// containing a single quote differs between them with no form that satisfies
/// both. Naming the carrier is the only way a renderer can be right.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum DialStringCarrier {
    /// `api originate` / `bgapi originate`, whose argument list is split before
    /// the block itself is parsed. The default for [`Display`](fmt::Display).
    EslApi,
    /// A dialplan application such as `bridge`, including via `sendmsg execute`,
    /// which receives its argument whole.
    Dialplan,
}

/// A literal backslash, whatever follows it.
const BACKSLASH: &str = r"\\\\\\\\";
/// A literal single quote, per carrier.
const QUOTE_DIALPLAN: &str = r"\\'";
const QUOTE_ESL_API: &str = r"\\\'";

impl DialStringCarrier {
    fn quote_escape(self) -> &'static str {
        match self {
            Self::EslApi => QUOTE_ESL_API,
            Self::Dialplan => QUOTE_DIALPLAN,
        }
    }
}

/// Reject a value the wire cannot carry, whatever escaping is applied to it.
///
/// Two shapes qualify. An empty value is discarded by the switch under every
/// encoding, and the block's own parse reports nothing when it happens. A value
/// carrying an unbalanced bracket ends the block early, because the switch finds
/// the block's end by counting depth and does not honour escapes while doing so;
/// a balanced pair such as `${var}` is fine and common.
fn check_representable(
    key: &str,
    value: &str,
    vars_type: VariablesType,
) -> Result<(), OriginateError> {
    if value.is_empty() {
        return Err(OriginateError::ParseError(format!(
            "variable {key} has an empty value: the switch discards such a pair \
             without logging it, so it cannot be told from an absent variable on \
             the wire. Give it a value or remove it -- and if its presence was \
             itself the signal, that signal needs a home outside the dial string"
        )));
    }

    let (open, close) = vars_type.delimiters();
    let mut depth = 0i32;
    for ch in value.chars() {
        if ch == open {
            depth += 1;
        } else if ch == close {
            depth -= 1;
            if depth < 0 {
                return Err(OriginateError::ParseError(format!(
                    "variable {key} closes a '{open}' it never opened, ending the block early"
                )));
            }
        }
    }
    if depth != 0 {
        return Err(OriginateError::ParseError(format!(
            "variable {key} opens a '{open}' it never closes, swallowing the block's end"
        )));
    }
    Ok(())
}

/// Escaping for a block whose separator is not the comma, so a comma in a value
/// is ordinary text. Everything else is escaped as it would be otherwise.
fn escape_value_keeping_commas(value: &str, carrier: DialStringCarrier) -> String {
    let escaped = value
        .replace('\\', BACKSLASH)
        .replace('\'', carrier.quote_escape());
    if escaped.contains(' ') {
        format!("'{}'", escaped)
    } else {
        escaped
    }
}

pub(super) fn escape_value(value: &str, carrier: DialStringCarrier) -> String {
    // The backslash goes first, or the ones the other rules introduce get
    // escaped in turn.
    let escaped = value
        .replace('\\', BACKSLASH)
        .replace('\'', carrier.quote_escape())
        .replace(',', "\\,");
    if escaped.contains(' ') {
        format!("'{}'", escaped)
    } else {
        escaped
    }
}

/// Inverts [`escape_value`], undoing each substitution in the reverse order it
/// was applied so an escape introduced by a later rule is not read as input to
/// an earlier one.
fn unescape_value(value: &str, carrier: DialStringCarrier) -> String {
    let s = value
        .strip_prefix('\'')
        .and_then(|s| s.strip_suffix('\''))
        .unwrap_or(value);

    s.replace("\\,", ",")
        .replace(carrier.quote_escape(), "'")
        .replace(BACKSLASH, "\\")
}

impl Variables {
    /// Create an empty variable set with the given scope.
    pub fn new(vars_type: VariablesType) -> Self {
        Self {
            vars_type,
            inner: IndexMap::new(),
            separator: None,
        }
    }

    /// Create from an existing set of key-value pairs.
    pub fn with_vars(
        vars_type: VariablesType,
        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        Self {
            vars_type,
            inner: vars
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            separator: None,
        }
    }

    /// Separate the pairs with `sep` instead of a comma, emitting the block in
    /// FreeSWITCH's `^^<sep>` form.
    ///
    /// A value expanded from `${...}` in a dialplan is substituted before the
    /// block is parsed, so no escaping can be inserted into it; choosing a
    /// separator none of the values contain is the only way such a value can
    /// carry a comma. The separator is given rather than derived, so a block
    /// renders the same way whatever its values happen to be that call.
    ///
    /// Fails if `sep` cannot delimit this block, or if a value already present
    /// contains it. Values inserted afterwards are not checked.
    pub fn with_separator(mut self, sep: char) -> Result<Self, OriginateError> {
        let (_, close) = self
            .vars_type
            .delimiters();
        if sep == close || sep == '=' || sep == '^' {
            return Err(OriginateError::ParseError(format!(
                "invalid ^^ separator: '{sep}'"
            )));
        }
        if let Some((key, _)) = self
            .inner
            .iter()
            .find(|(_, v)| v.contains(sep))
        {
            return Err(OriginateError::ParseError(format!(
                "variable {key} contains the chosen '{sep}' separator"
            )));
        }
        self.separator = Some(sep);
        Ok(self)
    }

    /// The `^^` separator this block renders with, if one was chosen.
    pub fn separator(&self) -> Option<char> {
        self.separator
    }

    /// Insert or overwrite a variable.
    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.inner
            .insert(key.into(), value.into());
    }

    /// Remove a variable by name, returning its value if it existed.
    pub fn remove(&mut self, key: &str) -> Option<String> {
        self.inner
            .shift_remove(key)
    }

    /// Look up a variable by name.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.inner
            .get(key)
            .map(|s| s.as_str())
    }

    /// Whether the set contains no variables.
    pub fn is_empty(&self) -> bool {
        self.inner
            .is_empty()
    }

    /// Number of variables.
    pub fn len(&self) -> usize {
        self.inner
            .len()
    }

    /// Variable scope (Enterprise, Default, or Channel).
    pub fn scope(&self) -> VariablesType {
        self.vars_type
    }

    /// Change the variable scope.
    pub fn set_scope(&mut self, scope: VariablesType) {
        self.vars_type = scope;
    }

    /// Iterate over key-value pairs in insertion order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.inner
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
    }

    /// Mutable iterator over key-value pairs in insertion order.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut String)> {
        self.inner
            .iter_mut()
            .map(|(k, v)| (k.as_str(), v))
    }

    /// Mutable iterator over values in insertion order.
    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut String> {
        self.inner
            .values_mut()
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Variables {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if self.vars_type == VariablesType::Default {
            self.inner
                .serialize(serializer)
        } else {
            use serde::ser::SerializeStruct;
            let mut s = serializer.serialize_struct("Variables", 2)?;
            s.serialize_field("scope", &self.vars_type)?;
            s.serialize_field("vars", &self.inner)?;
            s.end()
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Variables {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(serde::Deserialize)]
        #[serde(untagged)]
        enum VariablesRepr {
            Scoped {
                scope: VariablesType,
                vars: IndexMap<String, String>,
            },
            Flat(IndexMap<String, String>),
        }

        let (vars_type, inner) = match VariablesRepr::deserialize(deserializer)? {
            VariablesRepr::Scoped { scope, vars } => (scope, vars),
            VariablesRepr::Flat(map) => (VariablesType::Default, map),
        };
        // A config naming a value the wire cannot carry fails at load rather
        // than on the call it was loaded for.
        for (key, value) in &inner {
            check_representable(key, value, vars_type).map_err(serde::de::Error::custom)?;
        }
        Ok(Self {
            vars_type,
            inner,
            separator: None,
        })
    }
}

/// Renders a [`Variables`] for one carrier. Returned by
/// [`Variables::display_for`].
#[derive(Debug, Clone, Copy)]
pub struct VariablesDisplay<'a> {
    vars: &'a Variables,
    carrier: DialStringCarrier,
}

impl fmt::Display for VariablesDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.vars
            .write_for(f, self.carrier)
    }
}

impl Variables {
    /// Render for a named carrier, rather than the [`DialStringCarrier::EslApi`]
    /// default that [`Display`](fmt::Display) uses.
    pub fn display_for(&self, carrier: DialStringCarrier) -> VariablesDisplay<'_> {
        VariablesDisplay {
            vars: self,
            carrier,
        }
    }

    pub(super) fn write_for(
        &self,
        f: &mut fmt::Formatter<'_>,
        carrier: DialStringCarrier,
    ) -> fmt::Result {
        let (open, close) = self
            .vars_type
            .delimiters();
        f.write_fmt(format_args!("{}", open))?;
        if let Some(sep) = self.separator {
            write!(f, "^^{sep}")?;
        }
        // A chosen separator carries the values that a comma would have needed
        // escaping for, so only the comma form escapes them.
        let sep = self
            .separator
            .unwrap_or(',');
        for (i, (key, value)) in self
            .inner
            .iter()
            .enumerate()
        {
            if i > 0 {
                write!(f, "{sep}")?;
            }
            let value = match self.separator {
                Some(_) => escape_value_keeping_commas(value, carrier),
                None => escape_value(value, carrier),
            };
            write!(f, "{}={}", key, value)?;
        }
        f.write_fmt(format_args!("{}", close))
    }
}

impl fmt::Display for Variables {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.write_for(f, DialStringCarrier::EslApi)
    }
}

impl FromStr for Variables {
    type Err = OriginateError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_for(s, DialStringCarrier::EslApi)
    }
}

impl Variables {
    /// Parse a block written for a named carrier, mirroring
    /// [`display_for`](Self::display_for). [`FromStr`] uses the same
    /// [`DialStringCarrier::EslApi`] default as [`Display`](fmt::Display), so
    /// the two round-trip.
    pub fn parse_for(s: &str, carrier: DialStringCarrier) -> Result<Self, OriginateError> {
        let s = s.trim();
        if s.len() < 2 {
            return Err(OriginateError::ParseError(
                "variable block too short".into(),
            ));
        }

        let (vars_type, inner_str) = match (s.as_bytes()[0], s.as_bytes()[s.len() - 1]) {
            (b'{', b'}') => (VariablesType::Default, &s[1..s.len() - 1]),
            (b'<', b'>') => (VariablesType::Enterprise, &s[1..s.len() - 1]),
            (b'[', b']') => (VariablesType::Channel, &s[1..s.len() - 1]),
            (open, close) => {
                return Err(OriginateError::ParseError(format!(
                    "unknown variable delimiters: {:?}..{:?}",
                    open as char, close as char
                )));
            }
        };

        let mut inner = IndexMap::new();
        if !inner_str.is_empty() {
            if let Some(rest) = inner_str.strip_prefix("^^") {
                let sep = rest
                    .chars()
                    .next()
                    .ok_or_else(|| {
                        OriginateError::ParseError("^^ without separator character".into())
                    })?;
                let (_, close) = vars_type.delimiters();
                if sep == close || sep == '=' {
                    return Err(OriginateError::ParseError(format!(
                        "invalid ^^ separator: '{sep}'"
                    )));
                }
                let var_str = &rest[sep.len_utf8()..];
                if !var_str.is_empty() {
                    for (i, part) in var_str
                        .split(sep)
                        .enumerate()
                    {
                        let (key, value) = part
                            .split_once('=')
                            .ok_or_else(|| {
                                OriginateError::ParseError(format!("missing = in variable {i}"))
                            })?;
                        check_representable(key, value, vars_type)?;
                        inner.insert(key.to_string(), value.to_string());
                    }
                }
            } else {
                for (i, part) in split_unescaped_commas(inner_str)
                    .into_iter()
                    .enumerate()
                {
                    let (key, value) = part
                        .split_once('=')
                        .ok_or_else(|| {
                            OriginateError::ParseError(format!("missing = in variable {i}"))
                        })?;
                    let value = unescape_value(value, carrier);
                    check_representable(key, &value, vars_type)?;
                    inner.insert(key.to_string(), value);
                }
            }
        }

        Ok(Self {
            vars_type,
            inner,
            separator: None,
        })
    }
}

/// Split on commas that are not escaped by a backslash.
///
/// A comma preceded by an odd number of backslashes is escaped (e.g. `\,`).
/// A comma preceded by an even number of backslashes is a real split point
/// (e.g. `\\,` means escaped backslash followed by comma delimiter).
pub(super) fn split_unescaped_commas(s: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let bytes = s.as_bytes();

    for i in 0..bytes.len() {
        if bytes[i] == b',' {
            let mut backslashes = 0;
            let mut j = i;
            while j > 0 && bytes[j - 1] == b'\\' {
                backslashes += 1;
                j -= 1;
            }
            if backslashes % 2 == 0 {
                parts.push(&s[start..i]);
                start = i + 1;
            }
        }
    }
    parts.push(&s[start..]);
    parts
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Measured on a live switch: bare, quoted, escaped-quoted and
    /// backslash-quoted empty values are all discarded, on both carriers, with
    /// no diagnostic from the switch at any level. Nothing can be emitted for
    /// one, so it is refused where refusing is possible.
    /// A config that loaded yesterday and does not today has to say what to do
    /// about it: the remedy is dropping the key, which is not guessable from
    /// being told the value is unrepresentable.
    #[test]
    fn an_empty_value_is_refused_at_the_boundary() {
        let err = "{k=,after=sentinel}"
            .parse::<Variables>()
            .unwrap_err()
            .to_string();
        assert!(err.contains('k'), "error does not name the variable: {err}");
        assert!(
            err.contains("remove it"),
            "error does not name a remedy: {err}"
        );
        // Prescribing removal alone is wrong for a caller whose *presence* test
        // is the signal: dropping the key silently reverses that decision.
        assert!(
            err.contains("presence"),
            "error prescribes a fix without allowing that presence meant something: {err}"
        );
    }

    /// The switch finds a block's end by counting bracket depth and honours no
    /// escape while doing so, so a value closing a bracket it never opened ends
    /// the block early and the rest becomes dial-string text.
    #[test]
    fn an_unbalanced_bracket_is_refused_while_a_balanced_one_is_not() {
        assert!("{k=oops}extra}"
            .parse::<Variables>()
            .is_err());

        let balanced: Variables = "{k=${some_var}}"
            .parse()
            .expect("a balanced ${...} is ordinary and must parse");
        assert_eq!(balanced.get("k"), Some("${some_var}"));
    }

    /// A chosen separator is what carries a comma through a value that was
    /// expanded before the block was parsed, so the comma must survive as
    /// ordinary text rather than picking up an escape.
    #[test]
    fn chosen_separator_leaves_commas_alone() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("codecs", "PCMA,PCMU,G729");
        let vars = vars
            .with_separator(':')
            .unwrap();

        assert_eq!(vars.to_string(), "{^^:codecs=PCMA,PCMU,G729}");
        assert_eq!(vars.separator(), Some(':'));
    }

    #[test]
    fn separator_that_cannot_delimit_the_block_is_refused() {
        let vars = Variables::new(VariablesType::Channel);
        for sep in [']', '=', '^'] {
            assert!(
                vars.clone()
                    .with_separator(sep)
                    .is_err(),
                "accepted {sep:?}"
            );
        }
    }

    /// Refusing here is the whole point: a value carrying the separator would
    /// split into a pair that was never written, and the switch reports nothing.
    #[test]
    fn separator_already_present_in_a_value_is_refused() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("uri", "sip:bob@example.com");
        let err = vars
            .with_separator(':')
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("uri"),
            "error does not name the variable: {err}"
        );
    }

    /// Measured against a live switch, with two awkward values in one block —
    /// a block carrying only one is more forgiving and hides the failure.
    /// Sweeping the backslash count, each carrier succeeds at counts the other
    /// fails, so these forms are the wire contract and not a preference.
    #[test]
    fn escaping_pins_the_measured_wire_forms() {
        let cases = [
            (DialStringCarrier::Dialplan, "it's", r"it\\'s"),
            (DialStringCarrier::EslApi, "it's", r"it\\\'s"),
            (DialStringCarrier::Dialplan, r"a\nb", r"a\\\\\\\\nb"),
            (DialStringCarrier::EslApi, r"a\nb", r"a\\\\\\\\nb"),
            (DialStringCarrier::Dialplan, "a,b", r"a\,b"),
            (DialStringCarrier::EslApi, "a,b", r"a\,b"),
        ];
        for (carrier, value, want) in cases {
            assert_eq!(
                escape_value(value, carrier),
                want,
                "{value:?} for {carrier:?}"
            );
        }
    }

    /// The crate exists to drive `api originate`, so a block rendered with no
    /// carrier named is rendered for that one.
    #[test]
    fn display_defaults_to_the_api_carrier() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("k", "it's");
        assert_eq!(vars.to_string(), r"{k=it\\\'s}");
        assert_eq!(
            vars.display_for(DialStringCarrier::Dialplan)
                .to_string(),
            r"{k=it\\'s}"
        );
    }

    #[test]
    fn round_trips_at_either_carrier() {
        for carrier in [DialStringCarrier::EslApi, DialStringCarrier::Dialplan] {
            for value in ["it's", r"a\,b", r"C:\path", "a,b", "with space"] {
                let mut vars = Variables::new(VariablesType::Default);
                vars.insert("k", value);
                vars.insert("after", "sentinel");
                let rendered = vars
                    .display_for(carrier)
                    .to_string();

                let back = Variables::parse_for(&rendered, carrier).unwrap_or_else(|e| {
                    panic!("{value:?} for {carrier:?} rendered {rendered}: {e}")
                });
                assert_eq!(back.get("k"), Some(value), "rendered {rendered}");
                assert_eq!(back.get("after"), Some("sentinel"), "rendered {rendered}");
            }
        }
    }

    /// `split_unescaped_commas` reads a comma behind an even number of
    /// backslashes as a real separator, so a value ending in a backslash has to
    /// be written with its own backslash escaped or the writer contradicts the
    /// reader and the block no longer parses.
    #[test]
    fn value_with_backslash_round_trips() {
        for value in [r"a\,b", r"C:\path", r"trailing\", r"\\", r"a\nb"] {
            let mut vars = Variables::new(VariablesType::Default);
            vars.insert("k", value);
            vars.insert("after", "sentinel");
            let rendered = vars.to_string();

            let back: Variables = rendered
                .parse()
                .unwrap_or_else(|e| {
                    panic!("{value:?} rendered {rendered} and failed to parse: {e}")
                });
            assert_eq!(back.get("k"), Some(value), "rendered {rendered}");
            assert_eq!(
                back.get("after"),
                Some("sentinel"),
                "value {value:?} ate the next variable: {rendered}"
            );
        }
    }

    /// A variable block holds dialled numbers and passthrough header values, so a
    /// malformed part is reported by position.
    #[test]
    fn missing_equals_error_omits_the_fragment() {
        let msg = "{origination_caller_id_number=15551234567,15550009999}"
            .parse::<Variables>()
            .unwrap_err()
            .to_string();
        assert!(
            !msg.contains("15550009999"),
            "error quoted its input: {msg}"
        );
        assert!(
            msg.contains("variable 1"),
            "error does not name the part: {msg}"
        );
    }

    #[test]
    fn unknown_delimiters_error_omits_the_block() {
        let msg = "(origination_caller_id_number=15551234567)"
            .parse::<Variables>()
            .unwrap_err()
            .to_string();
        assert!(
            !msg.contains("15551234567"),
            "error quoted its input: {msg}"
        );
    }

    #[test]
    fn variables_standard_chars() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("test_key", "this_value");
        let result = vars.to_string();
        assert!(result.contains("test_key"));
        assert!(result.contains("this_value"));
    }

    #[test]
    fn variables_comma_escaped() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("test_key", "this,is,a,value");
        let result = vars.to_string();
        assert!(result.contains("\\,"));
    }

    #[test]
    fn variables_spaces_quoted() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("test_key", "this is a value");
        let result = vars.to_string();
        assert_eq!(
            result
                .matches('\'')
                .count(),
            2
        );
    }

    #[test]
    fn variables_single_quote_escaped() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("test_key", "let's_this_be_a_value");
        let result = vars.to_string();
        assert!(result.contains("\\'"));
    }

    #[test]
    fn variables_enterprise_delimiters() {
        let mut vars = Variables::new(VariablesType::Enterprise);
        vars.insert("k", "v");
        let result = vars.to_string();
        assert!(result.starts_with('<'));
        assert!(result.ends_with('>'));
    }

    #[test]
    fn variables_channel_delimiters() {
        let mut vars = Variables::new(VariablesType::Channel);
        vars.insert("k", "v");
        let result = vars.to_string();
        assert!(result.starts_with('['));
        assert!(result.ends_with(']'));
    }

    #[test]
    fn variables_default_delimiters() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("k", "v");
        let result = vars.to_string();
        assert!(result.starts_with('{'));
        assert!(result.ends_with('}'));
    }

    #[test]
    fn variables_parse_round_trip() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("origination_caller_id_number", "9005551212");
        vars.insert("sip_h_Call-Info", "<url>;meta=123,<uri>");
        let s = vars.to_string();
        let parsed: Variables = s
            .parse()
            .unwrap();
        assert_eq!(
            parsed.get("origination_caller_id_number"),
            Some("9005551212")
        );
        assert_eq!(parsed.get("sip_h_Call-Info"), Some("<url>;meta=123,<uri>"));
    }

    #[test]
    fn split_unescaped_commas_basic() {
        assert_eq!(split_unescaped_commas("a,b,c"), vec!["a", "b", "c"]);
    }

    #[test]
    fn split_unescaped_commas_escaped() {
        assert_eq!(split_unescaped_commas(r"a\,b,c"), vec![r"a\,b", "c"]);
    }

    #[test]
    fn split_unescaped_commas_double_backslash() {
        // \\, = escaped backslash + comma delimiter
        assert_eq!(split_unescaped_commas(r"a\\,b"), vec![r"a\\", "b"]);
    }

    #[test]
    fn split_unescaped_commas_triple_backslash() {
        // \\\, = escaped backslash + escaped comma (no split)
        assert_eq!(split_unescaped_commas(r"a\\\,b"), vec![r"a\\\,b"]);
    }

    #[test]
    fn variables_caret_caret_separator() {
        let vars: Variables =
            "[^^:sip_invite_domain=pbx.example.com:presence_id=1211@pbx.example.com]"
                .parse()
                .unwrap();
        assert_eq!(vars.scope(), VariablesType::Channel);
        assert_eq!(vars.get("sip_invite_domain"), Some("pbx.example.com"));
        assert_eq!(vars.get("presence_id"), Some("1211@pbx.example.com"));
    }

    #[test]
    fn variables_caret_caret_display_uses_canonical_comma() {
        let vars: Variables = "[^^:a=1:b=2]"
            .parse()
            .unwrap();
        assert_eq!(vars.to_string(), "[a=1,b=2]");
    }

    #[test]
    fn variables_caret_caret_default_scope() {
        let vars: Variables = "{^^|x=1|y=2}"
            .parse()
            .unwrap();
        assert_eq!(vars.scope(), VariablesType::Default);
        assert_eq!(vars.get("x"), Some("1"));
        assert_eq!(vars.get("y"), Some("2"));
    }

    #[test]
    fn variables_caret_caret_enterprise_scope() {
        let vars: Variables = "<^^;a=1;b=2>"
            .parse()
            .unwrap();
        assert_eq!(vars.scope(), VariablesType::Enterprise);
        assert_eq!(vars.get("a"), Some("1"));
    }

    #[test]
    fn variables_caret_caret_no_unescape() {
        let vars: Variables = r"[^^:key=val\,ue:other=x]"
            .parse()
            .unwrap();
        assert_eq!(vars.get("key"), Some(r"val\,ue"));
    }

    #[test]
    fn variables_caret_caret_values_with_commas() {
        let vars: Variables = "[^^|sip_h_X-Call-Info=<urn:foo>;purpose=bar,<urn:baz>|other=val]"
            .parse()
            .unwrap();
        assert_eq!(
            vars.get("sip_h_X-Call-Info"),
            Some("<urn:foo>;purpose=bar,<urn:baz>")
        );
        assert_eq!(vars.get("other"), Some("val"));
    }

    #[test]
    fn variables_caret_caret_empty_vars() {
        let vars: Variables = "[^^:]"
            .parse()
            .unwrap();
        assert!(vars.is_empty());
        assert_eq!(vars.scope(), VariablesType::Channel);
    }

    #[test]
    fn variables_caret_caret_missing_separator() {
        assert!("[^^]"
            .parse::<Variables>()
            .is_err());
    }

    #[test]
    fn variables_caret_caret_closing_bracket_as_sep() {
        assert!("[^^]]"
            .parse::<Variables>()
            .is_err());
    }

    #[test]
    fn variables_caret_caret_equals_as_sep() {
        assert!("[^^=a=1]"
            .parse::<Variables>()
            .is_err());
    }

    #[test]
    fn variables_from_str_empty_block() {
        let result = "{}".parse::<Variables>();
        assert!(
            result.is_ok(),
            "empty variable block should parse successfully"
        );
        let vars = result.unwrap();
        assert!(
            vars.is_empty(),
            "parsed empty block should have no variables"
        );
    }

    #[test]
    fn variables_from_str_empty_channel_block() {
        let result = "[]".parse::<Variables>();
        assert!(result.is_ok());
        let vars = result.unwrap();
        assert!(vars.is_empty());
        assert_eq!(vars.scope(), VariablesType::Channel);
    }

    #[test]
    fn variables_from_str_empty_enterprise_block() {
        let result = "<>".parse::<Variables>();
        assert!(result.is_ok());
        let vars = result.unwrap();
        assert!(vars.is_empty());
        assert_eq!(vars.scope(), VariablesType::Enterprise);
    }

    #[test]
    fn serde_variables_type() {
        let json = serde_json::to_string(&VariablesType::Enterprise).unwrap();
        assert_eq!(json, "\"enterprise\"");
        let parsed: VariablesType = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, VariablesType::Enterprise);
    }

    #[test]
    fn serde_variables_flat_default() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("key1", "val1");
        vars.insert("key2", "val2");
        let json = serde_json::to_string(&vars).unwrap();
        let parsed: Variables = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.scope(), VariablesType::Default);
        assert_eq!(parsed.get("key1"), Some("val1"));
        assert_eq!(parsed.get("key2"), Some("val2"));
    }

    #[test]
    fn serde_variables_scoped_enterprise() {
        let mut vars = Variables::new(VariablesType::Enterprise);
        vars.insert("key1", "val1");
        let json = serde_json::to_string(&vars).unwrap();
        assert!(json.contains("\"enterprise\""));
        let parsed: Variables = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.scope(), VariablesType::Enterprise);
        assert_eq!(parsed.get("key1"), Some("val1"));
    }

    #[test]
    fn serde_variables_flat_map_deserializes_as_default() {
        let json = r#"{"key1":"val1","key2":"val2"}"#;
        let vars: Variables = serde_json::from_str(json).unwrap();
        assert_eq!(vars.scope(), VariablesType::Default);
        assert_eq!(vars.get("key1"), Some("val1"));
        assert_eq!(vars.get("key2"), Some("val2"));
    }

    #[test]
    fn serde_variables_scoped_deserializes() {
        let json = r#"{"scope":"channel","vars":{"k":"v"}}"#;
        let vars: Variables = serde_json::from_str(json).unwrap();
        assert_eq!(vars.scope(), VariablesType::Channel);
        assert_eq!(vars.get("k"), Some("v"));
    }
}