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