1use crate::*;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum FormatMode {
10 Compact,
12 Aligned,
14 Spaced,
16}
17
18#[inline]
20pub fn glyph(byte: u8) -> char {
21 char::from_u32(0x2400 + byte as u32).unwrap_or('\u{FFFD}')
22}
23
24#[inline]
25fn push_glyph(out: &mut Vec<u8>, byte: u8) {
26 let mut tmp = [0u8; 4];
27 out.extend_from_slice(glyph(byte).encode_utf8(&mut tmp).as_bytes());
28}
29
30pub fn format(buf: &[u8]) -> Result<String> {
32 format_with(buf, " ")
33}
34
35pub fn format_with(buf: &[u8], indent: &str) -> Result<String> {
37 let mut out = Vec::new();
38 format_compact(buf, indent, &mut out)?;
39 Ok(String::from_utf8_lossy(&out).into_owned())
40}
41
42pub fn format_mode(buf: &[u8], indent: &str, mode: FormatMode) -> Result<String> {
44 let compact = format_with(buf, indent)?;
45 Ok(match mode {
46 FormatMode::Compact => compact,
47 _ => align(&compact, mode),
48 })
49}
50
51fn newline_unless(out: &mut Vec<u8>, line_start: bool) {
54 if !line_start {
55 out.push(b'\n');
56 }
57}
58
59fn format_compact(buf: &[u8], indent: &str, out: &mut Vec<u8>) -> Result<()> {
60 let len = buf.len();
61 let mut pos = 0;
62 let mut depth = 0usize; let mut gdepth = 0usize; let mut line_start = true;
65 let mut prefixed = false; let mut stack: Vec<usize> = Vec::new();
67
68 while pos < len {
69 let byte = buf[pos];
70 if byte >= 0x20 || is_layout(byte) {
71 if is_layout(byte) {
73 pos += 1;
74 } else {
75 let start = pos;
76 pos = scan::plain(buf, pos, len);
77 write_data(&buf[start..pos], out)?;
78 line_start = false;
79 }
80 continue;
81 }
82 match byte {
83 SYN => {
84 newline_unless(out, line_start);
85 push_glyph(out, SYN);
86 pos = write_heading(buf, pos + 1, len, out)?;
87 out.push(b'\n');
88 line_start = true;
89 gdepth = 0;
90 }
91 FS => {
92 if !prefixed {
93 newline_unless(out, line_start);
94 write_indent(out, indent, depth);
95 }
96 prefixed = false;
97 push_glyph(out, FS);
98 pos = write_plain(buf, pos + 1, len, out)?;
99 out.push(b'\n');
100 line_start = true;
101 gdepth = 1;
102 }
103 GS => {
104 if !prefixed {
106 newline_unless(out, line_start);
107 write_indent(out, indent, depth);
108 }
109 prefixed = false;
110 push_glyph(out, GS);
111 pos = write_plain(buf, pos + 1, len, out)?;
112 out.push(b'\n');
113 line_start = true;
114 gdepth = 1;
115 }
116 SUB => {
117 let mut p2 = scan::layout(buf, pos + 1, len);
119 while p2 < len && buf[p2] == SUB {
120 p2 = scan::layout(buf, p2 + 1, len);
121 }
122 if p2 < len && (buf[p2] == GS || buf[p2] == FS) {
123 newline_unless(out, line_start);
124 write_indent(out, indent, depth);
125 for _ in 0..count_sub(&buf[pos..p2]) {
126 push_glyph(out, SUB);
127 }
128 prefixed = true;
129 line_start = false;
130 pos = p2;
131 } else {
132 newline_unless(out, line_start);
133 write_indent(out, indent, depth + gdepth);
134 let (p, d, ls) = write_element(buf, pos, len, out, depth, gdepth, &mut stack)?;
135 pos = p;
136 depth = d;
137 line_start = ls;
138 }
139 }
140 SOH | RS | BEL | ETB => {
141 newline_unless(out, line_start);
142 write_indent(out, indent, depth + gdepth);
143 let (p, d, ls) = write_element(buf, pos, len, out, depth, gdepth, &mut stack)?;
144 pos = p;
145 depth = d;
146 line_start = ls;
147 }
148 CAN => {
149 depth = depth.saturating_sub(1);
150 gdepth = stack.pop().unwrap_or(0);
151 newline_unless(out, line_start);
152 write_indent(out, indent, depth + gdepth);
153 push_glyph(out, CAN);
154 pos += 1;
155 let (p, d, ls) = write_units(buf, pos, len, out, depth, gdepth, &mut stack)?;
157 pos = p;
158 depth = d;
159 line_start = ls;
160 if !line_start {
161 out.push(b'\n');
162 line_start = true;
163 }
164 }
165 EOT => {
166 newline_unless(out, line_start);
167 push_glyph(out, EOT);
168 out.push(b'\n');
169 pos += 1;
170 line_start = true;
171 }
172 EM => {
173 newline_unless(out, line_start);
174 push_glyph(out, EM);
175 let tail = len - pos - 1;
176 if tail > 0 {
177 out.extend_from_slice(format!(" {tail} bytes").as_bytes());
178 }
179 out.push(b'\n');
180 return Ok(());
181 }
182 STX | DLE | ENQ | US => {
183 let (p, d, ls) = write_units(buf, pos, len, out, depth, gdepth, &mut stack)?;
185 pos = p;
186 depth = d;
187 let _ = ls;
188 out.push(b'\n');
189 line_start = true;
190 }
191 _ => {
192 return Err(Error::UnassignedCode {
193 byte,
194 position: pos,
195 })
196 }
197 }
198 }
199 if !line_start {
200 out.push(b'\n');
201 }
202 Ok(())
203}
204
205fn write_element(
208 buf: &[u8],
209 mut pos: usize,
210 len: usize,
211 out: &mut Vec<u8>,
212 mut depth: usize,
213 gdepth: usize,
214 stack: &mut Vec<usize>,
215) -> Result<(usize, usize, bool)> {
216 let byte = buf[pos];
217 let mut line_start = false;
218 match byte {
219 BEL => {
220 push_glyph(out, BEL);
221 pos = scan::layout(buf, pos + 1, len);
222 if pos < len && (buf[pos] >= 0x20 || buf[pos] == STX) {
223 let (p, d, _ls) = write_units(buf, pos, len, out, depth, gdepth, stack)?;
224 out.push(b'\n');
225 return Ok((p, d, true));
226 }
227 if pos >= len {
229 return Ok((pos, depth, false));
230 }
231 return write_element(buf, pos, len, out, depth, gdepth, stack);
232 }
233 SUB => {
234 push_glyph(out, SUB);
236 pos = scan::layout(buf, pos + 1, len);
237 if pos >= len {
238 return Ok((pos, depth, false));
239 }
240 return write_element(buf, pos, len, out, depth, gdepth, stack);
241 }
242 SOH => {
243 push_glyph(out, SOH);
244 pos = scan::layout(buf, pos + 1, len);
245 if pos < len && buf[pos] == RS {
246 push_glyph(out, RS);
247 pos += 1;
248 }
249 let (p, d, ls) = write_units(buf, pos, len, out, depth, gdepth, stack)?;
250 pos = p;
251 depth = d;
252 line_start = ls;
253 }
254 RS => {
255 push_glyph(out, RS);
256 let (p, d, ls) = write_units(buf, pos + 1, len, out, depth, gdepth, stack)?;
257 pos = p;
258 depth = d;
259 line_start = ls;
260 }
261 ETB => {
262 push_glyph(out, ETB);
263 pos = write_plain(buf, pos + 1, len, out)?;
264 }
265 _ => {}
266 }
267 if !line_start {
268 out.push(b'\n');
269 line_start = true;
270 }
271 Ok((pos, depth, line_start))
272}
273
274fn write_units(
279 buf: &[u8],
280 mut pos: usize,
281 len: usize,
282 out: &mut Vec<u8>,
283 depth: usize,
284 gdepth: usize,
285 stack: &mut Vec<usize>,
286) -> Result<(usize, usize, bool)> {
287 while pos < len {
288 let b = buf[pos];
289 if b >= 0x20 {
290 let start = pos;
291 pos = scan::plain(buf, pos, len);
292 write_data(trim(&buf[start..pos]), out)?;
293 } else if is_layout(b) {
294 pos += 1;
295 } else if b == US || b == ENQ {
296 push_glyph(out, b);
297 pos += 1;
298 } else if b == SUB {
299 let mut p2 = scan::layout(buf, pos + 1, len);
302 while p2 < len && buf[p2] == SUB {
303 p2 = scan::layout(buf, p2 + 1, len);
304 }
305 if !(p2 < len && buf[p2] == US) {
306 break;
307 }
308 for _ in 0..count_sub(&buf[pos..p2]) {
309 push_glyph(out, SUB);
310 }
311 pos = p2;
312 } else if b == SOH {
313 let p2 = scan::layout(buf, pos + 1, len);
314 if p2 < len && buf[p2] == RS {
315 break;
316 }
317 push_glyph(out, SOH);
318 pos += 1;
319 } else if b == STX {
320 let stop = scan::text(buf, pos, len)?;
321 write_text(&buf[pos..stop], out)?;
322 pos = stop;
323 } else if b == DLE {
324 push_glyph(out, DLE);
325 out.push(b'\n');
326 stack.push(gdepth);
327 return Ok((pos + 1, depth + 1, true));
328 } else if b == BEL {
329 let p2 = scan::layout(buf, pos + 1, len);
330 if p2 < len && (buf[p2] >= 0x20 || buf[p2] == STX || buf[p2] == DLE) {
331 push_glyph(out, BEL);
332 pos = p2;
333 } else {
334 break;
335 }
336 } else if b == ETB {
337 push_glyph(out, ETB);
338 pos = write_plain(buf, pos + 1, len, out)?;
339 } else {
340 break;
341 }
342 }
343 Ok((pos, depth, false))
344}
345
346fn write_heading(buf: &[u8], mut pos: usize, len: usize, out: &mut Vec<u8>) -> Result<usize> {
347 while pos < len {
348 let b = buf[pos];
349 if b == SOH {
350 let p2 = scan::layout(buf, pos + 1, len);
351 if p2 < len && buf[p2] == RS {
352 break;
353 }
354 push_glyph(out, SOH);
355 pos = write_plain(buf, p2, len, out)?;
356 if pos < len && buf[pos] == US {
357 push_glyph(out, US);
358 pos = scan::layout(buf, pos + 1, len);
359 if pos < len && buf[pos] == STX {
360 let stop = scan::text(buf, pos, len)?;
361 write_text(&buf[pos..stop], out)?;
362 pos = stop;
363 } else if pos < len && buf[pos] == DLE {
364 let stop = scan::level(buf, pos, len)?;
365 write_inline_level(&buf[pos..stop], out)?;
367 pos = stop;
368 } else {
369 pos = write_plain(buf, pos, len, out)?;
370 }
371 }
372 } else if b == BEL {
373 let p2 = scan::layout(buf, pos + 1, len);
374 if p2 < len && (buf[p2] >= 0x20 || buf[p2] == STX) {
375 push_glyph(out, BEL);
376 pos = p2;
377 if buf[pos] == STX {
378 let stop = scan::text(buf, pos, len)?;
379 write_text(&buf[pos..stop], out)?;
380 pos = stop;
381 } else {
382 pos = write_plain(buf, pos, len, out)?;
383 }
384 } else if p2 < len && buf[p2] == SOH {
385 push_glyph(out, BEL);
386 pos = p2;
387 } else {
388 break;
389 }
390 } else if is_layout(b) {
391 pos += 1;
392 } else {
393 break;
394 }
395 }
396 Ok(pos)
397}
398
399fn count_sub(run: &[u8]) -> usize {
401 run.iter().filter(|&&b| b == SUB).count()
402}
403
404fn write_inline_level(raw: &[u8], out: &mut Vec<u8>) -> Result<()> {
406 let mut i = 0;
407 while i < raw.len() {
408 let b = raw[i];
409 if b == STX {
410 let stop = scan::text(raw, i, raw.len())?;
411 write_text(&raw[i..stop], out)?;
412 i = stop;
413 } else if b >= 0x20 {
414 let start = i;
415 i = scan::plain(raw, i, raw.len());
416 write_data(trim(&raw[start..i]), out)?;
417 } else if is_layout(b) {
418 i += 1;
419 } else {
420 push_glyph(out, b);
421 i += 1;
422 }
423 }
424 Ok(())
425}
426
427fn write_plain(buf: &[u8], pos: usize, len: usize, out: &mut Vec<u8>) -> Result<usize> {
428 let start = scan::layout(buf, pos, len);
429 let pos = scan::plain(buf, start, len);
430 write_data(trim(&buf[start..pos]), out)?;
431 Ok(pos)
432}
433
434fn write_text(text: &[u8], out: &mut Vec<u8>) -> Result<()> {
437 check_glyphs(text)?;
438 push_glyph(out, STX);
439 for &b in &text[1..text.len() - 1] {
440 if b < 0x20 && b != LF && b != CR && b != HT {
441 push_glyph(out, b);
442 } else {
443 out.push(b);
444 }
445 }
446 push_glyph(out, ETX);
447 Ok(())
448}
449
450fn write_data(data: &[u8], out: &mut Vec<u8>) -> Result<()> {
451 check_glyphs(data)?;
452 out.extend_from_slice(data);
453 Ok(())
454}
455
456fn check_glyphs(data: &[u8]) -> Result<()> {
459 if data
460 .windows(3)
461 .any(|w| w[0] == 0xE2 && w[1] == 0x90 && (0x80..=0x9F).contains(&w[2]))
462 {
463 return Err(Error::GlyphInData);
464 }
465 Ok(())
466}
467
468fn write_indent(out: &mut Vec<u8>, indent: &str, depth: usize) {
469 for _ in 0..depth {
470 out.extend_from_slice(indent.as_bytes());
471 }
472}
473
474fn glyph_code(ch: char) -> Option<u8> {
477 let cp = ch as u32;
478 (0x2400..=0x241F).contains(&cp).then(|| (cp - 0x2400) as u8)
479}
480
481fn push_char(out: &mut Vec<u8>, ch: char) {
482 let mut tmp = [0u8; 4];
483 out.extend_from_slice(ch.encode_utf8(&mut tmp).as_bytes());
484}
485
486pub fn parse(s: &str) -> Vec<u8> {
490 let chars: Vec<char> = s.chars().collect();
491 let mut out = Vec::new();
492 let mut pending: Vec<u8> = Vec::new(); let mut after_code = true;
494 let mut i = 0;
495 while i < chars.len() {
496 let ch = chars[i];
497 if let Some(code) = glyph_code(ch) {
498 pending.clear();
499 out.push(code);
500 i += 1;
501 if code == STX {
502 i = parse_text(&chars, i, &mut out);
503 } else if code == EM {
504 while i < chars.len() && chars[i] != '\n' {
506 i += 1;
507 }
508 }
509 after_code = true;
510 } else if ch == '\n' || ch == '\r' {
511 pending.clear();
512 after_code = true;
513 i += 1;
514 } else if ch == ' ' || ch == '\t' {
515 if !after_code {
516 pending.push(ch as u8);
517 }
518 i += 1;
519 } else {
520 out.append(&mut pending);
521 after_code = false;
522 push_char(&mut out, ch);
523 i += 1;
524 }
525 }
526 out
527}
528
529fn parse_text(chars: &[char], mut i: usize, out: &mut Vec<u8>) -> usize {
532 while i < chars.len() {
533 let ch = chars[i];
534 if let Some(code) = glyph_code(ch) {
535 out.push(code);
536 i += 1;
537 if code == DLE {
538 if let Some(nx) = chars.get(i).and_then(|&c| glyph_code(c)) {
539 out.push(nx);
540 i += 1;
541 }
542 } else if code == ETX {
543 return i;
544 }
545 } else {
546 push_char(out, ch);
547 i += 1;
548 }
549 }
550 i
551}
552
553struct TableLine {
556 line_index: usize,
557 prefix: String,
558 fields: Vec<String>,
559 seps: Vec<bool>,
562}
563
564pub fn align(pretty: &str, mode: FormatMode) -> String {
567 let mut lines: Vec<String> = pretty.split('\n').map(str::to_string).collect();
568 if lines.last().is_some_and(String::is_empty) {
569 lines.pop();
570 }
571 let groups = find_table_groups(&lines);
572 let spaced = mode == FormatMode::Spaced;
573 let sp = if spaced { " " } else { "" };
574 let g_us = glyph(US);
575
576 let mut table_lines = std::collections::HashSet::new();
577 for group in &groups {
578 for line in group {
579 table_lines.insert(line.line_index);
580 }
581 }
582
583 for group in &groups {
584 let col_count = group.iter().map(|l| l.fields.len()).max().unwrap_or(0);
585 let mut max_widths = vec![0usize; col_count];
586 for line in group {
587 for (c, f) in line.fields.iter().enumerate() {
588 max_widths[c] = max_widths[c].max(f.chars().count());
589 }
590 }
591 for line in group {
592 let mut text = String::new();
593 text.push_str(&line.prefix);
594 text.push_str(sp);
595 let n = line.fields.len();
596 for (col, field) in line.fields.iter().enumerate() {
597 text.push_str(field);
598 if col < n - 1 {
599 let pad = max_widths[col] - field.chars().count();
600 text.extend(std::iter::repeat_n(' ', pad));
601 if line.seps[col] {
602 text.push_str(sp);
603 text.push(g_us);
604 text.push_str(sp);
605 } else {
606 text.push(' ');
607 }
608 }
609 }
610 lines[line.line_index] = text;
611 }
612 }
613
614 let prefixes = [
615 glyph(FS),
616 glyph(GS),
617 glyph(RS),
618 glyph(SOH),
619 glyph(US),
620 glyph(SYN),
621 glyph(BEL),
622 ];
623 for (i, line) in lines.iter_mut().enumerate() {
624 if table_lines.contains(&i) || line.trim().is_empty() {
625 continue;
626 }
627 let chars: Vec<char> = line.chars().collect();
628 let mut ws_end = 0;
629 while ws_end < chars.len() && (chars[ws_end] == ' ' || chars[ws_end] == '\t') {
630 ws_end += 1;
631 }
632 let mut glyph_end = ws_end;
633 while glyph_end < chars.len() && prefixes.contains(&chars[glyph_end]) {
634 glyph_end += 1;
635 }
636 if glyph_end == ws_end || glyph_end >= chars.len() {
637 continue;
638 }
639 let indent_str: String = chars[..ws_end].iter().collect();
640 let glyphs: String = chars[ws_end..glyph_end].iter().collect();
641 let rest: String = chars[glyph_end..].iter().collect();
642 let rest = rest.trim_start();
643 *line = if spaced {
644 format!("{indent_str}{glyphs} {rest}")
645 } else {
646 format!("{indent_str}{glyphs}{rest}")
647 };
648 }
649
650 let mut result = lines.join("\n");
651 result.push('\n');
652 result
653}
654
655fn find_table_groups(lines: &[String]) -> Vec<Vec<TableLine>> {
656 let breakers = [glyph(GS), glyph(FS), glyph(EOT), glyph(SYN), glyph(CAN)];
657 let g_soh = glyph(SOH);
658 let g_rs = glyph(RS);
659 let mut groups: Vec<Vec<TableLine>> = Vec::new();
660 let mut current: Option<Vec<TableLine>> = None;
661
662 fn close(groups: &mut Vec<Vec<TableLine>>, current: &mut Option<Vec<TableLine>>) {
663 if let Some(cur) = current.take() {
664 if !cur.is_empty() {
665 groups.push(cur);
666 }
667 }
668 }
669
670 for (i, text) in lines.iter().enumerate() {
671 let trimmed = text.trim();
672 let first = trimmed.chars().next();
673 if trimmed.is_empty() || first.is_some_and(|c| breakers.contains(&c)) {
674 close(&mut groups, &mut current);
675 continue;
676 }
677 if first == Some(g_soh) || first == Some(g_rs) {
678 match parse_table_line(i, text) {
679 Some(parsed) if parsed.fields.len() >= 2 => {
680 current.get_or_insert_with(Vec::new).push(parsed);
681 }
682 _ => close(&mut groups, &mut current),
683 }
684 } else {
685 close(&mut groups, &mut current);
686 }
687 }
688 close(&mut groups, &mut current);
689 groups
690}
691
692fn parse_table_line(line_index: usize, text: &str) -> Option<TableLine> {
695 let g_soh = glyph(SOH);
696 let g_rs = glyph(RS);
697 let g_us = glyph(US);
698 let g_stx = glyph(STX);
699 let g_etx = glyph(ETX);
700 let g_dle = glyph(DLE);
701 let g_can = glyph(CAN);
702 let chars: Vec<char> = text.chars().collect();
703 let mut i = 0;
704 while i < chars.len() && (chars[i] == ' ' || chars[i] == '\t') {
705 i += 1;
706 }
707 if i >= chars.len() {
708 return None;
709 }
710 if chars[i] == g_soh {
711 i += 1;
712 if !(i < chars.len() && chars[i] == g_rs) {
713 return None;
714 }
715 i += 1;
716 } else if chars[i] == g_rs {
717 i += 1;
718 } else {
719 return None;
720 }
721 let prefix: String = chars[..i].iter().collect();
722 let prefix_len = i;
723 let mut fields = Vec::new();
724 let mut seps = Vec::new();
725 let mut field = String::new();
726 let mut in_text = false;
727 let keyed = i < chars.len() && chars[i] == g_soh;
728 while i < chars.len() {
729 let ch = chars[i];
730 if in_text {
731 field.push(ch);
732 if ch == g_etx {
733 in_text = false;
734 }
735 if ch == g_dle && i + 1 < chars.len() {
736 field.push(chars[i + 1]);
737 i += 1;
738 }
739 } else if ch == g_stx {
740 in_text = true;
741 field.push(ch);
742 } else if ch == g_dle || ch == g_can {
743 return None; } else if ch == g_us {
745 fields.push(field.trim().to_string());
746 seps.push(true);
747 field = String::new();
748 } else if keyed && ch == g_soh && i > prefix_len {
749 fields.push(field.trim().to_string());
750 seps.push(false);
751 field = String::new();
752 field.push(ch);
753 } else {
754 field.push(ch);
755 }
756 i += 1;
757 }
758 if in_text {
759 return None; }
761 fields.push(field.trim().to_string());
762 if fields.len() < 2 {
763 return None;
764 }
765 Some(TableLine {
766 line_index,
767 prefix,
768 fields,
769 seps,
770 })
771}