fyi_msg 2.4.0

Simple ANSI-formatted, prefixed messages for console printing.
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
/*!
# FYI Msg: Messages!
*/

pub(super) mod kind;

#[expect(unused_imports, reason = "For docs.")]
use crate::MsgKind;

#[cfg(feature = "progress")] use crate::BeforeAfter;
use fyi_ansi::{
	ansi,
	csi,
	dim,
};
use kind::IntoMsgPrefix;
use std::{
	borrow::{
		Borrow,
		Cow,
	},
	cmp::Ordering,
	fmt,
	hash,
	io,
	num::NonZeroUsize,
	ops::Range,
};



#[cfg(feature = "timestamps")]
/// # Helper: `Toc` Setup.
macro_rules! toc {
	($p_end:expr, $m_end:expr) => (
		$crate::msg::Toc([
			0,      // Indentation.
			0,      // Timestamp.
			0,      // Prefix.
			$p_end, // Message.
			$m_end, // Suffix.
			$m_end, // Newline.
			$m_end, // Total Length.
		])
	);
	($p_end:expr, $m_end:expr, true) => (
		$crate::msg::Toc([
			0,          // Indentation.
			0,          // Timestamp.
			0,          // Prefix.
			$p_end,     // Message.
			$m_end,     // Suffix.
			$m_end,     // Newline.
			$m_end + 1, // Total Length.
		])
	);
}

#[cfg(not(feature = "timestamps"))]
/// # Helper: `Toc` Setup.
macro_rules! toc {
	($p_end:expr, $m_end:expr) => (
		$crate::msg::Toc([
			0,      // Indentation.
			0,      // Prefix.
			$p_end, // Message.
			$m_end, // Suffix.
			$m_end, // Newline.
			$m_end, // Total Length.
		])
	);
	($p_end:expr, $m_end:expr, true) => (
		$crate::msg::Toc([
			0,          // Indentation.
			0,          // Prefix.
			$p_end,     // Message.
			$m_end,     // Suffix.
			$m_end,     // Newline.
			$m_end + 1, // Total Length.
		])
	);
}
use toc; // kind.rs needs this.



#[derive(Debug, Default, Clone)]
/// # Message.
///
/// The `Msg` struct provides a partitioned, contiguous byte source to hold
/// arbitrary messages of the "Error: Oh no!" variety. They can be modified
/// efficiently in place (per-part) and printed to `STDOUT` with [`Msg::print`]
/// or `STDERR` with [`Msg::eprint`] (or via [`Display`](fmt::Display)).
///
/// There are two crate feature gates that augment this struct (at the expense
/// of additional dependencies):
///
/// * `fitted` adds [`Msg::fitted`] for obtaining a slice trimmed to a specific display width.
/// * `timestamps` adds [`Msg::set_timestamp`]/[`Msg::with_timestamp`] for inserting a local datetime value before the prefix.
///
/// Everything else comes stock!
///
/// ## Examples
///
/// ```
/// use fyi_msg::{Msg, MsgKind};
///
/// Msg::new(MsgKind::Success, "You did it!")
///     .with_newline(true)
///     .print();
/// ```
///
/// There are a bunch of built-in prefix types ([`MsgKind`]), each of which
/// (except [`MsgKind::None`] and [`MsgKind::Confirm`]) has a corresponding
/// "quick" method on this struct to save the effort of chaining [`Msg::new`]
/// and [`Msg::with_newline`].
///
/// ```
/// use fyi_msg::{Msg, MsgKind};
///
/// // Same as before, but more concise.
/// Msg::success("You did it!").print();
/// ```
///
/// Confirmations have a convenience _macro_ instead, [`confirm`](crate::confirm),
/// that handles all the setup and prompting, returning a simple `bool`
/// indicating the yes/noness of the user response.
///
/// Take a look at `examples/msg.rs` for a breakdown of the various options.
///
/// ## Conversion
///
/// `Msg` objects are essentially just fancy strings.
///
/// You can borrow the the result with [`Msg::as_str`]/[`Msg::as_bytes`] or
/// steal it with [`Msg::into_string`]/[`Msg::into_bytes`].
pub struct Msg {
	/// # Actual Message.
	inner: String,

	/// # Table of Contents.
	toc: Toc,
}

impl AsRef<[u8]> for Msg {
	#[inline]
	fn as_ref(&self) -> &[u8] { self.as_bytes() }
}

impl AsRef<str> for Msg {
	#[inline]
	fn as_ref(&self) -> &str { self.as_str() }
}

impl Borrow<str> for Msg {
	#[inline]
	fn borrow(&self) -> &str { self.as_str() }
}

impl fmt::Display for Msg {
	#[inline]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		<str as fmt::Display>::fmt(self.as_str(), f)
	}
}

impl Eq for Msg {}

