rxml_validation 0.11.0

Plumbing crate for rxml and rxml_proc crates.
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
use core::borrow::Borrow;
use core::cmp::{Ordering, PartialOrd};
use core::convert::{TryFrom, TryInto};
use core::fmt;
use core::ops::{
	Deref, Index, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
};

#[cfg(feature = "std")]
use std::{
	borrow::{Cow, ToOwned},
	iter::FromIterator,
	ops::{Add, AddAssign, DerefMut},
};

/// Type alias to access the inner type used for [`Name`] and [`NcName`]
/// irrespective of feature flags.
///
/// This will be [`compact_str::CompactString`] if the `compact_str` feature
/// flag is enabled and [`String`] otherwise.
#[cfg(feature = "compact_str")]
pub type CompactString = compact_str::CompactString;

/// Type alias to access the inner type used for [`Name`] and [`NcName`]
/// irrespective of feature flags.
///
/// This will be `compact_str::CompactString` if the `compact_str` feature
/// flag is enabled and [`String`] otherwise.
#[cfg(all(not(feature = "compact_str"), feature = "std"))]
pub type CompactString = String;

use crate::selectors;
use crate::selectors::CharSelector;
use crate::Error;
use crate::{validate_name, validate_ncname};

macro_rules! rxml_unsafe_str_construct_doc {
	($name:ident, $other:ident) => {
		concat!(
			"Construct a `",
			stringify!($name),
			"` without enforcing anything\n",
			"\n",
			"# Safety\n",
			"\n",
			"The caller is responsible for ensuring that the passed [`",
			stringify!($other),
			"`] is in fact a valid `",
			stringify!($name),
			"`.\n",
		)
	};
}

macro_rules! rxml_safe_str_construct_doc {
	($name:ident, $other:ident, $more:expr) => {
		concat!(
			"Converts a [`",
			stringify!($other),
			"`] to a `",
			stringify!($name),
			"`.\n",
			"\n",
			"If the given `",
			stringify!($other),
			"` does not conform to the restrictions imposed by `",
			stringify!($name),
			"`, an error is returned.\n",
			$more
		)
	};
}

