freeswitch-types 1.7.0-beta3

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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
//! Channel variable scope and ordered key-value storage for originate commands.
//!
//! Line numbers in this module index FreeSWITCH `v1.11.1`
//! (`c2c59645f6911a76589e5008c4d73349ded44b65`).

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

use super::originate::OriginateError;
use crate::version::FreeswitchVersion;

/// 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 => ('[', ']'),
        }
    }

    /// A `[]` block rides through the `|` and `,` leg splits before the block
    /// parse, and both consume escapes.
    fn leg_split_passes(self) -> u32 {
        match self {
            Self::Enterprise | Self::Default => 0,
            Self::Channel => 2,
        }
    }
}

/// Ordered set of channel variables with FreeSWITCH escaping.
///
/// A comma is escaped with `\,`, a backslash and a single quote with as many
/// backslashes as the [`DialStringTarget`]'s passes consume, and a value with
/// spaces is wrapped in single quotes. This form round-trips through [`FromStr`];
/// what the switch itself decodes depends on which command carries the block
/// and which parser revision reads it, documented in `docs/dial-string-format.md`.
///
/// # Serde format
///
/// [`Default`](VariablesType::Default) scope with the comma separator
/// serializes as a flat JSON map: `{"key": "value", ...}`. Anything else
/// serializes as `{"scope": "enterprise", "vars": {"key": "value"}}`, carrying
/// a `"separator"` field only when [`with_separator`](Variables::with_separator)
/// chose one. Deserialization accepts both formats; a flat map implies
/// `Default` scope and the comma. A `separator` that cannot delimit the block,
/// or that a value already contains, is refused at load.
// qual:allow(srp, god_struct) reason: "public builder; accessors read disjoint fields"
#[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,
}

impl DialStringCarrier {
    /// Dialplan variable expansion deletes an escaped quote outright, where every
    /// other pass unescapes it.
    fn deletes_escaped_quote(self) -> bool {
        matches!(self, Self::Dialplan)
    }
}

/// Which revision of the switch's bracket-block parser a dial string is rendered
/// for.
///
/// How many escape-consuming passes a block meets is the switch's to change, and
/// every escaped quote and backslash depends on it. It covers `{}`, `<>` and `[]`
/// escaping only: the inline action list and the quote pre-scan ahead of a `[]`
/// block are other parsers. Which revisions a FreeSWITCH version is known to run
/// is documented in `docs/dial-string-format.md`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum BlockParse {
    /// Both of the block's own splits, on the separator and on `=`, run the
    /// escape-consuming cleanup.
    #[default]
    PairSplitCleans,
}

impl BlockParse {
    const ALL: &'static [Self] = &[Self::PairSplitCleans];

    fn as_str(self) -> &'static str {
        match self {
            Self::PairSplitCleans => "pair_split_cleans",
        }
    }

    fn cleanup_passes(self) -> u32 {
        match self {
            Self::PairSplitCleans => 2,
        }
    }

    /// The revision a FreeSWITCH release is vouched to run, or why it cannot be.
    ///
    /// A release is vouched for only inside a range whose block parse
    /// (`switch_event.c:1737`, `switch_utils.c:2804`) was checked at every tag and
    /// whose line passed the live escaping suite. Anything else, a development
    /// build included, is refused; name a revision explicitly for it instead.
    pub fn for_version(version: &FreeswitchVersion) -> Result<Self, UnvouchedVersion> {
        let version = *version;
        let (first, last) = VOUCHED_PAIR_SPLIT_CLEANS;
        if version.is_dev() {
            Err(UnvouchedVersion::Dev { version })
        } else if version < first {
            Err(UnvouchedVersion::OlderThanVouched { version })
        } else if version > last {
            Err(UnvouchedVersion::NewerThanVouched { version })
        } else {
            Ok(Self::PairSplitCleans)
        }
    }
}

const VOUCHED_PAIR_SPLIT_CLEANS: (FreeswitchVersion, FreeswitchVersion) = (
    FreeswitchVersion::new(1, 10, 0),
    FreeswitchVersion::new(1, 10, 12),
);