/// # Helper: From Stringlike.
macro_rules! from_stringlike {
	($ty:ty, $op:ident) => (
		impl From<$ty> for Msg {
			#[inline]
			fn from(src: $ty) -> Self { Self::from(src.$op()) }
		}
	);
}
from_stringlike!(&str, to_owned);
from_stringlike!(&String, clone);
from_stringlike!(Cow<'_, str>, into_owned);

impl From<String> for Msg {
	#[inline]
	fn from(src: String) -> Self {
		let m_end = src.len();
		Self {
			inner: src,
			toc: toc!(0, m_end),
		}
	}
}

impl From<Msg> for String {
	#[inline]
	fn from(src: Msg) -> Self { src.into_string() }
}

impl hash::Hash for Msg {
	#[inline]
	fn hash<H: hash::Hasher>(&self, state: &mut H) { self.inner.hash(state); }
}

impl PartialEq for Msg {
	#[inline]
	fn eq(&self, other: &Self) -> bool { self.inner == other.inner }
}

impl PartialEq<str> for Msg {
	#[inline]
	fn eq(&self, other: &str) -> bool { self.as_str() == other }
}
impl PartialEq<Msg> for str {
	#[inline]
	fn eq(&self, other: &Msg) -> bool { <Msg as PartialEq<Self>>::eq(other, self) }
}

impl PartialEq<[u8]> for Msg {
	#[inline]
	fn eq(&self, other: &[u8]) -> bool { self.as_bytes() == other }
}
impl PartialEq<Msg> for [u8] {
	#[inline]
	fn eq(&self, other: &Msg) -> bool { <Msg as PartialEq<Self>>::eq(other, self) }
}

/// # Helper: Reciprocal `PartialEq`.
macro_rules! eq {
	($parent:ty: $($ty:ty),+) => ($(
		impl PartialEq<$ty> for Msg {
			#[inline]
			fn eq(&self, other: &$ty) -> bool { <Self as PartialEq<$parent>>::eq(self, other) }
		}
		impl PartialEq<Msg> for $ty {
			#[inline]
			fn eq(&self, other: &Msg) -> bool { <Msg as PartialEq<$parent>>::eq(other, self) }
		}
	)+);
}
eq!(str:  &str,  &String,  String,  &Cow<'_, str>,  Cow<'_, str>,  &Box<str>,  Box<str>);
eq!([u8]: &[u8], &Vec<u8>, Vec<u8>, &Cow<'_, [u8]>, Cow<'_, [u8]>, &Box<[u8]>, Box<[u8]>);

impl Ord for Msg {
	#[inline]
	fn cmp(&self, other: &Self) -> Ordering { self.inner.cmp(&other.inner) }
}

impl PartialOrd for Msg {
	#[inline]
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}

/// ## Construction.
impl Msg {
	#[must_use]
	#[expect(clippy::needless_pass_by_value, reason = "Trait covers owned and referenced types.")]
	/// # New Message.
	///
	/// This creates a new [`Msg`] with prefix and message parts.
	///
	/// The prefix can be a built-in [`MsgKind`], or something custom, with or
	/// without ANSI formatting.
	///
	/// Custom prefixes can be any of the usual string types — `&str`,
	/// `String`/`&String`, or `Cow<str>`/`&Cow<str>` — optionally tupled with
	/// an [`AnsiColor`](crate::AnsiColor) for sex appeal.
	///
	/// Custom prefixes should _not_ include the `": "` separator, as that is
	/// appended automatically to all non-empty values.
	///
	/// To create a message without a prefix, just pass the content to
	/// [`Msg::from`] instead.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::{
	///     AnsiColor,
	///     Msg,
	///     MsgKind,
	/// };
	///
	/// // Built-in prefix. Easy!
	/// assert_eq!(
	///     Msg::new(MsgKind::Info, "This is a message."),
	///     "\x1b[1;95mInfo:\x1b[0m This is a message.",
	/// );
	///
	/// // Custom prefix, no formatting.
	/// assert_eq!(
	///     Msg::new("Best Picture", "C.H.U.D."),
	///     "Best Picture: C.H.U.D.",
	/// );
	///
	/// // Custom prefix, red and bold.
	/// assert_eq!(
	///     Msg::new(("Crap", AnsiColor::Red), "Something broke!"),
	///     "\x1b[1;31mCrap:\x1b[0m Something broke!"
	/// );
	///
	/// // Same as above, but with the color as a `u8`.
	/// assert_eq!(
	///     Msg::new(("Crap", 1), "Something broke!"),
	///     "\x1b[1;31mCrap:\x1b[0m Something broke!"
	/// );
	///
	/// // If for some reason you pass an empty string, the prefix will be
	/// // omitted.
	/// assert_eq!(
	///     Msg::new(("", AnsiColor::Misc199), "Plain Jane."),
	///     "Plain Jane.",
	/// );
	/// ```
	pub fn new<P, S>(prefix: P, msg: S) -> Self
	where
		P: IntoMsgPrefix,
		S: AsRef<str>,
	{
		let msg = msg.as_ref();

		let p_end = prefix.prefix_len();
		let mut inner = String::with_capacity(p_end + msg.len());
		prefix.prefix_push(&mut inner);
		inner.push_str(msg);
		let m_end = inner.len();

		// Done!
		Self {
			inner,
			toc: toc!(p_end, m_end),
		}
	}
}

/// ## Getters.
impl Msg {
	#[inline]
	#[must_use]
	/// # As Byte Slice.
	///
	/// Return the formatted message as a byte slice.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// assert_eq!(
	///     Msg::from("Hello world").as_bytes(),
	///     b"Hello world",
	/// );
	/// ```
	pub const fn as_bytes(&self) -> &[u8] { self.inner.as_bytes() }

	#[inline]
	#[must_use]
	/// # As String Slice.
	///
	/// Return the formatted message as a string slice.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// assert_eq!(
	///     Msg::from("Hello world").as_str(),
	///     "Hello world",
	/// );
	/// ```
	pub const fn as_str(&self) -> &str { self.inner.as_str() }

	#[cfg(feature = "fitted")]
	#[cfg_attr(docsrs, doc(cfg(feature = "fitted")))]
	#[must_use]
	#[inline]
	/// # Fit to Width.
	///
	/// Return the message as a string with its lines capped to the given
	/// display `width`.
	///
	/// This is essentially just a convenience wrapper around [`fit_to_width`](crate::fit_to_width);
	/// refer to that method documentation for more details.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::{AnsiColor, Msg};
	///
	/// let msg = Msg::new(("Name", AnsiColor::Blue), "Björk")
	///     .with_suffix(" (the Great)")
	///     .with_newline(true); // Trailing line breaks are fine.
	///
	/// // As it is:
	/// assert_eq!(
	///     msg.as_str(),
	///     "\x1b[1;34mName:\x1b[0m Björk (the Great)\n",
	/// );
	///
	/// // Fitting to 20 columns loses some of the suffix, but the trailing
	/// // line break is preserved.
	/// assert_eq!(
	///     msg.fitted(20),
	///     "\x1b[1;34mName:\x1b[0m Björk (the Gre\n",
	/// );
	///
	/// // Fitting to 10 columns drops the suffix entirely, loses a bit of
	/// // the message part, but the line break hangs on.
	/// // the trailing line break.
	/// assert_eq!(
	///     msg.fitted(10),
	///     "\x1b[1;34mName:\x1b[0m Björ\n",
	/// );
	///
	/// // Fitting to 4 columns kills most everything, but the ANSI reset and
	/// // line break are preserved.
	/// assert_eq!(
	///     msg.fitted(4),
	///     "\x1b[1;34mName\x1b[0m\n",
	/// );
	/// ```
	pub fn fitted(&self, width: usize) -> Cow<'_, str> {
		crate::fit_to_width(self.as_str(), width)
	}

	#[inline]
	#[must_use]
	/// # Into Bytes.
	///
	/// Consume self, returning an owned byte vector.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// assert_eq!(
	///     Msg::from("Hello world").into_bytes(),
	///     b"Hello world",
	/// );
	/// ```
	pub fn into_bytes(self) -> Vec<u8> { self.inner.into_bytes() }

	#[inline]
	#[must_use]
	/// # Into String.
	///
	/// Consume self, returning the inner string.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// assert_eq!(
	///     Msg::from("Hello world").into_string(),
	///     "Hello world",
	/// );
	/// ```
	pub fn into_string(self) -> String { self.inner }

	#[inline]
	#[must_use]
	/// # Is Empty?
	///
	/// Returns `true` if the message is empty.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// // One way to get an empty message.
	/// assert!(Msg::from("").is_empty());
	/// ```
	pub const fn is_empty(&self) -> bool { self.inner.is_empty() }

	#[inline]
	#[must_use]
	/// # Message Length.
	///
	/// Return the total number of bytes in the formatted message.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// assert_eq!(Msg::from("ABC").len(), 3);
	/// assert_eq!(
	///     Msg::done("Goodbye.").len(),
	///     26,
	/// ); // Don't forget about ANSI…
	/// ```
	pub const fn len(&self) -> usize { self.inner.len() }
}

