antifacet 0.1.0

crate for general utilities
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
//! Pretty printer implementation for Facet types

use {
	facet::Shape,
	siphasher::sip::SipHasher,
};

use crate::format::Indent;

use {
	alloc::collections::VecDeque,
	core::{
		fmt::{
			self,
			Write,
		},
		hash::{
			Hash,
			Hasher,
		},
		str,
	},
};

use {
	facet_core::{
		Def,
		Facet,
		FieldFlags,
		PointerType,
		PrimitiveType,
		SequenceType,
		StructKind,
		TextualType,
		Type,
		TypeNameOpts,
		UserType,
	},
	facet_reflect::Peek,
};

#[cfg(feature = "std")]
type Map<K, V> = std::collections::HashMap<K, V>;
#[cfg(not(feature = "std"))]
type Map<K, V> = alloc::collections::BTreeMap<K, V>;

#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct ValueIdOrd {
	pub(crate) shape: *const Shape,
	pub(crate) ptr: *const u8,
}

fn id(peek: Peek) -> ValueIdOrd {
	ValueIdOrd {
		shape: peek.shape(),
		ptr: peek.data().as_byte_ptr(),
	}
}

use super::color::ColorGenerator;

/// A formatter for pretty-printing Facet types
pub struct PrettyPrinter {
	indent_level: usize,
	indent: Indent,
	max_depth: Option<usize>,
	color_generator: ColorGenerator,
	use_colors: bool,
	list_u8_as_bytes: bool,
}

impl Default for PrettyPrinter {
	fn default() -> Self {
		Self {
			indent_level: 0,
			indent: Indent::default(),
			max_depth: None,
			color_generator: ColorGenerator::default(),
			use_colors: false,
			list_u8_as_bytes: true,
		}
	}
}

/// Stack state for iterative formatting
enum StackState {
	Start,
	ProcessStructField { field_index: usize },
	ProcessSeqItem { item_index: usize, kind: SeqKind },
	ProcessBytesItem { item_index: usize },
	ProcessMapEntry,
	Finish { newline: bool },
	OptionFinish,
}

enum SeqKind {
	List,
	Tuple,
}

/// Stack item for iterative traversal
struct StackItem<'mem, 'facet> {
	value: Peek<'mem, 'facet>,
	format_depth: usize,
	type_depth: usize,
	state: StackState,
}

impl PrettyPrinter {
	/// Create a new PrettyPrinter with default settings
	pub fn new() -> Self {
		Self::default()
	}

	/// Set the indentation size
	pub fn with_indent_size(
		mut self,
		size: Indent,
	) -> Self {
		self.indent = size;
		self
	}

	/// Set the indentation level
	pub fn with_indent_level(
		mut self,
		level: usize,
	) -> Self {
		self.indent_level = level;
		self
	}

	/// Set the maximum depth for recursive printing
	pub fn with_max_depth(
		mut self,
		depth: usize,
	) -> Self {
		self.max_depth = Some(depth);
		self
	}

	/// Set the color generator
	pub fn with_color_generator(
		mut self,
		generator: ColorGenerator,
	) -> Self {
		self.color_generator = generator;
		self
	}

	/// Enable or disable colors
	pub fn with_colors(
		mut self,
		use_colors: bool,
	) -> Self {
		self.use_colors = use_colors;
		self
	}

	/// Format a value to a string
	pub fn format<'a, T: Facet<'a>>(
		&self,
		value: &T,
	) -> String {
		let value = Peek::new(value);

		let mut output = String::new();
		self.format_peek_internal(value, &mut output, &mut Map::new())
			.expect("Formatting failed");

		output
	}

	/// Format a value to a formatter
	pub fn format_to<'a, T: Facet<'a>>(
		&self,
		value: &T,
		f: &mut fmt::Formatter<'_>,
	) -> fmt::Result {
		let value = Peek::new(value);
		self.format_peek_internal(value, f, &mut Map::new())
	}

	/// Format a value to a string
	pub fn format_peek(
		&self,
		value: Peek<'_, '_>,
	) -> String {
		let mut output = String::new();
		self.format_peek_internal(value, &mut output, &mut Map::new())
			.expect("Formatting failed");
		output
	}