/// A FreeSWITCH version [`BlockParse::for_version`] cannot vouch for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnvouchedVersion {
    /// A development build, whose version stays the same across commits.
    Dev {
        /// The version refused.
        version: FreeswitchVersion,
    },
    /// A release newer than the vouched range.
    NewerThanVouched {
        /// The version refused.
        version: FreeswitchVersion,
    },
    /// A release older than the vouched range.
    OlderThanVouched {
        /// The version refused.
        version: FreeswitchVersion,
    },
}

impl UnvouchedVersion {
    /// The version refused.
    pub fn version(&self) -> FreeswitchVersion {
        match *self {
            Self::Dev { version }
            | Self::NewerThanVouched { version }
            | Self::OlderThanVouched { version } => version,
        }
    }
}

impl fmt::Display for UnvouchedVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (first, last) = VOUCHED_PAIR_SPLIT_CLEANS;
        let why = match self {
            Self::Dev { .. } => "is a development build",
            Self::NewerThanVouched { .. } => "is newer than any vouched release",
            Self::OlderThanVouched { .. } => "is older than any vouched release",
        };
        write!(
            f,
            "FreeSWITCH {} {why}; releases {first} to {last} are vouched for, name a BlockParse explicitly",
            self.version()
        )
    }
}

impl std::error::Error for UnvouchedVersion {}

impl fmt::Display for BlockParse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for BlockParse {
    type Err = ParseBlockParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .iter()
            .copied()
            .find(|revision| {
                revision
                    .as_str()
                    .eq_ignore_ascii_case(s)
            })
            .ok_or_else(|| ParseBlockParseError(s.to_string()))
    }
}

/// A [`BlockParse`] name this crate does not know. The rejected name is the field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseBlockParseError(pub String);