/// ## Setters.
impl Msg {
	/// # Set Indentation.
	///
	/// (Re)set the message's indentation level to `tabs` "tabs" (four spaces
	/// each), up to a maximum depth of eight (thirty-two spaces total).
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::from("Hello world.");
	///
	/// msg.set_indent(1);
	/// assert_eq!(msg, "    Hello world.");
	///
	/// msg.set_indent(2);
	/// assert_eq!(msg, "        Hello world.");
	///
	/// msg.set_indent(3);
	/// assert_eq!(msg, "            Hello world.");
	///
	/// // …
	///
	/// msg.set_indent(7);
	/// assert_eq!(msg, "                            Hello world.");
	///
	/// msg.set_indent(8);
	/// assert_eq!(msg, "                                Hello world.");
	///
	/// msg.set_indent(9);
	/// assert_eq!(msg, "                                Hello world."); // Same as 8.
	///
	/// // …
	///
	/// msg.set_indent(u8::MAX);
	/// assert_eq!(msg, "                                Hello world."); // Same as 8.
	///
	/// // Back to zero!
	/// msg.set_indent(0);
	/// assert_eq!(msg, "Hello world.");
	/// ```
	pub fn set_indent(&mut self, tabs: u8) {
		/// # Thirty-Two Spaces.
		///
		/// For indentation, alignment, etc.
		static SPACES: &str = "                                ";

		self.replace_part(
			TocId::Indent,
			SPACES.get(..usize::from(tabs) * 4).unwrap_or(SPACES),
		);
	}