macro_rules! rxml_split_at_example {
	($borrowed:ty) => {
		concat!(
			"\n\n```\n",
			"# use std::convert::TryInto;\n",
			"# use rxml_validation::",
			stringify!($borrowed),
			";\n",
			"let value: &",
			stringify!($borrowed),
			" = \"foobar\".try_into().unwrap();\n",
			"let (lhs, rhs) = value.split_at(3);\n",
			"assert_eq!(lhs, \"foo\");\n",
			"assert_eq!(rhs, \"bar\");\n",
			"```\n",
		)
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_make_ascii_lowercase_example {
	($owned:ty, $borrowed:ty) => {
		concat!(
			"\n\n# Example\n\n```\n",
			"# use std::convert::TryInto;\n",
			"# use rxml_validation::{",
			stringify!($borrowed),
			", ",
			stringify!($owned),
			"};\n",
			"let mut owned: ",
			stringify!($owned),
			" = \"FÖöBar\".try_into().unwrap();\n",
			"let borrowed: &mut ",
			stringify!($borrowed),
			" = &mut owned;\n",
			"borrowed.make_ascii_lowercase();\n",
			"assert_eq!(borrowed, \"fÖöbar\");\n",
			"```\n",
		)
	};
}

#[cfg(not(feature = "std"))]
macro_rules! rxml_make_ascii_lowercase_example {
	($owned:ty, $borrowed:ty) => {
		""
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_make_ascii_uppercase_example {
	($owned:ty, $borrowed:ty) => {
		concat!(
			"\n\n# Example\n\n```\n",
			"# use std::convert::TryInto;\n",
			"# use rxml_validation::{",
			stringify!($borrowed),
			", ",
			stringify!($owned),
			"};\n",
			"let mut owned: ",
			stringify!($owned),
			" = \"FÖöBar\".try_into().unwrap();\n",
			"let borrowed: &mut ",
			stringify!($borrowed),
			" = &mut owned;\n",
			"borrowed.make_ascii_uppercase();\n",
			"assert_eq!(borrowed, \"FÖöBAR\");\n",
			"```\n",
		)
	};
}

#[cfg(not(feature = "std"))]
macro_rules! rxml_make_ascii_uppercase_example {
	($owned:ty, $borrowed:ty) => {
		""
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_split_off_panic_on_empty {
	() => {
		concat!(
			"\n",
			"# Panics\n",
			"\n",
			"If `idx` is 0 or equal to the length minus one, as the empty ",
			"string is not valid.\n",
		)
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_split_off_panics {
	(NcName) => {
		rxml_split_off_panic_on_empty!()
	};
	(Name) => {
		rxml_split_off_panic_on_empty!()
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_split_off_example {
	($ty:ident) => {
		concat!(
			"\n",
			"```\n",
			"# use std::convert::TryInto;\n",
			"# use rxml_validation::",
			stringify!($ty),
			";\n",
			"let mut value: ",
			stringify!($ty),
			" = \"foobar\".try_into().unwrap();\n",
			"let rhs: ",
			stringify!($ty),
			" = value.split_off(3);\n",
			"assert_eq!(value, \"foo\");\n",
			"assert_eq!(rhs, \"bar\");\n",
			"```\n",
		)
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_insert_str_example {
	($owned:ident, $borrowed:ident) => {
		concat!(
			"\n",
			"```\n",
			"# use std::convert::TryInto;\n",
			"# use rxml_validation::{",
			stringify!($owned),
			", ",
			stringify!($borrowed),
			"};\n",
			"let mut value: ",
			stringify!($owned),
			" = \"foobaz\".try_into().unwrap();\n",
			"let to_insert: &",
			stringify!($borrowed),
			" = \"bar\".try_into().unwrap();\n",
			"value.insert_str(3, to_insert);\n",
			"assert_eq!(value, \"foobarbaz\");\n",
			"```\n",
		)
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_push_str_example {
	($owned:ident, $borrowed:ident) => {
		concat!(
			"\n",
			"```\n",
			"# use std::convert::TryInto;\n",
			"# use rxml_validation::{",
			stringify!($owned),
			", ",
			stringify!($borrowed),
			"};\n",
			"let mut value: ",
			stringify!($owned),
			" = \"foobar\".try_into().unwrap();\n",
			"let to_append: &",
			stringify!($borrowed),
			" = \"baz\".try_into().unwrap();\n",
			"value.push_str(to_append);\n",
			"assert_eq!(value, \"foobarbaz\");\n",
			"```\n",
		)
	};
}

#[cfg(all(not(feature = "compact_str"), feature = "std"))]
macro_rules! rxml_non_compact_str_only_note {
	(CompactString) => {
		"\n# Note\nThis function is only available *without* the `compact_str` feature!\n"
	};
	($other:ident) => {
		""
	};
}

#[cfg(feature = "std")]
macro_rules! rxml_custom_string_type {
	(
		$(#[$outer:meta])*
		pub struct $name:ident($string:ident) use $check:ident => $borrowed:ident;
	) => {
		$(#[$outer])*
		#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord)]
		#[repr(transparent)]
		pub struct $name($string);

		impl $name {
			/// Extract the inner string and return it.
			pub fn into_inner(self) -> $string {
				self.0
			}

			/// Obtain a reference to the inner string slice.
			pub fn as_str(&self) -> &str {
				self.0.as_str()
			}

			/// Return the capacity, in bytes.
			pub fn capacity(&self) -> usize {
				self.0.capacity()
			}

			/// Inserts a slice into this typed string at a byte position.
			///
			/// This is an *O(n)* operation as it requires copying every
			/// element into the buffer.
			///
			/// # Panics
			///
			/// Panics if `idx` is larger than the string's length, or if it
			/// does not lie on a `char` boundary.
			///
			/// # Example
			///
			#[doc = rxml_insert_str_example!($name, $borrowed)]
			pub fn insert_str(&mut self, idx: usize, string: &$borrowed) {
				// CORRECTNESS: as $borrowed is a valid sub-slice of $name,
				// it is also valid at the start of $name -> we can insert it
				// at arbitrary positions.
				self.0.insert_str(idx, &string.0);
			}

			/// Return the length of this string in bytes.
			pub fn len(&self) -> usize {
				self.0.len()
			}

			/// Reserve capacity for at least `additional` bytes more than the
			/// current length.
			pub fn reserve(&mut self, additional: usize) {
				self.0.reserve(additional)
			}

			/// Reserve capacity for at least `additional` bytes more than the current
			/// length.
			///
			/// Unlike `reserve`, this will not over-allocate, ever.
			// ↓ CompactString does not have this.
			#[doc = rxml_non_compact_str_only_note!($string)]
			#[cfg(not(feature = "compact_str"))]
			pub fn reserve_exact(&mut self, additional: usize) {
				self.0.reserve_exact(additional)
			}

			/// Shrink the capacity of this string with a lower bound.
			pub fn shrink_to(&mut self, min_capacity: usize) {
				self.0.shrink_to(min_capacity)
			}

			/// Shrink the capacity of this string to match its length.
			pub fn shrink_to_fit(&mut self) {
				self.0.shrink_to_fit()
			}

			#[doc = rxml_unsafe_str_construct_doc!($name, str)]
			pub unsafe fn from_str_unchecked<T: AsRef<str>>(s: T) -> Self {
				Self(s.as_ref().into())
			}

			#[doc = rxml_unsafe_str_construct_doc!($name, String)]
			pub unsafe fn from_string_unchecked<T: Into<String>>(s: T) -> Self {
				Self(s.into().into())
			}

			#[cfg(feature = "compact_str")]
			#[allow(dead_code)]
			unsafe fn from_auto_unchecked(s: CompactString) -> Self {
				Self(s.into())
			}

			#[cfg(not(feature = "compact_str"))]
			#[allow(dead_code)]
			unsafe fn from_auto_unchecked(s: String) -> Self {
				Self(s.into())
			}

			#[doc = rxml_unsafe_str_construct_doc!($name, CompactString)]
			#[cfg(feature = "compact_str")]
			#[cfg_attr(docsrs, doc(cfg(feature = "compact_str")))]
			pub unsafe fn from_compact_str_unchecked<T: Into<CompactString>>(s: T) -> Self {
				Self(s.into().into())
			}

			unsafe fn from_native_unchecked(s: $string) -> Self {
				Self(s)
			}

			/// Appends a slice to this typed string.
			///
			/// This is an *O(n)* operation as it requires copying every
			/// element into the buffer.
			///
			/// # Example
			///
			#[doc = rxml_push_str_example!($name, $borrowed)]
			// CORRECTNESS:
			// For NcName and Name it holds that concatenations of these types
			// are correct.
			pub fn push_str(&mut self, v: &$borrowed) {
				self.0.push_str(&v.0)
			}
		}

		impl Deref for $name {
			type Target = $borrowed;

			fn deref(&self) -> &Self::Target {
				// SAFETY: $borrowed is assumed to use the same check; this is
				// enforced by using the pair macro.
				unsafe { $borrowed::from_str_unchecked(&self.0) }
			}
		}

		impl DerefMut for $name {
			fn deref_mut(&mut self) -> &mut Self::Target {
				// SAFETY: $borrowed is assumed to use the same check; this is
				// enforced by using the pair macro.
				unsafe { $borrowed::from_str_unchecked_mut(&mut self.0) }
			}
		}

		impl Borrow<$string> for $name {
			fn borrow(&self) -> &$string {
				&self.0
			}
		}

		impl Borrow<$borrowed> for $name {
			fn borrow(&self) -> &$borrowed {
				// SAFETY: $borrowed is assumed to use the same check; this is
				// enforced by using the pair macro.
				unsafe { $borrowed::from_str_unchecked(&self.0) }
			}
		}

		impl Borrow<str> for $name {
			fn borrow(&self) -> &str {
				&self.0
			}
		}

		impl AsRef<$string> for $name {
			fn as_ref(&self) -> &$string {
				&self.0
			}
		}

		impl AsRef<$borrowed> for $name {
			fn as_ref(&self) -> &$borrowed {
				// SAFETY: $borrowed is assumed to use the same check; this is
				// enforced by using the pair macro.
				unsafe { $borrowed::from_str_unchecked(&self.0) }
			}
		}

		impl AsRef<str> for $name {
			fn as_ref(&self) -> &str {
				&self.0
			}
		}

		impl PartialEq<str> for $name {
			fn eq(&self, other: &str) -> bool {
				self.0 == other
			}
		}

		// following the example of std::string::String, we define PartialEq
		// against the slice and the base type.
		impl PartialEq<$name> for str {
			fn eq(&self, other: &$name) -> bool {
				other.0 == self
			}
		}

		impl PartialEq<&str> for $name {
			fn eq(&self, other: &&str) -> bool {
				&self.0 == other
			}
		}

		impl PartialEq<$name> for &str {
			fn eq(&self, other: &$name) -> bool {
				other.0 == *self
			}
		}

		impl PartialEq<$borrowed> for $name {
			fn eq(&self, other: &$borrowed) -> bool {
				self.0 == &other.0
			}
		}

		impl PartialEq<$name> for $borrowed {
			fn eq(&self, other: &$name) -> bool {
				other.0 == &self.0
			}
		}

		impl PartialEq<&$borrowed> for $name {
			fn eq(&self, other: &&$borrowed) -> bool {
				self.0 == &other.0
			}
		}

		impl PartialEq<$name> for &$borrowed {
			fn eq(&self, other: &$name) -> bool {
				other.0 == &self.0
			}
		}

		impl PartialOrd<$name> for $name {
			fn partial_cmp(&self, other: &$name) -> Option<Ordering> {
				self.0.partial_cmp(&other.0)
			}
		}

		impl From<$name> for String {
			fn from(other: $name) -> Self {
				other.0.into()
			}
		}

		#[cfg(feature = "compact_str")]
		#[cfg_attr(docsrs, doc(cfg(feature = "compact_str")))]
		impl From<$name> for CompactString {
			fn from(other: $name) -> Self {
				other.0.into()
			}
		}

		impl<'x> From<$name> for Cow<'x, $borrowed> {
			fn from(other: $name) -> Self {
				Self::Owned(other)
			}
		}

		impl<'x> From<Cow<'x, $borrowed>> for $name {
			fn from(other: Cow<'x, $borrowed>) -> Self {
				other.into_owned()
			}
		}

		#[cfg(feature = "compact_str")]
		#[cfg_attr(docsrs, doc(cfg(feature = "compact_str")))]
		impl TryFrom<CompactString> for $name {
			type Error = Error;

			#[doc = rxml_safe_str_construct_doc!($name, CompactString, "")]
			fn try_from(other: CompactString) -> Result<Self, Self::Error> {
				$check(&other)?;
				Ok($name(other.into()))
			}
		}

		impl TryFrom<String> for $name {
			type Error = Error;

			#[doc = rxml_safe_str_construct_doc!($name, String, "")]
			fn try_from(other: String) -> Result<Self, Self::Error> {
				$check(&other)?;
				Ok($name(other.into()))
			}
		}

		impl TryFrom<&str> for $name {
			type Error = Error;

			#[doc = rxml_safe_str_construct_doc!($name, str, "")]
			fn try_from(other: &str) -> Result<Self, Self::Error> {
				$check(other)?;
				Ok($name(other.into()))
			}
		}

		impl fmt::Display for $name {
			fn fmt<'f>(&self, f: &'f mut fmt::Formatter) -> fmt::Result {
				f.write_str(&self.0 as &str)
			}
		}

		// The impls below here are inspired by the list of trait impls of
		// String.

		// CORRECTNESS:
		// For NcName and Name it holds that concatenations of these types are
		// correct.
		//
		// That is because while they may have constraints on the characters
		// at the beginning, the characters allowed in the remainder of the
		// respective string types are a superset of those allowed as first
		// character.
		impl Add<&$borrowed> for $name {
			type Output = $name;

			fn add(mut self, rhs: &$borrowed) -> Self::Output {
				self += rhs;
				self
			}
		}

		impl AddAssign<&$borrowed> for $name {
			fn add_assign(&mut self, rhs: &$borrowed) {
				self.0.push_str(&rhs.0)
			}
		}

		impl<'a> Extend<&'a $borrowed> for $name {
			fn extend<I: IntoIterator<Item = &'a $borrowed>>(&mut self, iter: I) {
				self.0.extend(iter.into_iter().map(|x| &x.0))
			}
		}

		impl Extend<Box<$borrowed>> for $name {
			fn extend<I: IntoIterator<Item = Box<$borrowed>>>(&mut self, iter: I) {
				for item in iter {
					self.add_assign(&item);
				}
			}
		}

		impl<'a> Extend<Cow<'a, $borrowed>> for $name {
			fn extend<I: IntoIterator<Item = Cow<'a, $borrowed>>>(&mut self, iter: I) {
				for item in iter {
					self.add_assign(&item);
				}
			}
		}

		impl Extend<$name> for $name {
			fn extend<I: IntoIterator<Item = $name>>(&mut self, iter: I) {
				self.0.extend(iter.into_iter().map(|x| x.0))
			}
		}

		impl<'x> FromIterator<&'x $borrowed> for $name {
			fn from_iter<I: IntoIterator<Item = &'x $borrowed>>(iter: I) -> Self {
				// SAFETY: see note above impl Add<&$borrowed>.
				unsafe {
					Self::from_native_unchecked(
						<$string>::from_iter(iter.into_iter().map(|x| &x.0))
					)
				}
			}
		}

		impl FromIterator<Box<$borrowed>> for $name {
			fn from_iter<I: IntoIterator<Item = Box<$borrowed>>>(iter: I) -> Self {
				let mut buf = <$string>::with_capacity(0);
				for item in iter {
					buf.push_str(&item.0);
				}
				unsafe {
					Self::from_native_unchecked(buf)
				}
			}
		}

		impl<'x> FromIterator<Cow<'x, $borrowed>> for $name {
			fn from_iter<I: IntoIterator<Item = Cow<'x, $borrowed>>>(iter: I) -> Self {
				let mut buf = <$string>::with_capacity(0);
				for item in iter {
					buf.push_str(&item.0);
				}
				unsafe {
					Self::from_native_unchecked(buf)
				}
			}
		}
	}
}

macro_rules! rxml_custom_str_type {
	(
		$(#[$outer:meta])*
		pub struct $name:ident(str) use $check:ident => $owned:ident;
	) => {
		$(#[$outer])*
		#[derive(Debug, Hash, PartialEq, Eq, Ord)]
		#[repr(transparent)]
		pub struct $name(str);

		impl $name {
			#[doc = rxml_safe_str_construct_doc!($name, str, "")]
			pub fn from_str<'x>(s: &'x str) -> Result<&'x Self, Error> {
				s.try_into()
			}

			/// Access the underlying str.
			///
			/// This is mostly provided for use in const functions.
			pub const fn as_str(&self) -> &str {
				&self.0
			}

			#[doc = rxml_unsafe_str_construct_doc!($name, str)]
			pub const unsafe fn from_str_unchecked<'x>(s: &'x str) -> &'x Self {
				core::mem::transmute(s)
			}

			#[doc = rxml_unsafe_str_construct_doc!($name, str)]
			pub unsafe fn from_str_unchecked_mut<'x>(s: &'x mut str) -> &'x mut Self {
				core::mem::transmute(s)
			}

			/// Replace A-Z with a-z, in-place.
			///
			/// Non-ASCII characters remain unchanged.
			#[doc = rxml_make_ascii_lowercase_example!($owned, $name)]
			pub fn make_ascii_lowercase(&mut self) {
				self.0.make_ascii_lowercase()
			}

			/// Replace a-z with A-Z, in-place.
			///
			/// Non-ASCII characters remain unchanged.
			#[doc = rxml_make_ascii_uppercase_example!($owned, $name)]
			pub fn make_ascii_uppercase(&mut self) {
				self.0.make_ascii_uppercase()
			}
		}

		impl Deref for $name {
			type Target = str;

			fn deref(&self) -> &Self::Target {
				&self.0
			}
		}

		impl AsRef<str> for $name {
			fn as_ref(&self) -> &str {
				&self.0
			}
		}

		impl AsRef<$name> for &$name {
			fn as_ref(&self) -> &$name {
				&self
			}
		}

		impl PartialEq<str> for $name {
			fn eq(&self, other: &str) -> bool {
				&self.0 == other
			}
		}

		impl PartialEq<$name> for str {
			fn eq(&self, other: &$name) -> bool {
				self == &other.0
			}
		}

		impl PartialOrd<$name> for $name {
			fn partial_cmp(&self, other: &$name) -> Option<Ordering> {
				self.0.partial_cmp(&other.0)
			}
		}

		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		impl ToOwned for $name {
			type Owned = $owned;

			fn to_owned(&self) ->Self::Owned {
				self.into()
			}
		}

		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		impl From<&$name> for $owned {
			fn from(other: &$name) -> Self {
				// SAFETY: $owned is assumed to use the same check; this is
				// enforced by using the pair macro.
				unsafe { $owned::from_str_unchecked(&other.0) }
			}
		}

		impl<'x> TryFrom<&'x str> for &'x $name {
			type Error = Error;

			fn try_from(other: &'x str) -> Result<Self, Self::Error> {
				$check(other)?;
				// SAFETY: the content check is executed right above and we're
				// transmuting &str into a repr(transparent) of &str.
				Ok(unsafe { core::mem::transmute(other) } )
			}
		}

		impl fmt::Display for $name {
			fn fmt<'f>(&self, f: &'f mut fmt::Formatter) -> fmt::Result {
				f.write_str(&self.0)
			}
		}
	}
}

macro_rules! rxml_index_impl {
	($ty:ty, $selcode:expr, $borrowed:ty, $rangety:ty) => {
		impl Index<$rangety> for $ty {
			type Output = $borrowed;

			fn index(&self, index: $rangety) -> &$borrowed {
				let tmp = &self.0[index];
				let firstchar = tmp.chars().next();
				if !($selcode(firstchar)) {
					panic!(concat!("slice is not a valid ", stringify!($borrowed)));
				}
				// SAFETY: please please point $selcode at the right stuff, kthxbai.
				unsafe { <$borrowed>::from_str_unchecked(tmp) }
			}
		}
	};
}

macro_rules! rxml_splitting_impls {
	($ty:ident => $firstsel:path => $borrowed:ident) => {
		rxml_splitting_impls!($ty => (|firstchar: Option<char>| firstchar.map(|x| $firstsel.select(x)).unwrap_or(false)) => $borrowed);
	};
	($ty:ident => $selcode:expr => $borrowed:ident) => {
		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		rxml_index_impl!($ty, $selcode, $borrowed, Range<usize>);

		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		rxml_index_impl!($ty, $selcode, $borrowed, RangeFrom<usize>);

		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		rxml_index_impl!($ty, $selcode, $borrowed, RangeFull);

		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		rxml_index_impl!($ty, $selcode, $borrowed, RangeInclusive<usize>);

		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		rxml_index_impl!($ty, $selcode, $borrowed, RangeTo<usize>);

		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		rxml_index_impl!($ty, $selcode, $borrowed, RangeToInclusive<usize>);

		rxml_index_impl!($borrowed, $selcode, $borrowed, Range<usize>);
		rxml_index_impl!($borrowed, $selcode, $borrowed, RangeFrom<usize>);
		rxml_index_impl!($borrowed, $selcode, $borrowed, RangeFull);
		rxml_index_impl!($borrowed, $selcode, $borrowed, RangeInclusive<usize>);
		rxml_index_impl!($borrowed, $selcode, $borrowed, RangeTo<usize>);
		rxml_index_impl!($borrowed, $selcode, $borrowed, RangeToInclusive<usize>);


		#[cfg(feature = "std")]
		#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
		impl $ty {
			/// Splits the string into two at the given byte index.
			#[doc = rxml_split_off_panics!($ty)]
			///
			/// # Example
			///
			#[doc = rxml_split_off_example!($ty)]
			pub fn split_off(&mut self, at: usize) -> Self {
				let other = self.0.split_off(at);
				if !<$borrowed>::verify(&other) || !<$borrowed>::verify(&self.0) {
					panic!(concat!("split string is not a valid ", stringify!($ty)));
				}
				// SAFETY: please please point $selcode at the right stuff, kthxbai.
				unsafe {
					<$ty>::from_str_unchecked(other)
				}
			}
		}

		impl $borrowed {
			fn verify(s: &str) -> bool {
				let firstchar = s.chars().next();
				return $selcode(firstchar);
			}

			/// Divide one string slice into two at an index.
			///
			/// # Panics
			///
			/// Panics if `mid` is not on a UTF-8 code point boundary, or if
			/// it is past the end of the last code point of the slice, or
			/// if either resulting part is not a valid slice of this type.
			///
			/// # Example
			#[doc = rxml_split_at_example!($borrowed)]
			pub fn split_at(&self, mid: usize) -> (&Self, &Self) {
				let (a, b) = self.0.split_at(mid);
				if !Self::verify(a) || !Self::verify(b) {
					panic!(concat!("split_at result is not a valid ", stringify!($borrowed)));
				}
				// SAFETY: please please point $selcode at the right stuff, kthxbai.
				unsafe {
					(
						Self::from_str_unchecked(a),
						Self::from_str_unchecked(b),
					)
				}
			}

			/// Divide one mutable string slice into two at an index.
			///
			/// # Panics
			///
			/// Panics if `mid` is not on a UTF-8 code point boundary, or if
			/// it is past the end of the last code point of the slice, or
			/// if either resulting part is not a valid slice of this type.
			pub fn split_at_mut(&mut self, mid: usize) -> (&mut Self, &mut Self) {
				let (a, b) = self.0.split_at_mut(mid);
				if !Self::verify(a) || !Self::verify(b) {
					panic!(concat!("split_at_mut result is not a valid ", stringify!($borrowed)));
				}
				// SAFETY: please please point $selcode at the right stuff, kthxbai.
				unsafe {
					(
						Self::from_str_unchecked_mut(a),
						Self::from_str_unchecked_mut(b),
					)
				}
			}
		}
	}
}

macro_rules! rxml_custom_string_type_pair {
	(
		$(#[$ownedmeta:meta])*
		pub struct $owned:ident($string:ident) use $check:ident;

		$(#[$borrowedmeta:meta])*
		pub struct $borrowed:ident(str);
	) => {
		#[cfg(feature = "std")]
		rxml_custom_string_type!{
			$(#[$ownedmeta])*
			#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
			pub struct $owned($string) use $check => $borrowed;
		}

		rxml_custom_str_type!{
			$(#[$borrowedmeta])*
			pub struct $borrowed(str) use $check => $owned;
		}
	}
}

rxml_custom_string_type_pair! {
	/// String which conforms to the Name production of XML 1.0.
	///
	/// [`Name`] corresponds to a (restricted) [`String`]. For a [`str`]-like type
	/// with the same restrictions, see [`NameStr`].
	///
	/// If using the `rxml` crate and the `macros` feature of the `rxml` crate
	/// is enabled, `&NameStr` can be created from a string literal at compile
	/// time using the `rxml::xml_name` macro.
	///
	/// Since [`Name`] (indirectly) derefs to [`str`], all (non-mutable)
	/// methods from [`str`] are available.
	///
	/// # Formal definition
	///
	/// The data inside [`Name`] (and [`NameStr`]) is guaranteed to conform to
	/// the `Name` production of the below grammar, quoted from
	/// [XML 1.0 § 2.3](https://www.w3.org/TR/REC-xml/#NT-NameStartChar):
	///
	/// ```text
	/// [4]  NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6]
	///                        | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D]
	///                        | [#x37F-#x1FFF] | [#x200C-#x200D]
	///                        | [#x2070-#x218F] | [#x2C00-#x2FEF]
	///                        | [#x3001-#xD7FF] | [#xF900-#xFDCF]
	///                        | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
	/// [4a] NameChar      ::= NameStartChar | "-" | "." | [0-9] | #xB7
	///                        | [#x0300-#x036F] | [#x203F-#x2040]
	/// [5]  Name          ::= NameStartChar (NameChar)*
	/// ```
	pub struct Name(CompactString) use validate_name;

	/// str which conforms to the Name production of XML 1.0.
	///
	/// [`NameStr`] corresponds to a (restricted) [`str`]. For a [`String`]-like
	/// type with the same restrictions as well as the formal definition of those
	/// restrictions, see [`Name`].
	///
	/// If using the `rxml` crate and the `macros` feature of the `rxml` crate
	/// is enabled, `&NameStr` can be created from a string literal at compile
	/// time using the `rxml::xml_name` macro.
	///
	/// Since [`NameStr`] derefs to [`str`], all (non-mutable) methods from
	/// [`str`] are available.
	pub struct NameStr(str);
}

rxml_splitting_impls! {
	Name => selectors::CLASS_XML_NAMESTART => NameStr
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl Name {
	/// Split the name at a colon, if it exists.
	///
	/// If the name contains no colon, the function returns `(None, self)`.
	/// If the name contains exactly one colon, the function returns the part
	/// before the colon (the prefix) in the first return value and the part
	/// following the colon (the suffix) as second return value.
	///
	/// If neither of the two cases apply or the string on either side of the
	/// colon is empty, an error is returned.
	///
	/// This function optimizes the split (compared to operating on a borrowed
	/// [`NameStr`] and then cloning the returned parts) by avoiding
	/// unnecessary copying.
	///
	/// # Example
	///
	/// ```
	/// # use rxml_validation::Name;
	/// # use std::convert::TryFrom;
	/// // with prefix:
	/// let name = Name::try_from("foo:bar").unwrap();
	/// let (prefix, local) = name.split_name().unwrap();
	/// assert_eq!(prefix.unwrap(), "foo");
	/// assert_eq!(local, "bar");
	///
	/// // without prefix:
	/// let name = Name::try_from("no-prefix").unwrap();
	/// let (prefix, local) = name.split_name().unwrap();
	/// assert!(prefix.is_none());
	/// assert_eq!(local, "no-prefix");
	/// ```
	pub fn split_name(self) -> Result<(Option<NcName>, NcName), Error> {
		let mut name = self.0;
		let colon_pos = match name.find(':') {
			None => return Ok((None, unsafe { NcName::from_auto_unchecked(name) })),
			Some(pos) => pos,
		};
		if colon_pos == 0 || colon_pos == name.len() - 1 {
			return Err(Error::EmptyNamePart);
		}

		let localname = name.split_off(colon_pos + 1);
		let mut prefix = name;

		if localname.find(':').is_some() {
			// Namespaces in XML 1.0 (Third Edition) namespace-well-formed criterium 1
			return Err(Error::MultiColonName);
		};
		if !selectors::CLASS_XML_NAMESTART.select(localname.chars().next().unwrap()) {
			// Namespaces in XML 1.0 (Third Edition) NcName production
			return Err(Error::InvalidLocalName);
		}

		prefix.pop();
		// do not shrink to fit here -- the prefix will be used when the element
		// is finalized to put it on the stack for quick validation of the
		// </element> token.

		debug_assert!(prefix.len() > 0);
		debug_assert!(localname.len() > 0);
		Ok((
			Some(unsafe { NcName::from_auto_unchecked(prefix) }),
			unsafe { NcName::from_auto_unchecked(localname) },
		))
	}
}

impl NameStr {
	/// Create an owned copy of the string as [`Name`].
	///
	/// This operation is also available as implementation of the `Into`
	/// trait.
	#[cfg(feature = "std")]
	#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
	pub fn to_name(&self) -> Name {
		self.into()
	}

	/// Split the name at a colon, if it exists.
	///
	/// If the name contains no colon, the function returns `(None, self)`.
	/// If the name contains exactly one colon, the function returns the part
	/// before the colon (the prefix) in the first return value and the part
	/// following the colon (the suffix) as second return value.
	///
	/// If neither of the two cases apply or the string on either side of the
	/// colon is empty, an error is returned.
	///
	/// # Example
	///
	/// ```
	/// # use rxml_validation::NameStr;
	/// # use std::convert::TryInto;
	/// // with prefix:
	/// let name: &NameStr = "foo:bar".try_into().unwrap();
	/// let (prefix, local) = name.split_name().unwrap();
	/// assert_eq!(prefix.unwrap(), "foo");
	/// assert_eq!(local, "bar");
	///
	/// // without prefix:
	/// let name: &NameStr = "no-prefix".try_into().unwrap();
	/// let (prefix, local) = name.split_name().unwrap();
	/// assert!(prefix.is_none());
	/// assert_eq!(local, "no-prefix");
	/// ```
	pub fn split_name(&self) -> Result<(Option<&'_ NcNameStr>, &'_ NcNameStr), Error> {
		let name = &self.0;
		let colon_pos = match name.find(':') {
			None => return Ok((None, unsafe { NcNameStr::from_str_unchecked(name) })),
			Some(pos) => pos,
		};
		if colon_pos == 0 || colon_pos == name.len() - 1 {
			return Err(Error::EmptyNamePart);
		}

		let (prefix, localname) = name.split_at(colon_pos);
		let localname = &localname[1..];

		if localname.find(':').is_some() {
			// Namespaces in XML 1.0 (Third Edition) namespace-well-formed criterium 1
			return Err(Error::MultiColonName);
		};
		if !selectors::CLASS_XML_NAMESTART.select(localname.chars().next().unwrap()) {
			// Namespaces in XML 1.0 (Third Edition) NcName production
			return Err(Error::InvalidLocalName);
		}

		debug_assert!(prefix.len() > 0);
		debug_assert!(localname.len() > 0);
		Ok((
			Some(unsafe { NcNameStr::from_str_unchecked(prefix) }),
			unsafe { NcNameStr::from_str_unchecked(localname) },
		))
	}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl From<NcName> for Name {
	fn from(other: NcName) -> Self {
		other.into_name()
	}
}

impl<'x> From<&'x NcNameStr> for &'x NameStr {
	fn from(other: &'x NcNameStr) -> Self {
		other.as_namestr()
	}
}

rxml_custom_string_type_pair! {
	/// String which conforms to the NcName production of Namespaces in XML 1.0.
	///
	/// [`NcName`] corresponds to a (restricted) [`String`]. For a [`str`]-like
	/// type with the same restrictions, see [`NcNameStr`].
	///
	/// If using the `rxml` crate and the `macros` feature of the `rxml` crate
	/// is enabled, `&NcNameStr` can be created from a string literal at
	/// compile time using the `rxml::xml_ncname` macro.
	///
	/// Since [`NcName`] (indirectly) derefs to [`str`], all (non-mutable)
	/// methods from [`str`] are available.
	///
	/// # Formal definition
	///
	/// The data inside [`NcName`] (and [`NcNameStr`]) is guaranteed to conform to
	/// the `NcName` production of the below grammar, quoted from
	/// [Namespaces in XML 1.0 § 3](https://www.w3.org/TR/REC-xml-names/#NT-NcName):
	///
	/// ```text
	/// [4] NcName ::= Name - (Char* ':' Char*)  /* An XML Name, minus the ":" */
	/// ```
	pub struct NcName(CompactString) use validate_ncname;

	/// str which conforms to the NcName production of Namespaces in XML 1.0.
	///
	/// [`NcNameStr`] corresponds to a (restricted) [`str`]. For a [`String`]-like
	/// type with the same restrictions as well as the formal definition of those
	/// restrictions, see [`NcName`].
	///
	/// If using the `rxml` crate and the `macros` feature of the `rxml` crate
	/// is enabled, `&NcNameStr` can be created from a string literal at
	/// compile time using the `rxml::xml_ncname` macro.
	///
	/// Since [`NcNameStr`] derefs to [`str`], all (non-mutable) methods from
	/// [`str`] are available.
	pub struct NcNameStr(str);
}

rxml_splitting_impls! {
	NcName => selectors::CLASS_XML_NAMESTART => NcNameStr
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl NcName {
	/// Compose two [`NcName`] objects to one [`Name`], separating them with
	/// a colon.
	///
	/// As an [`NcName`] is always a valid [`Name`], the composition of the
	/// two with a `:` as separator is also a valid [`Name`].
	///
	/// This is the inverse of [`Name::split_name()`].
	///
	/// # Example
	///
	/// ```
	/// # use rxml_validation::NcName;
	/// # use std::convert::TryFrom;
	/// let prefix = NcName::try_from("xmlns").unwrap();
	/// let localname = NcName::try_from("stream").unwrap();
	/// assert_eq!(prefix.add_suffix(&localname), "xmlns:stream");
	/// ```
	pub fn add_suffix(self, suffix: &NcNameStr) -> Name {
		let mut s: String = self.0.into();
		s.reserve(suffix.len() + 1);
		s.push_str(":");
		s.push_str(suffix);
		// SAFETY: NcName cannot contain a colon; Name is NcName with colons,
		// so we can concat two NcNames to a Name.
		unsafe { Name::from_string_unchecked(s) }
	}

	/// Convert the [`NcName`] into a [`Name`].
	///
	/// This operation is O(1).
	///
	/// This operation is also available as implementation of the `Into`
	/// trait.
	pub fn into_name(self) -> Name {
		// SAFETY: NcName is a strict subset of Name
		unsafe { Name::from_auto_unchecked(self.0) }
	}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl AsRef<NameStr> for NcName {
	fn as_ref(&self) -> &NameStr {
		<Self as AsRef<NcNameStr>>::as_ref(self).as_ref()
	}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl Borrow<NameStr> for NcName {
	fn borrow(&self) -> &NameStr {
		<Self as Borrow<NcNameStr>>::borrow(self).borrow()
	}
}

impl NcNameStr {
	/// Create an owned copy of the string as [`NcName`].
	///
	/// This operation is also available as implementation of the `Into`
	/// trait.
	#[cfg(feature = "std")]
	#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
	pub fn to_ncname(&self) -> NcName {
		self.into()
	}

	/// Create an owned copy of the string as [`Name`].
	#[cfg(feature = "std")]
	#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
	pub fn to_name(&self) -> Name {
		self.to_ncname().into()
	}

	/// Access the string as [`NameStr`].
	///
	/// This operation is O(1), as Names are a strict superset of NcNames.
	pub fn as_namestr<'x>(&'x self) -> &'x NameStr {
		// SAFETY: NcName is a strict subset of Name
		unsafe { NameStr::from_str_unchecked(&self.0) }
	}

	/// Compose two [`NcName`] objects to one [`Name`], separating them with
	/// a colon.
	///
	/// As an [`NcName`] is always a valid [`Name`], the composition of the
	/// two with a `:` as separator is also a valid [`Name`].
	///
	/// This is the inverse of [`Name::split_name()`].
	///
	/// # Example
	///
	/// ```
	/// # use rxml_validation::NcName;
	/// # use std::convert::TryFrom;
	/// let prefix = NcName::try_from("xmlns").unwrap();
	/// let localname = NcName::try_from("stream").unwrap();
	/// assert_eq!(prefix.add_suffix(&localname), "xmlns:stream");
	/// ```
	#[cfg(feature = "std")]
	#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
	pub fn with_suffix(&self, suffix: &NcNameStr) -> Name {
		let mut s = String::with_capacity(self.len() + 1 + suffix.len());
		s.push_str(self);
		s.push_str(":");
		s.push_str(suffix);
		// SAFETY: NcName cannot contain a colon; Name is NcName with colons,
		// so we can concat two NcNames to a Name.
		unsafe { Name::from_string_unchecked(s) }
	}
}

impl AsRef<NameStr> for NcNameStr {
	fn as_ref(&self) -> &NameStr {
		// SAFETY: NameStr rules are a superset of the NcNameStr rules.
		unsafe { NameStr::from_str_unchecked(&self.0) }
	}
}

impl Borrow<NameStr> for NcNameStr {
	fn borrow(&self) -> &NameStr {
		self.as_ref()
	}
}

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

	#[test]
	fn split_name_on_namestr_with_valid_name() {
		let nm: &NameStr = "foo:bar".try_into().unwrap();
		let (prefix, localname) = nm.split_name().unwrap();
		assert_eq!(prefix.unwrap(), "foo");
		assert_eq!(localname, "bar");
	}

	#[test]
	fn split_name_on_namestr_with_prefixless_name() {
		let nm: &NameStr = "bar".try_into().unwrap();
		let (prefix, localname) = nm.split_name().unwrap();
		assert_eq!(prefix, None);
		assert_eq!(localname, "bar");
	}

	#[test]
	fn split_name_on_namestr_rejects_localname_with_non_namestart_first_char() {
		let nm: &NameStr = "foo:-bar".try_into().unwrap();
		let result = nm.split_name();
		assert!(matches!(result.err().unwrap(), Error::InvalidLocalName,));
	}

	#[test]
	#[cfg(feature = "std")]
	fn split_name_on_name_with_valid_name() {
		let nm: Name = "foo:bar".try_into().unwrap();
		let (prefix, localname) = nm.split_name().unwrap();
		assert_eq!(prefix.unwrap(), "foo");
		assert_eq!(localname, "bar");
	}

	#[test]
	#[cfg(feature = "std")]
	fn split_name_on_name_with_prefixless_name() {
		let nm: Name = "bar".try_into().unwrap();
		let (prefix, localname) = nm.split_name().unwrap();
		assert_eq!(prefix, None);
		assert_eq!(localname, "bar");
	}

	#[test]
	#[cfg(feature = "std")]
	fn split_name_on_name_rejects_localname_with_non_namestart_first_char() {
		let nm: Name = "foo:-bar".try_into().unwrap();
		let result = nm.split_name();
		assert!(matches!(result.err().unwrap(), Error::InvalidLocalName,));
	}

	#[test]
	fn split_namestr_on_name_with_valid_name() {
		let nm: &NameStr = "foo:bar".try_into().unwrap();
		let (prefix, localname) = nm.split_name().unwrap();
		assert_eq!(prefix.unwrap(), "foo");
		assert_eq!(localname, "bar");
	}

	#[test]
	fn split_namestr_on_name_with_prefixless_name() {
		let nm: &NameStr = "bar".try_into().unwrap();
		let (prefix, localname) = nm.split_name().unwrap();
		assert_eq!(prefix, None);
		assert_eq!(localname, "bar");
	}

	#[test]
	fn split_namestr_on_name_rejects_localname_with_non_namestart_first_char() {
		let nm: &NameStr = "foo:-bar".try_into().unwrap();
		let result = nm.split_name();
		assert!(matches!(result.err().unwrap(), Error::InvalidLocalName,));
	}

	#[test]
	#[should_panic(expected = "slice is not a valid NameStr")]
	fn namestr_slice_panics_on_non_name_start() {
		let x: &NameStr = "foo-bar".try_into().unwrap();
		let _: &NameStr = &x[3..];
	}

	#[test]
	#[should_panic(expected = "slice is not a valid NameStr")]
	#[cfg(feature = "std")]
	fn name_slice_panics_on_non_name_start() {
		let x: Name = "foo-bar".try_into().unwrap();
		let _: &NameStr = &x[3..];
	}

	#[test]
	#[should_panic(expected = "split string is not a valid Name")]
	#[cfg(feature = "std")]
	fn name_split_off_refuses_empty_lhs() {
		let mut x: Name = "foobar".try_into().unwrap();
		x.split_off(0);
	}

	#[test]
	#[should_panic(expected = "split string is not a valid Name")]
	#[cfg(feature = "std")]
	fn name_split_off_refuses_empty_rhs() {
		let mut x: Name = "foobar".try_into().unwrap();
		x.split_off(6);
	}

	#[test]
	#[should_panic(expected = "slice is not a valid NcNameStr")]
	fn ncnamestr_slice_panics_on_non_name_start() {
		let x: &NcNameStr = "foo-bar".try_into().unwrap();
		let _: &NcNameStr = &x[3..];
	}

	#[test]
	#[should_panic(expected = "slice is not a valid NcNameStr")]
	#[cfg(feature = "std")]
	fn ncname_slice_panics_on_non_name_start() {
		let x: NcName = "foo-bar".try_into().unwrap();
		let _: &NcNameStr = &x[3..];
	}

	#[test]
	fn ncname_refuses_empty_slice() {
		match <&str as TryInto<&NcNameStr>>::try_into("") {
			Err(_) => (),
			other => panic!("unexpected result: {:?}", other),
		}
	}
}