impl fmt::Display for ParseBlockParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("unknown block-parse revision, expected one of:")?;
        for revision in BlockParse::ALL {
            write!(f, " {revision}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ParseBlockParseError {}

/// Where a dial string is headed: the command carrying it and the block-parser
/// revision of the switch reading it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DialStringTarget {
    carrier: DialStringCarrier,
    block_parse: BlockParse,
}

impl DialStringTarget {
    /// Target `carrier` at the default [`BlockParse`].
    pub fn new(carrier: DialStringCarrier) -> Self {
        Self {
            carrier,
            block_parse: BlockParse::default(),
        }
    }

    /// Target a switch running `block_parse`.
    pub fn with_block_parse(mut self, block_parse: BlockParse) -> Self {
        self.block_parse = block_parse;
        self
    }

    /// The command carrying the dial string.
    pub fn carrier(&self) -> DialStringCarrier {
        self.carrier
    }

    /// The block-parser revision rendered for.
    pub fn block_parse(&self) -> BlockParse {
        self.block_parse
    }

    fn passes(self, scope: VariablesType) -> u32 {
        1 + self
            .block_parse
            .cleanup_passes()
            + scope.leg_split_passes()
    }

    /// Every pass halves a run of backslashes, so a literal one needs 2^passes.
    fn backslash_escape(self, scope: VariablesType) -> String {
        "\\".repeat(1 << self.passes(scope))
    }

    /// A quote must still read `\'` entering the last pass, or bare after a
    /// carrier pass that deletes `\'`.
    fn quote_escape(self, scope: VariablesType) -> String {
        let consumed_by_carrier = if self
            .carrier
            .deletes_escaped_quote()
        {
            2
        } else {
            1
        };
        let run = (1usize << self.passes(scope)) - consumed_by_carrier;
        format!("{}'", "\\".repeat(run))
    }
}

impl From<DialStringCarrier> for DialStringTarget {
    fn from(carrier: DialStringCarrier) -> Self {
        Self::new(carrier)
    }
}

/// Reject a value the wire cannot carry, whatever escaping is applied to it.
///
/// Three 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. A single quote in a
/// channel-scope value pairs with the next quote anywhere before the peer split,
/// escaped or not, and the pair between them is swallowed into the first value.
fn check_representable(
    key: &str,
    value: &str,
    vars_type: VariablesType,
) -> Result<(), OriginateError> {
    if vars_type == VariablesType::Channel && value.contains('\'') {
        return Err(OriginateError::ParseError(format!(
            "variable {key} carries a single quote in channel scope: the switch \
             pairs it with the next quote in the dial string before it parses \
             the block, whatever escaping precedes either. Use default scope, \
             or keep the quote out of the value"
        )));
    }
    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(())
}

/// Reject a separator that cannot delimit the block it was chosen for.
///
/// Either bracket moves the end the switch counts its way to, `=` splits the
/// pair instead, `^` leaves the `^^` prefix reading as its own separator, and
/// `|` in a `[]` block is read by the leg split before the block is parsed.
fn check_separator(sep: char, vars_type: VariablesType) -> Result<(), OriginateError> {
    let (open, close) = vars_type.delimiters();
    if sep == open
        || sep == close
        || sep == '='
        || sep == '^'
        || (sep == '|' && vars_type == VariablesType::Channel)
    {
        return Err(OriginateError::ParseError(format!(
            "invalid ^^ separator: '{sep}'"
        )));
    }
    Ok(())
}

/// Escape a value for the wire, escaping the comma only when `commas_separate`
/// says it is this block's separator; a `^^` block separates on something else
/// and refuses a value carrying it, so a comma there is ordinary text. A `[]`
/// block also escapes the pipe, which the leg split would otherwise read.
fn escape_value(
    value: &str,
    target: impl Into<DialStringTarget>,
    commas_separate: bool,
    vars_type: VariablesType,
) -> String {
    let target = target.into();
    // The backslash goes first, or the ones the other rules introduce get
    // escaped in turn.
    let escaped = value
        .replace('\\', &target.backslash_escape(vars_type))
        .replace('\'', &target.quote_escape(vars_type));
    // `\,` and `\|` keep one backslash: a pass consumes `\x` only before a
    // quote, a backslash, a named escape or that pass's own delimiter.
    let escaped = if commas_separate {
        escaped.replace(',', "\\,")
    } else {
        escaped
    };
    let escaped = if vars_type == VariablesType::Channel {
        escaped.replace('|', "\\|")
    } else {
        escaped
    };
    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,
    target: DialStringTarget,
    commas_separate: bool,
    vars_type: VariablesType,
) -> String {
    let s = value
        .strip_prefix('\'')
        .and_then(|s| s.strip_suffix('\''))
        .unwrap_or(value);

    let s = if vars_type == VariablesType::Channel {
        s.replace("\\|", "|")
    } else {
        s.to_string()
    };
    let s = if commas_separate {
        s.replace("\\,", ",")
    } else {
        s
    };
    s.replace(&target.quote_escape(vars_type), "'")
        .replace(&target.backslash_escape(vars_type), "\\")
}

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. A value inserted afterwards is not checked: one carrying
    /// `sep` splits into a pair nobody wrote, silently, until
    /// [`insert`](Self::insert) becomes fallible (`docs/next-major.md`).
    pub fn with_separator(mut self, sep: char) -> Result<Self, OriginateError> {
        check_separator(sep, self.vars_type)?;
        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
                .separator
                .is_none()
        {
            self.inner
                .serialize(serializer)
        } else {
            use serde::ser::SerializeStruct;
            let fields = 2 + usize::from(
                self.separator
                    .is_some(),
            );
            let mut s = serializer.serialize_struct("Variables", fields)?;
            s.serialize_field("scope", &self.vars_type)?;
            s.serialize_field("vars", &self.inner)?;
            if let Some(sep) = self.separator {
                s.serialize_field("separator", &sep)?;
            }
            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>,
                #[serde(default)]
                separator: Option<char>,
            },
            Flat(IndexMap<String, String>),
        }

        let (vars_type, inner, separator) = match VariablesRepr::deserialize(deserializer)? {
            VariablesRepr::Scoped {
                scope,
                vars,
                separator,
            } => (scope, vars, separator),
            VariablesRepr::Flat(map) => (VariablesType::Default, map, None),
        };
        // 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)?;
        }
        let vars = Self {
            vars_type,
            inner,
            separator: None,
        };
        match separator {
            Some(sep) => vars
                .with_separator(sep)
                .map_err(serde::de::Error::custom),
            None => Ok(vars),
        }
    }
}

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

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

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

    pub(super) fn write_for(
        &self,
        f: &mut fmt::Formatter<'_>,
        target: DialStringTarget,
    ) -> 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 commas_separate = self
            .separator
            .is_none();
        let sep = self
            .separator
            .unwrap_or(',');
        for (i, (key, value)) in self
            .inner
            .iter()
            .enumerate()
        {
            if i > 0 {
                write!(f, "{sep}")?;
            }
            let value = escape_value(value, target, commas_separate, self.vars_type);
            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.into())
    }
}

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 or [`DialStringTarget`],
    /// 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, target: impl Into<DialStringTarget>) -> Result<Self, OriginateError> {
        let target = target.into();
        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 (sep, var_str) = match inner_str.strip_prefix("^^") {
            Some(rest) => {
                let sep = rest
                    .chars()
                    .next()
                    .ok_or_else(|| {
                        OriginateError::ParseError("^^ without separator character".into())
                    })?;
                check_separator(sep, vars_type)?;
                (sep, &rest[sep.len_utf8()..])
            }
            None => (',', inner_str),
        };
        let commas_separate = sep == ',';

        let mut inner = IndexMap::new();
        if !var_str.is_empty() {
            for (i, part) in split_unescaped(var_str, sep)
                .into_iter()
                .enumerate()
            {
                let (key, value) = part
                    .split_once('=')
                    .ok_or_else(|| {
                        OriginateError::ParseError(format!("missing = in variable {i}"))
                    })?;
                let value = unescape_value(value, target, commas_separate, vars_type);
                check_representable(key, &value, vars_type)?;
                inner.insert(key.to_string(), value);
            }
        }

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

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

    for (i, ch) in s.char_indices() {
        if ch == sep {
            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 + ch.len_utf8();
            }
        }
    }
    parts.push(&s[start..]);
    parts
}

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

    /// Measured on a live switch: an empty value is discarded under every
    /// encoding, silently, so nothing can be emitted for one and the refusal
    /// has to name a remedy the caller could not guess.
    #[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:?}"
            );
        }
    }

    /// The parser has to refuse what the builder refuses, `^` included:
    /// accepting a block no render of this crate can reproduce hands the caller
    /// a value that changes when it is written back out.
    #[test]
    fn the_parser_refuses_every_separator_the_builder_does() {
        for sep in ['[', ']', '=', '^'] {
            assert!(
                format!("[^^{sep}a=1{sep}b=2]")
                    .parse::<Variables>()
                    .is_err(),
                "parser 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, "l'a'b", r"l\\\\\\'a\\\\\\'b"),
            (DialStringCarrier::EslApi, "l'a'b", r"l\\\\\\\'a\\\\\\\'b"),
            (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"),
            (DialStringCarrier::Dialplan, "a|b", "a|b"),
            (DialStringCarrier::EslApi, "a|b", "a|b"),
        ];
        for (carrier, value, want) in cases {
            assert_eq!(
                escape_value(value, carrier, true, VariablesType::Default),
                want,
                "{value:?} for {carrier:?}"
            );
        }
    }

    /// A `[]` block rides through the leg splits before it is parsed: two more
    /// backslash-consuming passes, and a pipe the first of them would read.
    #[test]
    fn channel_scope_escapes_for_the_leg_splits() {
        let cases = [
            (
                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"),
            (DialStringCarrier::EslApi, "a,b", r"a\,b"),
        ];
        for (carrier, value, want) in cases {
            assert_eq!(
                escape_value(value, carrier, true, VariablesType::Channel),
                want,
                "{value:?} for {carrier:?}"
            );
        }
    }

    /// A `^^` block reaches the switch's tokenizer as often as the comma form,
    /// so every rule above still holds there; only the comma stops being the
    /// separator and so stops being escaped.
    #[test]
    fn a_chosen_separator_changes_only_the_comma() {
        let cases = [
            (DialStringCarrier::Dialplan, "it's", r"it\\\\\\'s"),
            (DialStringCarrier::EslApi, "it's", r"it\\\\\\\'s"),
            (DialStringCarrier::Dialplan, "l'a'b", r"l\\\\\\'a\\\\\\'b"),
            (DialStringCarrier::EslApi, "l'a'b", r"l\\\\\\\'a\\\\\\\'b"),
            (DialStringCarrier::Dialplan, r"a\nb", r"a\\\\\\\\nb"),
            (DialStringCarrier::EslApi, r"a\nb", r"a\\\\\\\\nb"),
            (DialStringCarrier::Dialplan, "a,b", "a,b"),
            (DialStringCarrier::EslApi, "a,b", "a,b"),
        ];
        for (carrier, value, want) in cases {
            assert_eq!(
                escape_value(value, carrier, false, VariablesType::Default),
                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}");
            }
        }
    }

    /// A chosen separator changes which character needs escaping, not whether
    /// the block is escape-processed: the switch runs the same tokenizer over
    /// it, so a value still comes back through the same undoing.
    #[test]
    fn separated_block_round_trips_at_either_carrier() {
        for carrier in [DialStringCarrier::EslApi, DialStringCarrier::Dialplan] {
            for value in ["it's", "a,b", r"C:\path", r"a\nb", "with space"] {
                let mut vars = Variables::new(VariablesType::Default);
                vars.insert("k", value);
                vars.insert("after", "sentinel");
                let vars = vars
                    .with_separator('~')
                    .expect("'~' appears in none of these values");
                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");
        vars.insert("second", "2");
        assert_eq!(vars.to_string(), "{test_key=this_value,second=2}");
    }

    #[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_basic() {
        assert_eq!(split_unescaped("a,b,c", ','), vec!["a", "b", "c"]);
        assert_eq!(split_unescaped("a~b~c", '~'), vec!["a", "b", "c"]);
    }

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

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

    #[test]
    fn split_unescaped_triple_backslash() {
        // \\\, = escaped backslash + escaped comma (no split)
        assert_eq!(split_unescaped(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"));
    }

    /// The switch consumes a backslash only before a quote, another backslash,
    /// the separator in force, or a character it has an escape for -- so in a
    /// block separated on something else, `\,` is two literal characters.
    #[test]
    fn variables_caret_caret_keeps_an_escaped_comma_literal() {
        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"));
    }

    /// A block whose separator is dropped by a round trip renders as a comma
    /// block, which splits the very value the separator was chosen to carry.
    #[test]
    fn serde_variables_separator_round_trips() {
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("codecs", "PCMA,PCMU");
        let vars = vars
            .with_separator('|')
            .unwrap();

        let json = serde_json::to_string(&vars).unwrap();
        let parsed: Variables = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.separator(), Some('|'));
        assert_eq!(parsed, vars);
        assert_eq!(parsed.to_string(), "{^^|codecs=PCMA,PCMU}");
    }

    /// The default separator has no key, so a config written before the key
    /// existed serializes back byte-identical.
    #[test]
    fn serde_variables_default_separator_is_absent() {
        let mut flat = Variables::new(VariablesType::Default);
        flat.insert("k", "v");
        assert_eq!(serde_json::to_string(&flat).unwrap(), r#"{"k":"v"}"#);

        let mut scoped = Variables::new(VariablesType::Channel);
        scoped.insert("k", "v");
        assert_eq!(
            serde_json::to_string(&scoped).unwrap(),
            r#"{"scope":"channel","vars":{"k":"v"}}"#
        );
    }

    #[test]
    fn serde_variables_separator_deserializes_from_config() {
        let json = r#"{"scope":"channel","vars":{"codecs":"PCMA,PCMU"},"separator":":"}"#;
        let vars: Variables = serde_json::from_str(json).unwrap();
        assert_eq!(vars.scope(), VariablesType::Channel);
        assert_eq!(vars.separator(), Some(':'));
        assert_eq!(vars.to_string(), "[^^:codecs=PCMA,PCMU]");
    }

    /// The leg split reads a `|` before a `[]` block is parsed, so it can
    /// separate nothing there; in `{}` it is ordinary.
    #[test]
    fn pipe_separator_is_refused_in_channel_scope_only() {
        let mut vars = Variables::new(VariablesType::Channel);
        vars.insert("k", "v");
        assert!(vars
            .clone()
            .with_separator('|')
            .is_err());
        let mut vars = Variables::new(VariablesType::Default);
        vars.insert("k", "v");
        assert!(vars
            .with_separator('|')
            .is_ok());
    }

    /// The builder's two refusals have to hold at the config boundary too, or a
    /// YAML file produces a block the same crate would not build.
    #[test]
    fn serde_variables_unusable_separator_is_refused() {
        let undelimitable = r#"{"scope":"default","vars":{"k":"v"},"separator":"="}"#;
        assert!(serde_json::from_str::<Variables>(undelimitable).is_err());

        let in_a_value =
            r#"{"scope":"default","vars":{"uri":"sip:bob@example.com"},"separator":":"}"#;
        let err = serde_json::from_str::<Variables>(in_a_value)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("uri"),
            "error does not name the variable: {err}"
        );
    }

    /// Measured: `[p1=it's,p2=don't,p3=x]` reaches the channel as
    /// `p1=its,p2=dont` with no `p2`, at every escaping depth, because the scan
    /// ahead of the peer split pairs quotes across values. The same value in
    /// default scope is ordinary.
    #[test]
    fn a_quote_in_channel_scope_is_refused_at_every_boundary() {
        let err = r"[cid=it\\\\\\\'s]"
            .parse::<Variables>()
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("cid") && err.contains("channel scope"),
            "error does not name the variable and scope: {err}"
        );

        let err = serde_json::from_str::<Variables>(r#"{"scope":"channel","vars":{"cid":"it's"}}"#)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("cid") && err.contains("channel scope"),
            "error does not name the variable and scope: {err}"
        );

        assert!(r"{cid=it\\\\\\\'s}"
            .parse::<Variables>()
            .is_ok());
        assert!(
            serde_json::from_str::<Variables>(r#"{"scope":"default","vars":{"cid":"it's"}}"#)
                .is_ok()
        );
    }

    /// Every revision a block can be rendered for; a new variant joins this list.
    const REVISIONS: &[BlockParse] = &[BlockParse::PairSplitCleans];

    #[test]
    fn a_bare_carrier_is_a_target_at_the_default_revision() {
        let target = DialStringTarget::from(DialStringCarrier::Dialplan);
        assert_eq!(target.carrier(), DialStringCarrier::Dialplan);
        assert_eq!(target.block_parse(), BlockParse::default());
        assert_eq!(BlockParse::default(), BlockParse::PairSplitCleans);
        assert_eq!(
            DialStringTarget::new(DialStringCarrier::EslApi)
                .with_block_parse(BlockParse::PairSplitCleans)
                .block_parse(),
            BlockParse::PairSplitCleans
        );
    }

    /// An enterprise block is parsed at the same depth as a default one; nothing
    /// else pins its forms.
    #[test]
    fn enterprise_scope_escapes_like_default_scope() {
        let cases = [
            (DialStringCarrier::Dialplan, "it's", r"it\\\\\\'s"),
            (DialStringCarrier::EslApi, "it's", r"it\\\\\\\'s"),
            (DialStringCarrier::EslApi, r"a\nb", r"a\\\\\\\\nb"),
            (DialStringCarrier::EslApi, "a,b", r"a\,b"),
        ];
        for (carrier, value, want) in cases {
            let target =
                DialStringTarget::new(carrier).with_block_parse(BlockParse::PairSplitCleans);
            assert_eq!(
                escape_value(value, target, true, VariablesType::Enterprise),
                want,
                "{value:?} for {carrier:?}"
            );
        }
    }

    #[test]
    fn round_trips_at_every_target() {
        let cases = [
            (
                VariablesType::Default,
                &["it's", r"C:\path", "a,b", r"a\nb", "with space"][..],
            ),
            (
                VariablesType::Enterprise,
                &["it's", r"C:\path", "a,b", "with space"][..],
            ),
            (
                VariablesType::Channel,
                &[r"C:\path", "a,b", "a|b", "with space"][..],
            ),
        ];
        for &block_parse in REVISIONS {
            for carrier in [DialStringCarrier::EslApi, DialStringCarrier::Dialplan] {
                let target = DialStringTarget::new(carrier).with_block_parse(block_parse);
                for (scope, values) in cases {
                    for &value in values {
                        let mut vars = Variables::new(scope);
                        vars.insert("k", value);
                        vars.insert("after", "sentinel");
                        let rendered = vars
                            .display_for(target)
                            .to_string();

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

    /// What the switch cannot deliver is decided before any block parse runs, so
    /// no revision makes one of these representable.
    #[test]
    fn refusals_do_not_depend_on_the_revision() {
        for &block_parse in REVISIONS {
            for carrier in [DialStringCarrier::EslApi, DialStringCarrier::Dialplan] {
                let target = DialStringTarget::new(carrier).with_block_parse(block_parse);
                for block in [
                    r"[cid=it\\\\\\\'s]",
                    "{k=,after=sentinel}",
                    "{k=oops}extra}",
                    "{^^=a=1=b=2}",
                    "[^^|a=1|b=2]",
                ] {
                    assert!(
                        Variables::parse_for(block, target).is_err(),
                        "{block} accepted at {target:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn block_parse_reads_config_spellings_and_writes_the_canonical_one() {
        for spelling in [
            "pair_split_cleans",
            "PAIR_SPLIT_CLEANS",
            "Pair_Split_Cleans",
        ] {
            assert_eq!(
                spelling
                    .parse::<BlockParse>()
                    .ok(),
                Some(BlockParse::PairSplitCleans),
                "{spelling}"
            );
        }
        assert_eq!(BlockParse::PairSplitCleans.to_string(), "pair_split_cleans");

        let err = "pair_split_whatever"
            .parse::<BlockParse>()
            .unwrap_err()
            .to_string();
        assert!(!err.contains("whatever"), "error quoted its input: {err}");
    }

    #[test]
    fn serde_block_parse_uses_the_config_spelling() {
        assert_eq!(
            serde_json::to_string(&BlockParse::PairSplitCleans).unwrap(),
            r#""pair_split_cleans""#
        );
        let parsed: BlockParse = serde_json::from_str(r#""pair_split_cleans""#).unwrap();
        assert_eq!(parsed, BlockParse::PairSplitCleans);
    }

    #[test]
    fn for_version_maps_a_vouched_release() {
        for version in [
            FreeswitchVersion::new(1, 10, 0),
            FreeswitchVersion::new(1, 10, 7),
            FreeswitchVersion::new(1, 10, 12),
        ] {
            assert_eq!(
                BlockParse::for_version(&version).ok(),
                Some(BlockParse::PairSplitCleans),
                "{version}"
            );
        }
    }

    /// A dev build reports one version across every commit, so even one below
    /// the vouched range's last release is refused.
    #[test]
    fn for_version_refuses_what_it_cannot_vouch_for() {
        for version in [
            FreeswitchVersion::new(1, 10, 12).dev(),
            FreeswitchVersion::new(1, 10, 5).dev(),
        ] {
            let err = BlockParse::for_version(&version).expect_err(&version.to_string());
            assert!(
                matches!(err, UnvouchedVersion::Dev { .. }),
                "{version}: {err:?}"
            );
            assert_eq!(err.version(), version);
        }
        for version in [
            FreeswitchVersion::new(1, 10, 13),
            FreeswitchVersion::new(1, 11, 1),
        ] {
            let err = BlockParse::for_version(&version).expect_err(&version.to_string());
            assert!(
                matches!(err, UnvouchedVersion::NewerThanVouched { .. }),
                "{version}: {err:?}"
            );
        }
        let version = FreeswitchVersion::new(1, 8, 7);
        let err = BlockParse::for_version(&version).expect_err(&version.to_string());
        assert!(
            matches!(err, UnvouchedVersion::OlderThanVouched { .. }),
            "{version}: {err:?}"
        );
    }

    /// The caller has to decide what to name instead, so the refusal says what
    /// would have been accepted.
    #[test]
    fn an_unvouched_version_names_the_vouched_range() {
        let msg = BlockParse::for_version(&FreeswitchVersion::new(1, 11, 1))
            .unwrap_err()
            .to_string();
        assert!(
            msg.contains("1.10.0") && msg.contains("1.10.12"),
            "does not name the vouched range: {msg}"
        );
    }
}