	/// # Set Message Content.
	///
	/// (Re)set the actual message part of the message.
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::from("Hello");
	/// assert_eq!(msg, "Hello");
	///
	/// msg.set_msg("Goodbye");
	/// assert_eq!(msg, "Goodbye");
	/// ```
	pub fn set_msg<S: AsRef<str>>(&mut self, msg: S) {
		self.replace_part(TocId::Message, msg.as_ref());
	}

	/// # Set Trailing Linebreak.
	///
	/// Add/remove the message's trailing line break.
	///
	/// ## Examples
	///
	/// Messages created with [`Msg::from`], [`Msg::new`], and
	/// [`MsgKind::into_msg`] have no trailing line break by default:
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::from("Hello World!");
	/// assert_eq!(msg, "Hello World!");
	///
	/// msg.set_newline(true); // Add it.
	/// assert_eq!(msg, "Hello World!\n");
	/// ```
	///
	/// Messages created with the kind-specific helper methods, however, _do_
	/// have a line break by default:
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::info("Hello World!");
	/// assert_eq!(msg, "\x1b[1;95mInfo:\x1b[0m Hello World!\n");
	///
	/// msg.set_newline(false); // Remove it.
	/// assert_eq!(msg, "\x1b[1;95mInfo:\x1b[0m Hello World!");
	/// ```
	pub fn set_newline(&mut self, enabled: bool) {
		let out = if enabled { "\n" } else { "" };
		self.replace_part(TocId::Newline, out);
	}

	#[expect(clippy::needless_pass_by_value, reason = "Impl is on referenced and owned types.")]
	/// # Set Prefix.
	///
	/// (Re/un)set the message prefix.
	///
	/// As with [`Msg::new`], prefixes can be a built-in [`MsgKind`] or custom
	/// string, with or without formatting.
	///
	/// To remove the prefix entirely, pass [`MsgKind::None`] or `""`.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::{
	///     AnsiColor,
	///     Msg,
	///     MsgKind,
	/// };
	///
	/// let mut msg = Msg::new(MsgKind::Error, "Uh oh!");
	/// assert_eq!(
	///     msg,
	///     "\x1b[1;91mError:\x1b[0m Uh oh!"
	/// );
	///
	/// // Downgrade to warning.
	/// msg.set_prefix(MsgKind::Warning);
	/// assert_eq!(
	///     msg,
	///     "\x1b[1;93mWarning:\x1b[0m Uh oh!"
	/// );
	///
	/// // Escalate it to profanity.
	/// msg.set_prefix(("Shit", AnsiColor::Misc199));
	/// assert_eq!(
	///     msg,
	///     "\x1b[1;38;5;199mShit:\x1b[0m Uh oh!"
	/// );
	///
	/// // Remove the prefix altogether.
	/// msg.set_prefix(MsgKind::None);
	/// assert_eq!(msg, "Uh oh!");
	/// ```
	pub fn set_prefix<P: IntoMsgPrefix>(&mut self, prefix: P) {
		self.replace_part(TocId::Prefix, &prefix.prefix_str());
	}

	/// # Set Suffix.
	///
	/// (Re)set the message suffix.
	///
	/// Unlike prefixes, no automatic formatting is applied to suffixes. For
	/// example, if you want a space separating the message content and suffix,
	/// the suffix should start with a leading space.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::from("Checked!");
	/// msg.set_suffix(" ✓");
	///
	/// assert_eq!(
	///     msg,
	///     "Checked! ✓",
	/// );
	pub fn set_suffix<S: AsRef<str>>(&mut self, suffix: S) {
		self.replace_part(TocId::Suffix, suffix.as_ref());
	}

	#[cfg(feature = "timestamps")]
	#[cfg_attr(docsrs, doc(cfg(feature = "timestamps")))]
	/// # Set Timestamp.
	///
	/// Add/remove a timestamp to/from the beginning the of the message.
	///
	/// ## Examples.
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::from("Parsed log.");
	/// msg.set_timestamp(true); // [YYYY-MM-DD hh:mm:ss] Parsed log.
	/// ```
	pub fn set_timestamp(&mut self, enabled: bool) {
		if enabled {
			let now = utc2k::Local2k::now().formatted();
			let mut out = String::with_capacity(43);
			out.push_str(concat!(csi!(dim), "[", csi!(reset, blue)));
			out.push_str(now.as_str());
			out.push_str(concat!(ansi!((reset, dim) "]"), " "));
			self.replace_part(TocId::Timestamp, &out);
		}
		else { self.replace_part(TocId::Timestamp, ""); }
	}