	/// Format a value to a formatter
	pub fn format_peek_to(
		&self,
		value: Peek<'_, '_>,
		f: &mut fmt::Formatter<'_>,
	) -> fmt::Result {
		self.format_peek_internal(value, f, &mut Map::new())
	}

	/// Internal method to format a Peek value
	pub(crate) fn format_peek_internal(
		&self,
		initial_value: Peek<'_, '_>,
		f: &mut impl Write,
		visited: &mut Map<ValueIdOrd, usize>,
	) -> fmt::Result {
		// Create a queue for our stack items
		let mut stack = VecDeque::new();

		// Push the initial item
		stack.push_back(StackItem {
			value: initial_value,
			format_depth: self.indent_level,
			type_depth: 0,
			state: StackState::Start,
		});

		// Process items until the stack is empty
		while let Some(mut item) = stack.pop_back() {
			loop {
				if let Ok(ptr) = item.value.into_pointer() {
					if let Some(ptr) = ptr.borrow_inner() {
						item.value = ptr;
						continue;
					}
				}
				break;
			}

			match item.state {
				StackState::Start => {
					// Check if we've reached the maximum depth
					if let Some(max_depth) = self.max_depth {
						if item.format_depth > max_depth {
							self.write_punctuation(f, "[")?;
							write!(f, "...")?;
							continue;
						}
					}

					// Check for cycles - if we've seen this value before at a different type_depth
					if let Some(&ptr_type_depth) = visited.get(&id(item.value)) {
						// If the current type_depth is significantly deeper than when we first saw
						// this value, we have a true cycle, not just a transparent wrapper
						if item.type_depth > ptr_type_depth + 1 {
							self.write_type_name(f, item.value)?;
							self.write_punctuation(f, " { ")?;
							self.write_comment(
								f,
								&format!(
									"/* cycle detected at {} (first seen at type_depth {}) */",
									item.value.id(),
									ptr_type_depth
								),
							)?;
							self.write_punctuation(f, " }")?;
							continue;
						}
					} else {
						// First time seeing this value, record its type_depth
						visited.insert(id(item.value), item.type_depth);
					}

					// Process based on the peek variant and type
					match (item.value.shape().def, item.value.shape().ty) {
						// Handle scalar values
						(Def::Scalar, _) => {
							self.format_scalar(item.value, f)?;
						},
						// Handle option types
						(Def::Option(_def), _) => {
							let option = item.value.into_option().unwrap();

							// Print the Option name
							self.write_type_name(f, item.value)?;

							if option.is_some() {
								self.write_punctuation(f, "::Some(")?;

								if let Some(inner_value) = option.value() {
									// Create a custom stack item for Option::Some value
									let start_item = StackItem {
										value: inner_value,
										format_depth: item.format_depth,
										type_depth: item.type_depth + 1,
										state: StackState::Start,
									};

									// Add a special close parenthesis item
									let close_paren_item = StackItem {
										value: item.value,
										format_depth: item.format_depth,
										type_depth: item.type_depth,
										state: StackState::OptionFinish,
									};

									// Process the value first, then handle closing
									stack.push_back(close_paren_item);
									stack.push_back(start_item);
								}

								// Skip to next item
								continue;
							} else {
								self.write_punctuation(f, "::None")?;
							}
						},
						// Handle tuple struct types
						(_, Type::User(UserType::Struct(struct_def)))
							if struct_def.kind == StructKind::Tuple =>
						{
							self.write_type_name(f, item.value)?;
							item.state = StackState::ProcessSeqItem {
								item_index: 0,
								kind: SeqKind::Tuple,
							};
							self.write_punctuation(f, " (")?;
							writeln!(f)?;
							item.format_depth += 1;
							item.type_depth += 1;
							stack.push_back(item);
						},
						// Handle regular struct types
						(_, Type::User(UserType::Struct(_))) => {
							let struct_ = item.value.into_struct().unwrap();

							let newline = !(matches!(
								struct_.ty().kind,
								StructKind::Tuple | StructKind::TupleStruct
							) && struct_.ty().fields.len() == 1
								&& struct_.ty().fields[0].doc.is_empty());

							// Get struct doc comments from the shape
							let doc_comments = item.value.shape().doc;
							if !doc_comments.is_empty() {
								for line in doc_comments {
									self.write_comment(f, &format!("///{line}"))?;
									writeln!(f)?;
								}
							}

							match struct_.ty().kind {
								StructKind::Tuple => {},
								_ => self.write_type_name(f, item.value)?,
							}

							match struct_.ty().kind {
								StructKind::Unit => continue,
								StructKind::Struct => {
									self.write_punctuation(f, " {")?;
									if struct_.field_count() == 0 {
										self.write_punctuation(f, "}")?;
										continue;
									}
								},
								StructKind::Tuple | StructKind::TupleStruct => {
									self.write_punctuation(f, "(")?;
									if struct_.field_count() == 0 {
										self.write_punctuation(f, ")")?;
										continue;
									}
								},
							}
							if newline {
								writeln!(f)?;
							}

							// Push back the item with the next state to continue processing fields
							item.state = StackState::ProcessStructField { field_index: 0 };
							item.format_depth += newline as usize;
							stack.push_back(item);
						},
						(Def::List(_), _) => {
							self.handle_list(&mut stack, item, f)?;
							continue;
						},
						(_, Type::Sequence(SequenceType::Slice(_) | SequenceType::Array(_))) => {
							self.handle_list(&mut stack, item, f)?;
						},
						(_, Type::Pointer(PointerType::Reference(r))) => {
							let target = (r.target)();
							match target.ty {
								Type::Primitive(PrimitiveType::Textual(TextualType::Str)) => {
									// well we can print a string slice, that's no issue.
									// `Peek` implements `Display` which forwards to the
									// `Display` implementation of the underlying type.
									if self.use_colors {
										// yellow
										write!(f, "\x1b[33m{}\x1b[0m", item.value)?;
									} else {
										write!(f, "{}", item.value)?;
									}
								},
								_ => {
									write!(f, "unsupported reference type: {:?}", item.value)?;
								},
							}
						},
						(Def::Map(_), _) => {
							let _map = item.value.into_map().unwrap();
							// Print the map name
							self.write_type_name(f, item.value)?;
							self.write_punctuation(f, " {")?;
							writeln!(f)?;

							// Push back the item with the next state to continue processing map
							item.state = StackState::ProcessMapEntry;
							item.format_depth += 1;
							// When recursing into a map, always increment format_depth
							item.type_depth += 1; // Always increment type_depth for map operations
							stack.push_back(item);
						},
						(_, Type::User(UserType::Enum(_))) => {
							// When recursing into an enum, increment format_depth
							// Only increment type_depth if we're moving to a different address
							let enum_peek = item.value.into_enum().unwrap();

							// Get the active variant or handle error
							let variant = match enum_peek.active_variant() {
								Ok(v) => v,
								Err(_) => {
									// Print the enum name
									self.write_type_name(f, item.value)?;
									write!(f, " /* cannot determine variant */")?;
									continue;
								},
							};

							// Get enum and variant doc comments
							let doc_comments = item.value.shape().doc;

							// Display doc comments before the type name
							for line in doc_comments {
								self.write_comment(f, &format!("///{line}"))?;
								writeln!(f)?;
							}

							// Show variant docs
							for line in variant.doc {
								self.write_comment(f, &format!("///{line}"))?;
								writeln!(f)?;
							}

							// Print the enum name and separator
							self.write_type_name(f, item.value)?;
							self.write_punctuation(f, "::")?;

							// Variant docs are already handled above

							// Get the active variant name - we've already checked above that we can
							// get it This is the same variant, but we're repeating the code
							// here to ensure consistency

							// Apply color for variant name
							if self.use_colors {
								if self.use_colors {
									write!(f, "\x1b[1m{}\x1b[0m", variant.name)?;
								// bold
								} else {
									write!(f, "{}", variant.name)?;
								}
							} else {
								write!(f, "{}", variant.name)?;
							}

							// Process the variant fields based on the variant kind
							match variant.data.kind {
								StructKind::Unit => {
									// Unit variant has no fields, nothing more
									// to print
								},
								StructKind::Tuple => {
									// Tuple variant, print the fields like a tuple
									self.write_punctuation(f, "(")?;

									// Check if there are any fields to print
									if variant.data.fields.is_empty() {
										self.write_punctuation(f, ")")?;
										continue;
									}

									let newline = !(matches!(
										variant.data.kind,
										StructKind::Tuple | StructKind::TupleStruct
									) && variant.data.fields.len() == 1
										&& variant.data.fields[0].doc.is_empty());

									if newline {
										writeln!(f)?;
									}

									// Push back item to process fields
									item.state = StackState::ProcessStructField { field_index: 0 };
									item.format_depth += newline as usize;
									stack.push_back(item);
								},
								StructKind::Struct => {
									// Struct variant, print the fields like a struct
									self.write_punctuation(f, " {")?;

									// Check if there are any fields to print
									let has_fields = !variant.data.fields.is_empty();

									if !has_fields {
										self.write_punctuation(f, " }")?;
										continue;
									}

									writeln!(f)?;

									// Push back item to process fields
									item.state = StackState::ProcessStructField { field_index: 0 };
									item.format_depth += 1;
									stack.push_back(item);
								},
								_ => {
									// Other variant kinds that might be added in the future
									write!(f, " /* unsupported variant kind */")?;
								},
							}
						},
						(_, Type::Pointer(PointerType::Function(_))) => {
							// Just print the type name for function pointers
							self.write_type_name(f, item.value)?;
							write!(f, " /* function pointer (not yet supported) */")?;
						},
						_ => {
							write!(f, "unsupported peek variant: {:?}", item.value)?;
						},
					}
				},
				StackState::ProcessStructField { field_index } => {
					// Handle both struct and enum fields
					if let Type::User(UserType::Struct(struct_)) = item.value.shape().ty {
						let newline =
							!(matches!(struct_.kind, StructKind::Tuple | StructKind::TupleStruct)
								&& struct_.fields.len() == 1
								&& struct_.fields[0].doc.is_empty());

						let peek_struct = item.value.into_struct().unwrap();
						if field_index >= struct_.fields.len() {
							// All fields processed, write closing brace
							let delim = match struct_.kind {
								StructKind::Unit => unreachable!(),
								StructKind::Struct => "}",
								StructKind::TupleStruct | StructKind::Tuple => ")",
							};
							if newline {
								self.indent.write(f, item.format_depth - 1)?;
							}
							write!(f, "{}", self.style_punctuation(delim))?;
							continue;
						}

						let field = struct_.fields[field_index];
						let field_value = peek_struct.field(field_index).unwrap();

						// Field doc comment
						if !field.doc.is_empty() {
							// Only add new line if not the first field
							if field_index > 0 {
								writeln!(f)?;
							}
							// Hard-code consistent indentation for doc comments
							for line in field.doc {
								// Use exactly the same indentation as fields (2 spaces)
								self.indent.write(f, item.format_depth)?;
								self.write_comment(f, &format!("///{line}"))?;
								writeln!(f)?;
							}
						}

						if newline {
							self.indent.write(f, item.format_depth)?;
							if let StructKind::Struct = struct_.kind {
								// Field name
								self.write_field_name(f, field.name)?;
								self.write_punctuation(f, ": ")?;
							}
						}

						// Check if field is sensitive
						if field.flags.contains(FieldFlags::SENSITIVE) {
							// Field value is sensitive, use write_redacted
							self.write_redacted(f, "[REDACTED]")?;
							if newline {
								self.write_punctuation(f, ",")?;
								writeln!(f)?;
							}

							item.state = StackState::ProcessStructField {
								field_index: field_index + 1,
							};
							stack.push_back(item);
						} else {
							// Field value is not sensitive, format normally
							// Push back current item to continue after formatting field value
							item.state = StackState::ProcessStructField {
								field_index: field_index + 1,
							};

							let finish_item = StackItem {
								value: field_value,
								format_depth: item.format_depth,
								type_depth: item.type_depth + 1,
								state: StackState::Finish { newline },
							};
							let start_item = StackItem {
								value: field_value,
								format_depth: item.format_depth,
								type_depth: item.type_depth + 1,
								state: StackState::Start,
							};

							stack.push_back(item);
							stack.push_back(finish_item);
							stack.push_back(start_item);
						}
					} else if let Type::User(UserType::Enum(_def)) = item.value.shape().ty {
						let enum_val = item.value.into_enum().unwrap();

						// Get active variant or skip this field processing
						let variant = match enum_val.active_variant() {
							Ok(v) => v,
							Err(_) => {
								// Skip field processing for this enum
								continue;
							},
						};
						let newline = !(matches!(
							variant.data.kind,
							StructKind::Tuple | StructKind::TupleStruct
						) && variant.data.fields.len() == 1
							&& variant.data.fields[0].doc.is_empty());

						if field_index >= variant.data.fields.len() {
							// Determine variant kind to use the right closing delimiter
							match variant.data.kind {
								StructKind::Tuple => {
									// Close tuple variant with )
									if newline {
										self.indent.write(f, item.format_depth - 1)?;
									}
									write!(f, "{}", self.style_punctuation(")"))?;
								},
								StructKind::Struct => {
									// Close struct variant with }
									if newline {
										self.indent.write(f, item.format_depth - 1)?;
									}
									write!(f, "{}", self.style_punctuation("}"))?;
								},
								_ => {},
							}
							continue;
						}

						let field = variant.data.fields[field_index];

						// Get field value or skip this field
						let field_value = match enum_val.field(field_index) {
							Ok(Some(v)) => v,
							_ => {
								// Can't get the field value, skip this field
								item.state = StackState::ProcessStructField {
									field_index: field_index + 1,
								};
								stack.push_back(item);
								continue;
							},
						};

						// Add field doc comments if available
						// Only add new line if not the first field
						if newline {
							self.indent.write(f, item.format_depth)?;
						}

						if !field.doc.is_empty() {
							for line in field.doc {
								self.write_comment(f, &format!("///{line}"))?;
								writeln!(f)?;
								self.indent.write(f, item.format_depth)?;
							}
						}

						// For struct variants, print field name
						if let StructKind::Struct = variant.data.kind {
							self.write_field_name(f, field.name)?;
							self.write_punctuation(f, ": ")?;
						}

						// Set up to process the next field after this one
						item.state = StackState::ProcessStructField {
							field_index: field_index + 1,
						};

						// Create finish and start items for processing the field value
						let finish_item = StackItem {
							value: field_value,
							format_depth: item.format_depth,
							type_depth: item.type_depth + 1,
							state: StackState::Finish { newline },
						};
						let start_item = StackItem {
							value: field_value,
							format_depth: item.format_depth,
							type_depth: item.type_depth + 1,
							state: StackState::Start,
						};

						// Push items to stack in the right order
						stack.push_back(item);
						stack.push_back(finish_item);
						stack.push_back(start_item);
					}
				},
				StackState::ProcessSeqItem { item_index, kind } => {
					let (len, elem) = match kind {
						SeqKind::List => {
							let list = item.value.into_list_like().unwrap();
							(list.len(), list.get(item_index))
						},
						SeqKind::Tuple => {
							let tuple = item.value.into_tuple().unwrap();
							(tuple.len(), tuple.field(item_index))
						},
					};
					if item_index >= len {
						// All items processed, write closing bracket
						self.indent.write(f, item.format_depth - 1)?;
						self.write_punctuation(
							f,
							match kind {
								SeqKind::List => "]",
								SeqKind::Tuple => ")",
							},
						)?;
						continue;
					}

					// Indent
					self.indent.write(f, item.format_depth)?;

					// Push back current item to continue after formatting list item
					item.state = StackState::ProcessSeqItem {
						item_index: item_index + 1,
						kind,
					};
					let next_format_depth = item.format_depth;
					let next_type_depth = item.type_depth + 1;
					stack.push_back(item);

					let elem = elem.unwrap();

					// Push list item to format first
					stack.push_back(StackItem {
						value: elem,
						format_depth: next_format_depth,
						type_depth: next_type_depth,
						state: StackState::Finish { newline: true },
					});

					// When we push a list item to format, we need to process it from the beginning
					stack.push_back(StackItem {
						value: elem,
						format_depth: next_format_depth,
						type_depth: next_type_depth,
						state: StackState::Start, // Use Start state to properly process the item
					});
				},
				StackState::ProcessBytesItem { item_index } => {
					let list = item.value.into_list().unwrap();
					if item_index >= list.len() {
						// All items processed, write closing bracket
						self.indent.write(f, item.format_depth - 1)?;
						continue;
					}

					// On the first byte, write the opening byte sequence indicator
					if item_index == 0 {
						write!(f, " ")?;
					}

					// Only display 16 bytes per line
					if item_index > 0 && item_index % 16 == 0 {
						writeln!(f)?;
						self.indent.write(f, item.format_depth)?;
					} else if item_index > 0 {
						write!(f, " ")?;
					}

					// Get the byte
					let byte_value = list.get(item_index).unwrap();
					// Get the byte value as u8
					let byte = byte_value.get::<u8>().unwrap_or(&0);

					// Generate a color for this byte based on its value
					let mut hasher = SipHasher::new();
					byte.hash(&mut hasher);
					let hash = hasher.finish();
					let color = self.color_generator.generate_color(hash);

					// Apply color if needed
					if self.use_colors {
						write!(f, "\x1b[38;2;{};{};{}m", color.r, color.g, color.b)?;
					}

					// Display the byte in hex format
					write!(f, "{:02x}", *byte)?;

					// Reset color if needed
					// Reset color already handled by stylize

					// Push back current item to continue after formatting byte
					item.state = StackState::ProcessBytesItem {
						item_index: item_index + 1,
					};
					stack.push_back(item);
				},
				StackState::ProcessMapEntry => {
					// TODO: Implement proper map iteration when available in facet

					// Indent
					self.indent.write(f, item.format_depth)?;
					write!(f, "{}", self.style_comment("/* Map contents */"))?;
					writeln!(f)?;

					// Closing brace with proper indentation
					self.indent.write(f, item.format_depth - 1)?;

					write!(f, "{}", self.style_punctuation("}"))?;
				},
				StackState::Finish { newline } => {
					if newline {
						// Add comma and newline for struct fields and list items
						self.write_punctuation(f, ",")?;
						writeln!(f)?;
					}
				},
				StackState::OptionFinish => {
					// Just close the Option::Some parenthesis, with no comma
					self.write_punctuation(f, ")")?;
				},
			}
		}

		Ok(())
	}