	/// # Strip ANSI Formatting.
	///
	/// Remove colors, bold, etc. from the message.
	///
	/// This is best called last, as changes made after this might reintroduce
	/// fancy formatting.
	///
	/// See also [`Msg::without_ansi`].
	///
	/// Returns `true` if the content was modified.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::info("5,000 matching files were found.");
	/// assert!(msg.strip_ansi());
	///
	/// // Now it reads:
	/// assert_eq!(
	///     msg,
	///     "Info: 5,000 matching files were found.\n",
	/// );
	/// ```
	pub fn strip_ansi(&mut self) -> bool {
		// Iterate through all the parts (except indent and newline), replacing
		// the content as needed.
		let mut changed = false;
		for id in TocId::ANSI_PARTS {
			// The original part location and size.
			let old_rng = self.toc.part_rng(id);
			let old_len = old_rng.len();

			// Remove ANSI in-place across the part range, but wait to
			// reconcile the table of contents until the end.
			let mut removed = 0;
			let mut start = old_rng.start;
			let mut stop = old_rng.end;
			while let Some(mut ansi_rng) = self.inner.get(start..stop).and_then(crate::ansi::next_ansi) {
				// Make the range absolute.
				ansi_rng.start += start;
				ansi_rng.end += start;

				// Update the counters and remove the chunk from the buffer.
				let ansi_len = ansi_rng.len();
				removed += ansi_len;    // We removed the whole range.
				start = ansi_rng.start; // Pick up from here next time around.
				stop -= ansi_len;       // But stop earlier, since we removed shit.
				self.inner.replace_range(ansi_rng, "");
			}

			// Update the table of contents, if necessary.
			if removed != 0 {
				self.toc.resize_part(id, old_len - removed);
				changed = true;
			}
		}

		changed
	}
}

/// ## Builder Setters.
impl Msg {
	#[inline]
	#[must_use]
	/// # With/Without Indentation.
	///
	/// (Re)set the message's indentation level to `tabs` "tabs" (four spaces
	/// each), up to a maximum depth of eight (thirty-two spaces total).
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let msg = Msg::from("Hello world.").with_indent(1);
	/// assert_eq!(msg, "    Hello world.");
	///
	/// let msg = Msg::from("Hello world.").with_indent(2);
	/// assert_eq!(msg, "        Hello world.");
	///
	/// let msg = Msg::from("Hello world.").with_indent(3);
	/// assert_eq!(msg, "            Hello world.");
	///
	/// // …
	///
	/// let msg = Msg::from("Hello world.").with_indent(7);
	/// assert_eq!(msg, "                            Hello world.");
	///
	/// let msg = Msg::from("Hello world.").with_indent(8);
	/// assert_eq!(msg, "                                Hello world.");
	///
	/// let msg = Msg::from("Hello world.").with_indent(9);
	/// assert_eq!(msg, "                                Hello world."); // Same as 8.
	///
	/// // …
	///
	/// let msg = Msg::from("Hello world.").with_indent(u8::MAX);
	/// assert_eq!(msg, "                                Hello world."); // Same as 8.
	/// ```
	pub fn with_indent(mut self, tabs: u8) -> Self {
		self.set_indent(tabs);
		self
	}

	#[inline]
	#[must_use]
	/// # With Message Content.
	///
	/// In most cases where the message content needs to change, [`Msg::set_msg`]
	/// probably makes more sense, but everything else gets a builder method,
	/// so why not?
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let msg = Msg::from("Hello")
	///     .with_msg("Goodbye");
	/// assert_eq!(msg, "Goodbye");
	/// ```
	pub fn with_msg<S: AsRef<str>>(mut self, msg: S) -> Self {
		self.set_msg(msg);
		self
	}

	#[inline]
	#[must_use]
	/// # With/Without Trailing Linebreak.
	///
	/// Add/remove the message's trailing line break.
	///
	/// ## Examples
	///
	/// Messages created with [`Msg::from`], [`Msg::new`], and
	/// [`MsgKind::into_msg`] have no trailing line break by default:
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::from("Hello World!");
	/// assert_eq!(
	///     msg,
	///     "Hello World!",
	/// );
	///
	/// assert_eq!(
	///     msg.with_newline(true), // Add line break.
	///     "Hello World!\n",
	/// );
	/// ```
	///
	/// Messages created with the built-in helper methods, however, do:
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let mut msg = Msg::info("Hello World!");
	/// assert_eq!(
	///     msg,
	///     "\x1b[1;95mInfo:\x1b[0m Hello World!\n",
	/// );
	///
	/// assert_eq!(
	///     msg.with_newline(false), // Remove line break.
	///     "\x1b[1;95mInfo:\x1b[0m Hello World!",
	/// );
	/// ```
	pub fn with_newline(mut self, enabled: bool) -> Self {
		self.set_newline(enabled);
		self
	}