	fn handle_list<'mem, 'facet>(
		&self,
		stack: &mut VecDeque<StackItem<'mem, 'facet>>,
		mut item: StackItem<'mem, 'facet>,
		f: &mut impl Write,
	) -> fmt::Result {
		let list = item.value.into_list_like().unwrap();

		// When recursing into a list, always increment format_depth
		// Only increment type_depth if we're moving to a different address
		let new_type_depth =
            // Incrementing type_depth for all list operations
            item.type_depth + 1; // Always increment type_depth for list operations

		// Print the list name
		self.write_punctuation(f, "<")?;
		self.write_type_name(f, item.value)?;
		self.write_punctuation(f, ">")?;

		if list.def().t().is_type::<u8>() && self.list_u8_as_bytes {
			// Push back the item with the next state to continue processing list items
			item.state = StackState::ProcessBytesItem { item_index: 0 };
			writeln!(f)?;
			write!(f, " ")?;

			// TODO: write all the bytes here instead?
		} else {
			// Push back the item with the next state to continue processing list items
			item.state = StackState::ProcessSeqItem {
				item_index: 0,
				kind: SeqKind::List,
			};
			self.write_punctuation(f, " [")?;
			if list.is_empty() {
				self.write_punctuation(f, "]")?;
				return Ok(());
			}
			writeln!(f)?;
		}

		item.format_depth += 1;
		item.type_depth = new_type_depth;
		stack.push_back(item);

		Ok(())
	}