	#[inline]
	#[must_use]
	/// # With Prefix.
	///
	/// (Re/un)set the message prefix.
	///
	/// As with [`Msg::new`], prefixes can be a built-in [`MsgKind`] or custom
	/// string, with or without formatting.
	///
	/// To remove the prefix entirely, pass [`MsgKind::None`] or `""`.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::{Msg, MsgKind};
	///
	/// // A built-in.
	/// assert_eq!(
	///     Msg::from("Uh oh!").with_prefix(MsgKind::Error),
	///     "\x1b[1;91mError:\x1b[0m Uh oh!",
	/// );
	///
	/// // A custom and plain prefix.
	/// assert_eq!(
	///     Msg::from("Uh oh!").with_prefix("Nope"),
	///     "Nope: Uh oh!",
	/// );
	///
	/// // A custom and blue prefix.
	/// assert_eq!(
	///     Msg::from("Uh oh!").with_prefix(("Meh", 4)),
	///     "\x1b[1;34mMeh:\x1b[0m Uh oh!",
	/// );
	/// ```
	pub fn with_prefix<P: IntoMsgPrefix>(mut self, prefix: P) -> Self {
		self.set_prefix(prefix);
		self
	}

	#[inline]
	#[must_use]
	/// # With Suffix.
	///
	/// (Re)set the message suffix.
	///
	/// Unlike prefixes, no automatic formatting is applied to suffixes. For
	/// example, if you want a space separating the message content and suffix,
	/// the suffix should start with a leading space.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let msg = Msg::from("Checked!")
	///     .with_suffix(" ✓");
	///
	/// assert_eq!(
	///     msg,
	///     "Checked! ✓",
	/// );
	pub fn with_suffix<S: AsRef<str>>(mut self, suffix: S) -> Self {
		self.set_suffix(suffix);
		self
	}

	#[cfg(feature = "timestamps")]
	#[cfg_attr(docsrs, doc(cfg(feature = "timestamps")))]
	#[inline]
	#[must_use]
	/// # With/Without Timestamp.
	///
	/// Add/remove a timestamp to/from the beginning the of the message.
	///
	/// ## Examples.
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let msg = Msg::from("Parsed log.")
	///     .with_timestamp(true); // [YYYY-MM-DD hh:mm:ss] Parsed log.
	/// ```
	pub fn with_timestamp(mut self, enabled: bool) -> Self {
		self.set_timestamp(enabled);
		self
	}

	#[must_use]
	/// # Without ANSI Formatting.
	///
	/// Remove colors, bold, etc. from the message.
	///
	/// This is best called last, as changes made after this might reintroduce
	/// fancy formatting.
	///
	/// For unchained usage, see [`Msg::strip_ansi`].
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// assert_eq!(
	///     Msg::info("5,000 matching files were found.").without_ansi(),
	///     "Info: 5,000 matching files were found.\n",
	/// );
	/// ```
	pub fn without_ansi(mut self) -> Self {
		self.strip_ansi();
		self
	}
}

/// ## Printing.
impl Msg {
	#[inline]
	/// # Print to `STDOUT`.
	///
	/// This is a convenience method for printing a message to `STDOUT` without
	/// having to go through the standard library's [`print`] macro.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let msg = Msg::info("Hello World!");
	///
	/// // You've got two choices to print.
	/// print!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
	/// msg.print();     // \x1b[1;95mInfo:\x1b[0m Hello World!\n
	/// // This line break is embedded in the message itself.   ^
	///
	/// // As such, you probably don't want to do this:
	/// println!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n\n
	///
	/// // Of course, messages don't _have to_ embed the break:
	/// let msg = Msg::info("Hello World!").with_newline(false);
	/// println!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
	/// ```
	pub fn print(&self) {
		use io::Write;

		let mut handle = io::stdout().lock();
		let _res = handle.write_all(self.as_bytes()).and_then(|()| handle.flush());
	}

	#[inline]
	/// # Print to `STDERR`.
	///
	/// This is a convenience method for printing a message to `STDERR` without
	/// having to go through the standard library's [`eprint`] macro.
	///
	/// ## Examples
	///
	/// ```
	/// use fyi_msg::Msg;
	///
	/// let msg = Msg::info("Hello World!");
	///
	/// // You've got two choices to print.
	/// eprint!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
	/// msg.eprint();     // \x1b[1;95mInfo:\x1b[0m Hello World!\n
	/// // This line break is embedded in the message itself.   ^
	///
	/// // As such, you probably don't want to do this:
	/// eprintln!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n\n
	///
	/// // Of course, messages don't _have to_ embed the break:
	/// let msg = Msg::info("Hello World!").with_newline(false);
	/// eprintln!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
	/// ```
	pub fn eprint(&self) {
		use io::Write;

		let mut handle = io::stderr().lock();
		let _res = handle.write_all(self.as_bytes()).and_then(|()| handle.flush());
	}

	#[must_use]
	#[inline]
	/// # Prompt.
	///
	/// This produces a simple y/N input prompt, requiring the user type "Y" or
	/// "N" to proceed. Positive values return `true`, negative values return
	/// `false`. The default (if the user just hits `<ENTER>`) is "N".
	///
	/// Note: the prompt normalizes the suffix and newline parts for display.
	/// If your message contains these parts, they will be ignored by the
	/// prompt action, but will be retained in the original struct should you
	/// wish to use it in some other manner later in your code.
	///
	/// Every example in the docs shows this in combination with the built-in
	/// [`MsgKind::Confirm`] prefix, but this can be called on any [`Msg`]
	/// object.
	///
	/// ## Example
	///
	/// ```no_run
	/// use fyi_msg::{confirm, Msg, MsgKind};
	///
	/// // The manual way:
	/// if Msg::new(MsgKind::Confirm, "Do you like chickens?").prompt() {
	///     println!("That's great! They like you too!");
	/// }
	///
	/// // The macro way:
	/// if confirm!("Do you like chickens?") {
	///     println!("That's great! They like you too!");
	/// }
	/// ```
	pub fn prompt(&self) -> bool { self.prompt_with_default(false) }

	#[must_use]
	#[inline]
	/// # Prompt (w/ Default).
	///
	/// Same as [`Msg::prompt`], but with the option of specifying the default
	/// return value — `true` for Yes, `false` for No — that will be returned
	/// if the user just hits `<ENTER>`.
	pub fn prompt_with_default(&self, default: bool) -> bool {
		self.prompt__(default, false)
	}

	#[must_use]
	#[inline]
	/// # Prompt (`STDERR`).
	///
	/// Same as [`Msg::prompt`], but printed to `STDERR` instead of `STDOUT`.
	pub fn eprompt(&self) -> bool { self.eprompt_with_default(false) }

	#[must_use]
	#[inline]
	/// # Prompt (w/ Default, `STDERR`).
	///
	/// Same as [`Msg::prompt_with_default`], but printed to `STDERR` instead of
	/// `STDOUT`.
	pub fn eprompt_with_default(&self, default: bool) -> bool {
		self.prompt__(default, true)
	}

	/// # Internal Prompt Handling.
	///
	/// This prints the prompt, handling the desired default and output.
	fn prompt__(&self, default: bool, stderr: bool) -> bool {
		// Clone the message and append a little [y/N] instructional bit to the
		// end. This might not be necessary, but preserves the original message
		// in case it is needed again.
		let q = self.clone()
			.with_suffix(
				if default { concat!(" ", dim!("[", csi!(underline), "Y", csi!(!underline), "/n]"), " ") }
				else       { concat!(" ", dim!("[y/", csi!(underline), "N", csi!(!underline), "]"), " ") },
			)
			.with_newline(false);

		// Ask and collect input, looping until a valid response is typed.
		let mut result = String::new();
		loop {
			if stderr { q.eprint(); }
			else { q.print(); }

			if io::stdin().read_line(&mut result).is_ok() {
				result.make_ascii_lowercase();
				match result.trim() {
					"" => return default,
					"n" | "no" => return false,
					"y" | "yes" => return true,
					_ => {}
				}
			}

			// Print an error and do it all over again.
			result.truncate(0);
			let err = Self::error(concat!(
				"Invalid input; enter ",
				ansi!((light_red) "N"),
				" or ",
				ansi!((light_green) "Y"),
				".",
			));
			if stderr { err.eprint(); }
			else { err.print(); }
		}
	}
}

#[cfg(feature = "progress")]
/// ## Miscellaneous.
impl Msg {
	#[cfg_attr(docsrs, doc(cfg(feature = "progress")))]
	#[must_use]
	/// # Bytes Saved Suffix.
	///
	/// A lot of our own programs using this lib crunch data and report the
	/// savings as a suffix. This method just provides a quick way to generate
	/// that.
	pub fn with_bytes_saved(mut self, state: BeforeAfter) -> Self {
		use dactyl::{NicePercent, NiceU64};
		use fyi_ansi::csi;

		if let Some(saved) = state.less() {
			let saved = NiceU64::from(saved);
			let buf = state.less_percent().map_or_else(
				// Just the bytes.
				|| {
					let mut buf = String::with_capacity(24 + saved.len());
					buf.push_str(concat!(" ", csi!(dim), "(Saved "));
					buf.push_str(saved.as_str());
					buf.push_str(concat!(" bytes.)", csi!()));
					buf
				},
				// With percent.
				|per| {
					let per = NicePercent::from(per);
					let mut buf = String::with_capacity(26 + saved.len() + per.len());
					buf.push_str(concat!(" ", csi!(dim), "(Saved "));
					buf.push_str(saved.as_str());
					buf.push_str(" bytes, ");
					buf.push_str(per.as_str());
					buf.push_str(concat!(".)", csi!()));
					buf
				}
			);

			self.replace_part(TocId::Suffix, &buf);
		}
		else {
			self.replace_part(
				TocId::Suffix,
				concat!(" ", dim!("(No savings.)")),
			);
		}

		self
	}
}

/// # Internal.
impl Msg {
	/// # Replace Part.
	fn replace_part(&mut self, id: TocId, content: &str) {
		// Update the content.
		let rng = self.toc.part_rng(id);
		self.inner.replace_range(rng, content);

		// Update the table of contents.
		self.toc.resize_part(id, content.len());
	}
}