	/// Format a scalar value
	fn format_scalar(
		&self,
		value: Peek,
		f: &mut impl Write,
	) -> fmt::Result {
		// Generate a color for this shape
		let mut hasher = SipHasher::new();
		value.shape().id.hash(&mut hasher);
		let hash = hasher.finish();
		let color = self.color_generator.generate_color(hash);

		// Display the value
		struct DisplayWrapper<'mem, 'facet>(&'mem Peek<'mem, 'facet>);

		impl fmt::Display for DisplayWrapper<'_, '_> {
			fn fmt(
				&self,
				f: &mut fmt::Formatter<'_>,
			) -> fmt::Result {
				if self.0.shape().is_display() {
					write!(f, "{}", self.0)?;
				} else if self.0.shape().is_debug() {
					write!(f, "{:?}", self.0)?;
				} else {
					write!(f, "{}", self.0.shape())?;
					write!(f, "(⋯)")?;
				}
				Ok(())
			}
		}

		// Apply color if needed and display
		if self.use_colors {
			// We need to use direct ANSI codes for RGB colors
			write!(
				f,
				"\x1b[38;2;{};{};{}m{}",
				color.r,
				color.g,
				color.b,
				DisplayWrapper(&value)
			)?;
			write!(f, "\x1b[0m")?;
		} else {
			write!(f, "{}", DisplayWrapper(&value))?;
		}

		Ok(())
	}

	/// Write styled type name to formatter
	pub(crate) fn write_type_name<W: fmt::Write>(
		&self,
		f: &mut W,
		peek: Peek,
	) -> fmt::Result {
		struct TypeNameWriter<'mem, 'facet>(Peek<'mem, 'facet>);

		impl core::fmt::Display for TypeNameWriter<'_, '_> {
			fn fmt(
				&self,
				f: &mut core::fmt::Formatter<'_>,
			) -> core::fmt::Result {
				self.0.type_name(f, TypeNameOpts::infinite())
			}
		}
		let type_name = TypeNameWriter(peek);

		if self.use_colors {
			write!(f, "\x1b[1m{type_name}\x1b[0m") // bold
		} else {
			write!(f, "{type_name}")
		}
	}

	/// Style a type name and return it as a string
	#[allow(dead_code)]
	fn style_type_name(
		&self,
		peek: Peek,
	) -> String {
		let mut result = String::new();
		self.write_type_name(&mut result, peek).unwrap();
		result
	}

	/// Write styled field name to formatter
	fn write_field_name<W: fmt::Write>(
		&self,
		f: &mut W,
		name: &str,
	) -> fmt::Result {
		if self.use_colors {
			// Use cyan color for field names (approximating original RGB color)
			write!(f, "\x1b[36m{name}\x1b[0m") // cyan
		} else {
			write!(f, "{name}")
		}
	}

	/// Write styled punctuation to formatter
	fn write_punctuation<W: fmt::Write>(
		&self,
		f: &mut W,
		text: &str,
	) -> fmt::Result {
		if self.use_colors {
			write!(f, "\x1b[2m{text}\x1b[0m") // dim
		} else {
			write!(f, "{text}")
		}
	}

	/// Style punctuation and return it as a string
	fn style_punctuation(
		&self,
		text: &str,
	) -> String {
		let mut result = String::new();
		self.write_punctuation(&mut result, text).unwrap();
		result
	}

	/// Write styled comment to formatter
	fn write_comment<W: fmt::Write>(
		&self,
		f: &mut W,
		text: &str,
	) -> fmt::Result {
		if self.use_colors {
			write!(f, "\x1b[2m{text}\x1b[0m") // dim
		} else {
			write!(f, "{text}")
		}
	}

	/// Style a comment and return it as a string
	fn style_comment(
		&self,
		text: &str,
	) -> String {
		let mut result = String::new();
		self.write_comment(&mut result, text).unwrap();
		result
	}

	/// Write styled redacted value to formatter
	fn write_redacted<W: fmt::Write>(
		&self,
		f: &mut W,
		text: &str,
	) -> fmt::Result {
		if self.use_colors {
			// Use bright red and bold for redacted values
			if self.use_colors {
				write!(f, "\x1b[91;1m{text}\x1b[0m") // bright red + bold
			} else {
				write!(f, "{text}")
			}
		} else {
			write!(f, "{text}")
		}
	}

	/// Style a redacted value and return it as a string
	#[allow(dead_code)]
	fn style_redacted(
		&self,
		text: &str,
	) -> String {
		let mut result = String::new();
		self.write_redacted(&mut result, text).unwrap();
		result
	}
}