#[derive(Debug, Clone, Copy, Default)]
/// # Table of Contents.
struct Toc([usize; Self::SIZE]);

impl Toc {
	/// # Table of Contents Size.
	///
	/// The struct's inner array holds the starting positions for each part,
	/// plus an extra holding the exclusive end.
	///
	/// The specific number of parts varies by crate feature, but
	/// [`TocId::Newline`] is always last. Add one for the extra end "part",
	/// and one more to convert index to length.
	const SIZE: usize = TocId::Newline as usize + 2;

	/// # Part Length.
	const fn part_len(&self, id: TocId) -> Option<NonZeroUsize> {
		let start = self.0[id as usize];   // All TocIds are in range.
		let end = self.0[id as usize + 1]; // And so is +1.
		if let Some(len) = end.checked_sub(start) { NonZeroUsize::new(len) }
		else { None }
	}

	/// # Part Range.
	const fn part_rng(&self, id: TocId) -> Range<usize> {
		let start = self.0[id as usize];
		let end = self.0[id as usize + 1];
		start..end
	}

	/// # Resize Part(s).
	///
	/// Change the size of `part`, realigning the subsequent boundaries as
	/// needed.
	fn resize_part(&mut self, id: TocId, new_len: usize) {
		let old_len = self.part_len(id).map_or(0, NonZeroUsize::get);

		match old_len.cmp(&new_len) {
			// The new length is bigger; increase the remaining positions.
			Ordering::Less => {
				let diff = new_len - old_len;
				for v in self.0.iter_mut().skip(id as usize + 1) { *v += diff; }
			},
			// The new length is smaller; decrease the remaining positions.
			Ordering::Greater => {
				let diff = old_len - new_len;
				for v in self.0.iter_mut().skip(id as usize + 1) { *v -= diff; }
			},
			// No change.
			Ordering::Equal => {},
		}
	}
}



#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
/// # Table of Contents: Parts.
///
/// This enum holds the name/index of each [`Toc`] "chapter".
enum TocId {
	/// # Indentation.
	Indent = 0_u8,

	#[cfg(feature = "timestamps")]
	/// # Timestamps.
	Timestamp = 1_u8,

	#[cfg(feature = "timestamps")]
	/// # Prefix.
	Prefix = 2_u8,

	#[cfg(feature = "timestamps")]
	/// # Message.
	Message = 3_u8,

	#[cfg(feature = "timestamps")]
	/// # Suffix.
	Suffix = 4_u8,

	#[cfg(feature = "timestamps")]
	/// # Line Break.
	Newline = 5_u8,

	#[cfg(not(feature = "timestamps"))]
	/// # Prefix.
	Prefix = 1_u8,

	#[cfg(not(feature = "timestamps"))]
	/// # Message.
	Message = 2_u8,

	#[cfg(not(feature = "timestamps"))]
	/// # Suffix.
	Suffix = 3_u8,

	#[cfg(not(feature = "timestamps"))]
	/// # Line Break.
	Newline = 4_u8,
}

impl TocId {
	#[cfg(feature = "timestamps")]
	/// # Parts w/ ANSI.
	///
	/// These parts _might_ have formatting.
	const ANSI_PARTS: [Self; 4] = [
		Self::Timestamp, Self::Prefix, Self::Message, Self::Suffix,
	];

	#[cfg(not(feature = "timestamps"))]
	/// # Parts w/ ANSI.
	///
	/// These parts _might_ have formatting.
	const ANSI_PARTS: [Self; 3] = [Self::Prefix, Self::Message, Self::Suffix];
}



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

	#[test]
	fn t_strip_ansi() {
		// Create an ANSIfull message and make sure its various parts turn out
		// as expected.
		let mut msg = Msg::error("Oops: \x1b[2mDaisy\x1b[0m.")
			.with_suffix(" \x1b[1mYikes!\x1b[0m");
		assert_eq!(
			msg,
			"\x1b[1;91mError:\x1b[0m Oops: \x1b[2mDaisy\x1b[0m. \x1b[1mYikes!\x1b[0m\n",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Prefix)],
			"\x1b[1;91mError:\x1b[0m ",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Message)],
			"Oops: \x1b[2mDaisy\x1b[0m.",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Suffix)],
			" \x1b[1mYikes!\x1b[0m",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Newline)],
			"\n",
		);

		// Strip the ANSI and reverify.
		msg.strip_ansi();
		assert_eq!(
			msg,
			"Error: Oops: Daisy. Yikes!\n",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Prefix)],
			"Error: ",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Message)],
			"Oops: Daisy.",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Suffix)],
			" Yikes!",
		);
		assert_eq!(
			&msg.inner[msg.toc.part_rng(TocId::Newline)],
			"\n",
		);

		// Make sure double-stripping doesn't break anything.
		assert_eq!(
			msg.clone().without_ansi(),
			msg,
		);
	}
}