1use super::UIfmt;
2use alloy_primitives::{Address, Bytes, FixedBytes, I256, U256};
3use comfy_table::{ContentLineStyle, LineStyle, Table, TableStyle};
4use std::fmt::{self, Write};
5
6const MAX_EXPONENTIAL_PRECISION: usize = 1024;
8
9#[derive(Clone, Debug, PartialEq, Eq)]
11pub enum Piece<'a> {
12 String(&'a str),
14 NextArgument(FormatSpec),
16}
17
18#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub enum FormatSpec {
21 #[default]
23 String,
24 Number,
26 Integer,
28 Object,
30 Exponential(Option<usize>),
32 Hexadecimal,
34}
35
36impl fmt::Display for FormatSpec {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.write_str("%")?;
39 match *self {
40 Self::String => f.write_str("s"),
41 Self::Number => f.write_str("d"),
42 Self::Integer => f.write_str("i"),
43 Self::Object => f.write_str("o"),
44 Self::Exponential(Some(n)) => write!(f, "{n}e"),
45 Self::Exponential(None) => f.write_str("e"),
46 Self::Hexadecimal => f.write_str("x"),
47 }
48 }
49}
50
51enum ParseArgError {
52 Err,
54 Skip,
56}
57
58#[derive(Debug)]
60pub struct Parser<'a> {
61 input: &'a str,
62 chars: std::str::CharIndices<'a>,
63}
64
65impl<'a> Parser<'a> {
66 pub fn new(input: &'a str) -> Self {
68 Self { input, chars: input.char_indices() }
69 }
70
71 fn string(&mut self, start: usize, mut skip: usize) -> &'a str {
76 while let Some((pos, c)) = self.peek() {
77 if c == '%' {
78 if skip == 0 {
79 return &self.input[start..pos];
80 }
81 skip -= 1;
82 }
83 self.chars.next();
84 }
85 &self.input[start..]
86 }
87
88 fn argument(&mut self) -> Result<FormatSpec, ParseArgError> {
93 let (start, ch) = self.peek().ok_or(ParseArgError::Err)?;
94 let simple_spec = match ch {
95 's' => Some(FormatSpec::String),
96 'd' => Some(FormatSpec::Number),
97 'i' => Some(FormatSpec::Integer),
98 'o' => Some(FormatSpec::Object),
99 'e' => Some(FormatSpec::Exponential(None)),
100 'x' => Some(FormatSpec::Hexadecimal),
101 '%' => return Err(ParseArgError::Skip),
103 _ => None,
104 };
105 if let Some(spec) = simple_spec {
106 self.chars.next();
107 return Ok(spec);
108 }
109
110 if ch.is_ascii_digit() {
112 let n = self.integer(start);
113 if let Some((_, 'e')) = self.peek() {
114 self.chars.next();
115 return n
116 .filter(|&precision| precision <= MAX_EXPONENTIAL_PRECISION)
117 .map(|precision| FormatSpec::Exponential(Some(precision)))
118 .ok_or(ParseArgError::Err);
119 }
120 }
121
122 Err(ParseArgError::Err)
123 }
124
125 fn integer(&mut self, start: usize) -> Option<usize> {
126 let mut end = start;
127 while let Some((pos, ch)) = self.peek() {
128 if !ch.is_ascii_digit() {
129 end = pos;
130 break;
131 }
132 self.chars.next();
133 }
134 self.input[start..end].parse().ok()
135 }
136
137 fn current_pos(&mut self) -> usize {
138 self.peek().map(|(n, _)| n).unwrap_or(self.input.len())
139 }
140
141 fn peek(&mut self) -> Option<(usize, char)> {
142 self.peek_n(0)
143 }
144
145 fn peek_n(&mut self, n: usize) -> Option<(usize, char)> {
146 self.chars.clone().nth(n)
147 }
148}
149
150impl<'a> Iterator for Parser<'a> {
151 type Item = Piece<'a>;
152
153 fn next(&mut self) -> Option<Self::Item> {
154 let (mut start, ch) = self.peek()?;
155 let mut skip = 0;
156 if ch == '%' {
157 let prev = self.chars.clone();
158 self.chars.next();
159 match self.argument() {
160 Ok(arg) => {
161 debug_assert_eq!(arg.to_string(), self.input[start..self.current_pos()]);
162 return Some(Piece::NextArgument(arg));
163 }
164
165 Err(ParseArgError::Skip) => {
167 start = self.current_pos();
168 skip += 1;
169 }
170
171 Err(ParseArgError::Err) => {
174 self.chars = prev;
175 skip += 1;
176 }
177 }
178 }
179 Some(Piece::String(self.string(start, skip)))
180 }
181}
182
183pub trait ConsoleFmt {
185 fn fmt(&self, spec: FormatSpec) -> String;
187}
188
189impl ConsoleFmt for String {
190 fn fmt(&self, spec: FormatSpec) -> String {
191 match spec {
192 FormatSpec::String => self.clone(),
193 FormatSpec::Object => format!("'{}'", self.clone()),
194 FormatSpec::Number
195 | FormatSpec::Integer
196 | FormatSpec::Exponential(_)
197 | FormatSpec::Hexadecimal => Self::from("NaN"),
198 }
199 }
200}
201
202impl ConsoleFmt for bool {
203 fn fmt(&self, spec: FormatSpec) -> String {
204 match spec {
205 FormatSpec::String => self.pretty(),
206 FormatSpec::Object => format!("'{}'", self.pretty()),
207 FormatSpec::Number => (*self as i32).to_string(),
208 FormatSpec::Integer | FormatSpec::Exponential(_) | FormatSpec::Hexadecimal => {
209 String::from("NaN")
210 }
211 }
212 }
213}
214
215impl ConsoleFmt for U256 {
216 fn fmt(&self, spec: FormatSpec) -> String {
217 match spec {
218 FormatSpec::String | FormatSpec::Object | FormatSpec::Number | FormatSpec::Integer => {
219 self.pretty()
220 }
221 FormatSpec::Hexadecimal => {
222 let hex = format!("{self:x}");
223 format!("0x{}", hex.trim_start_matches('0'))
224 }
225 FormatSpec::Exponential(None) => {
226 let log = self.pretty().len() - 1;
227 let exp10 = Self::from(10).pow(Self::from(log));
228 let amount = *self;
229 let integer = amount / exp10;
230 let decimal = (amount % exp10).to_string();
231 let decimal = format!("{decimal:0>log$}").trim_end_matches('0').to_string();
232 if decimal.is_empty() {
233 format!("{integer}e{log}")
234 } else {
235 format!("{integer}.{decimal}e{log}")
236 }
237 }
238 FormatSpec::Exponential(Some(precision)) => format_fixed(*self, "", precision),
239 }
240 }
241}
242
243impl ConsoleFmt for I256 {
244 fn fmt(&self, spec: FormatSpec) -> String {
245 match spec {
246 FormatSpec::String | FormatSpec::Object | FormatSpec::Number | FormatSpec::Integer => {
247 self.pretty()
248 }
249 FormatSpec::Hexadecimal => {
250 let hex = format!("{self:x}");
251 format!("0x{}", hex.trim_start_matches('0'))
252 }
253 FormatSpec::Exponential(None) => {
254 let amount = *self;
255 let sign = if amount.is_negative() { "-" } else { "" };
256 let log = if amount.is_negative() {
257 self.pretty().len() - 2
258 } else {
259 self.pretty().len() - 1
260 };
261 let exp10 = Self::exp10(log);
262 let integer = (amount / exp10).twos_complement();
263 let decimal = (amount % exp10).twos_complement().to_string();
264 let decimal = format!("{decimal:0>log$}").trim_end_matches('0').to_string();
265 if decimal.is_empty() {
266 format!("{sign}{integer}e{log}")
267 } else {
268 format!("{sign}{integer}.{decimal}e{log}")
269 }
270 }
271 FormatSpec::Exponential(Some(precision)) => {
272 let amount = *self;
273 let sign = if amount.is_negative() { "-" } else { "" };
274 format_fixed(amount.unsigned_abs(), sign, precision)
275 }
276 }
277 }
278}
279
280fn format_fixed(amount: U256, sign: &str, precision: usize) -> String {
281 let (integer, decimal) = U256::from(10)
282 .checked_pow(U256::from(precision))
283 .map_or((U256::ZERO, amount), |exp10| (amount / exp10, amount % exp10));
284 let decimal = decimal.to_string();
285 let decimal = format!("{decimal:0>precision$}").trim_end_matches('0').to_string();
286 if decimal.is_empty() {
287 format!("{sign}{integer}")
288 } else {
289 format!("{sign}{integer}.{decimal}")
290 }
291}
292
293impl ConsoleFmt for Address {
294 fn fmt(&self, spec: FormatSpec) -> String {
295 match spec {
296 FormatSpec::String | FormatSpec::Hexadecimal => self.pretty(),
297 FormatSpec::Object => format!("'{}'", self.pretty()),
298 FormatSpec::Number | FormatSpec::Integer | FormatSpec::Exponential(_) => {
299 String::from("NaN")
300 }
301 }
302 }
303}
304
305impl ConsoleFmt for Vec<u8> {
306 fn fmt(&self, spec: FormatSpec) -> String {
307 self[..].fmt(spec)
308 }
309}
310
311impl ConsoleFmt for Bytes {
312 fn fmt(&self, spec: FormatSpec) -> String {
313 self[..].fmt(spec)
314 }
315}
316
317impl<const N: usize> ConsoleFmt for [u8; N] {
318 fn fmt(&self, spec: FormatSpec) -> String {
319 self[..].fmt(spec)
320 }
321}
322
323impl<const N: usize> ConsoleFmt for FixedBytes<N> {
324 fn fmt(&self, spec: FormatSpec) -> String {
325 self[..].fmt(spec)
326 }
327}
328
329impl ConsoleFmt for [u8] {
330 fn fmt(&self, spec: FormatSpec) -> String {
331 match spec {
332 FormatSpec::String | FormatSpec::Hexadecimal => self.pretty(),
333 FormatSpec::Object => format!("'{}'", self.pretty()),
334 FormatSpec::Number | FormatSpec::Integer | FormatSpec::Exponential(_) => {
335 String::from("NaN")
336 }
337 }
338 }
339}
340
341pub fn console_format(spec: &str, values: &[&dyn ConsoleFmt]) -> String {
367 let mut values = values.iter().copied();
368 let mut result = String::with_capacity(spec.len());
369
370 let mut write_space = if spec.is_empty() {
372 false
373 } else {
374 format_spec(spec, &mut values, &mut result);
375 true
376 };
377
378 for v in values {
380 let fmt = v.fmt(FormatSpec::String);
381 if write_space {
382 result.push(' ');
383 }
384 result.push_str(&fmt);
385 write_space = true;
386 }
387
388 result
389}
390
391fn format_spec<'a>(
392 s: &str,
393 mut values: impl Iterator<Item = &'a dyn ConsoleFmt>,
394 result: &mut String,
395) {
396 for piece in Parser::new(s) {
397 match piece {
398 Piece::String(s) => result.push_str(s),
399 Piece::NextArgument(spec) => {
400 if let Some(value) = values.next() {
401 result.push_str(&value.fmt(spec));
402 } else {
403 write!(result, "{spec}").unwrap();
405 }
406 }
407 }
408 }
409}
410
411pub fn console_table_format(
412 keys: Option<&[&dyn ConsoleFmt]>,
413 values: &[&dyn ConsoleFmt],
414) -> String {
415 let keys_strings: Vec<String> = match keys {
416 Some(keys) => keys.iter().map(|k| k.fmt(FormatSpec::String)).collect(),
417 None => (0..values.len()).map(|i| i.to_string()).collect(),
418 };
419 let values_strings: Vec<String> = values.iter().map(|v| v.fmt(FormatSpec::String)).collect();
420
421 const STYLE: TableStyle = TableStyle::new()
422 .top_border(LineStyle::new('┌', '─', '┬', '┐'))
423 .header_lines(ContentLineStyle::new('│', '│', '│'))
424 .header_separator(LineStyle::new('├', '─', '┼', '┤'))
425 .content_lines(ContentLineStyle::new('│', '│', '│'))
426 .bottom_border(LineStyle::new('└', '─', '┴', '┘'));
427
428 let mut table = Table::new();
429 table.load_style(STYLE);
430 table.set_header(vec!["(index)", "Values"]);
431 for i in 0..keys_strings.len().max(values_strings.len()) {
432 let key = keys_strings.get(i).map(String::as_str).unwrap_or("");
433 let value = values_strings.get(i).map(String::as_str).unwrap_or("");
434 table.add_row(vec![key, value]);
435 }
436 table.to_string()
437}
438
439#[cfg(test)]
440mod tests {
441
442 use super::*;
443 use alloy_primitives::{address, b256, bytes};
444 use foundry_macros::ConsoleFmt;
445 use std::str::FromStr;
446
447 macro_rules! logf1 {
448 ($a:ident) => {
449 console_format(&$a.p_0, &[&$a.p_1])
450 };
451 }
452
453 macro_rules! logf2 {
454 ($a:ident) => {
455 console_format(&$a.p_0, &[&$a.p_1, &$a.p_2])
456 };
457 }
458
459 macro_rules! logf3 {
460 ($a:ident) => {
461 console_format(&$a.p_0, &[&$a.p_1, &$a.p_2, &$a.p_3])
462 };
463 }
464
465 #[derive(Clone, Debug, ConsoleFmt)]
466 struct Log1 {
467 p_0: String,
468 p_1: U256,
469 }
470
471 #[derive(Clone, Debug, ConsoleFmt)]
472 struct Log2 {
473 p_0: String,
474 p_1: bool,
475 p_2: U256,
476 }
477
478 #[derive(Clone, Debug, ConsoleFmt)]
479 struct Log3 {
480 p_0: String,
481 p_1: Address,
482 p_2: bool,
483 p_3: U256,
484 }
485
486 #[expect(unused)]
487 #[derive(Clone, Debug, ConsoleFmt)]
488 enum Logs {
489 Log1(Log1),
490 Log2(Log2),
491 Log3(Log3),
492 }
493
494 #[test]
495 fn test_console_log_format_specifiers() {
496 let fmt_1 = |spec: &str, arg: &dyn ConsoleFmt| console_format(spec, &[arg]);
497
498 assert_eq!("foo", fmt_1("%s", &String::from("foo")));
499 assert_eq!("NaN", fmt_1("%d", &String::from("foo")));
500 assert_eq!("NaN", fmt_1("%i", &String::from("foo")));
501 assert_eq!("NaN", fmt_1("%e", &String::from("foo")));
502 assert_eq!("NaN", fmt_1("%x", &String::from("foo")));
503 assert_eq!("'foo'", fmt_1("%o", &String::from("foo")));
504 assert_eq!("%s foo", fmt_1("%%s", &String::from("foo")));
505 assert_eq!("% foo", fmt_1("%", &String::from("foo")));
506 assert_eq!("% foo", fmt_1("%%", &String::from("foo")));
507
508 assert_eq!("true", fmt_1("%s", &true));
509 assert_eq!("1", fmt_1("%d", &true));
510 assert_eq!("0", fmt_1("%d", &false));
511 assert_eq!("NaN", fmt_1("%i", &true));
512 assert_eq!("NaN", fmt_1("%e", &true));
513 assert_eq!("NaN", fmt_1("%x", &true));
514 assert_eq!("'true'", fmt_1("%o", &true));
515
516 let b32 = b256!("0xdeadbeef00000000000000000000000000000000000000000000000000000000");
517 assert_eq!(
518 "0xdeadbeef00000000000000000000000000000000000000000000000000000000",
519 fmt_1("%s", &b32)
520 );
521 assert_eq!(
522 "0xdeadbeef00000000000000000000000000000000000000000000000000000000",
523 fmt_1("%x", &b32)
524 );
525 assert_eq!("NaN", fmt_1("%d", &b32));
526 assert_eq!("NaN", fmt_1("%i", &b32));
527 assert_eq!("NaN", fmt_1("%e", &b32));
528 assert_eq!(
529 "'0xdeadbeef00000000000000000000000000000000000000000000000000000000'",
530 fmt_1("%o", &b32)
531 );
532
533 let addr = address!("0xdEADBEeF00000000000000000000000000000000");
534 assert_eq!("0xdEADBEeF00000000000000000000000000000000", fmt_1("%s", &addr));
535 assert_eq!("NaN", fmt_1("%d", &addr));
536 assert_eq!("NaN", fmt_1("%i", &addr));
537 assert_eq!("NaN", fmt_1("%e", &addr));
538 assert_eq!("0xdEADBEeF00000000000000000000000000000000", fmt_1("%x", &addr));
539 assert_eq!("'0xdEADBEeF00000000000000000000000000000000'", fmt_1("%o", &addr));
540
541 let bytes = bytes!("0xdeadbeef");
542 assert_eq!("0xdeadbeef", fmt_1("%s", &bytes));
543 assert_eq!("NaN", fmt_1("%d", &bytes));
544 assert_eq!("NaN", fmt_1("%i", &bytes));
545 assert_eq!("NaN", fmt_1("%e", &bytes));
546 assert_eq!("0xdeadbeef", fmt_1("%x", &bytes));
547 assert_eq!("'0xdeadbeef'", fmt_1("%o", &bytes));
548
549 assert_eq!("100", fmt_1("%s", &U256::from(100)));
550 assert_eq!("100", fmt_1("%d", &U256::from(100)));
551 assert_eq!("100", fmt_1("%i", &U256::from(100)));
552 assert_eq!("1e2", fmt_1("%e", &U256::from(100)));
553 assert_eq!("1.0023e6", fmt_1("%e", &U256::from(1002300)));
554 assert_eq!("1.23e5", fmt_1("%e", &U256::from(123000)));
555 assert_eq!("0x64", fmt_1("%x", &U256::from(100)));
556 assert_eq!("100", fmt_1("%o", &U256::from(100)));
557
558 assert_eq!("100", fmt_1("%s", &I256::try_from(100).unwrap()));
559 assert_eq!("100", fmt_1("%d", &I256::try_from(100).unwrap()));
560 assert_eq!("100", fmt_1("%i", &I256::try_from(100).unwrap()));
561 assert_eq!("1e2", fmt_1("%e", &I256::try_from(100).unwrap()));
562 assert_eq!("-1e2", fmt_1("%e", &I256::try_from(-100).unwrap()));
563 assert_eq!("-1.0023e6", fmt_1("%e", &I256::try_from(-1002300).unwrap()));
564 assert_eq!("-1.23e5", fmt_1("%e", &I256::try_from(-123000).unwrap()));
565 assert_eq!("1.0023e6", fmt_1("%e", &I256::try_from(1002300).unwrap()));
566 assert_eq!("1.23e5", fmt_1("%e", &I256::try_from(123000).unwrap()));
567
568 assert_eq!("10", fmt_1("%1e", &I256::try_from(100).unwrap()));
570 assert_eq!("-1", fmt_1("%2e", &I256::try_from(-100).unwrap()));
571 assert_eq!("123000", fmt_1("%0e", &I256::try_from(123000).unwrap()));
572 assert_eq!("12300", fmt_1("%1e", &I256::try_from(123000).unwrap()));
573 assert_eq!("0.0123", fmt_1("%7e", &I256::try_from(123000).unwrap()));
574 assert_eq!("-0.0123", fmt_1("%7e", &I256::try_from(-123000).unwrap()));
575
576 assert_eq!("0x64", fmt_1("%x", &I256::try_from(100).unwrap()));
577 assert_eq!(
578 "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c",
579 fmt_1("%x", &I256::try_from(-100).unwrap())
580 );
581 assert_eq!(
582 "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffe8b7891800",
583 fmt_1("%x", &I256::try_from(-100000000000i64).unwrap())
584 );
585 assert_eq!("100", fmt_1("%o", &I256::try_from(100).unwrap()));
586
587 assert_eq!("%333d%3e%5F", console_format("%333d%3e%5F", &[]));
589 assert_eq!(
590 "%5d123456.789%2f%3f%e1",
591 console_format("%5d%3e%2f%3f%e1", &[&U256::from(123456789)])
592 );
593 }
594
595 #[test]
597 fn test_console_log_exponential_precision_overflow() {
598 let fmt_1 = |spec: &str, arg: &dyn ConsoleFmt| console_format(spec, &[arg]);
599
600 assert_eq!(format!("0.{}1", "0".repeat(255)), fmt_1("%256e", &U256::ONE));
602
603 let ten_pow_77 = U256::from(10).pow(U256::from(77u64));
605 assert_eq!("0.1", fmt_1("%78e", &ten_pow_77));
606
607 assert_eq!("1", fmt_1("%77e", &ten_pow_77));
608
609 assert_eq!(format!("0.{}1", "0".repeat(76)), fmt_1("%77e", &I256::try_from(1).unwrap()));
611 assert_eq!(format!("-0.{}1", "0".repeat(76)), fmt_1("%77e", &I256::try_from(-1).unwrap()));
612
613 assert_eq!(format!("0.{}1", "0".repeat(1023)), fmt_1("%1024e", &U256::ONE));
615
616 assert_eq!("%1025e 1", fmt_1("%1025e", &U256::ONE));
618 assert_eq!("%99999999999999999999e 1", fmt_1("%99999999999999999999e", &U256::ONE));
619
620 assert_eq!("1", fmt_1("%18e", &U256::from(1_000_000_000_000_000_000u64)));
621
622 assert_eq!("0", fmt_1("%0e", &U256::ZERO));
623 assert_eq!("0", fmt_1("%256e", &U256::ZERO));
624
625 let expect_fallback = |digits: String, precision: usize, sign: &str| {
627 let padded = format!("{digits:0>precision$}");
628 let trimmed = padded.trim_end_matches('0');
629 if trimmed.is_empty() { format!("{sign}0") } else { format!("{sign}0.{trimmed}") }
630 };
631 assert_eq!(expect_fallback(U256::MAX.to_string(), 78, ""), fmt_1("%78e", &U256::MAX));
632 assert_eq!(
633 expect_fallback(I256::MIN.unsigned_abs().to_string(), 77, "-"),
634 fmt_1("%77e", &I256::MIN)
635 );
636 assert_eq!(
637 expect_fallback(I256::MAX.unsigned_abs().to_string(), 77, ""),
638 fmt_1("%77e", &I256::MAX)
639 );
640 }
641
642 #[test]
643 fn test_console_log_format() {
644 let mut log1 = Log1 { p_0: "foo %s".to_string(), p_1: U256::from(100) };
645 assert_eq!("foo 100", logf1!(log1));
646 log1.p_0 = String::from("foo");
647 assert_eq!("foo 100", logf1!(log1));
648 log1.p_0 = String::from("%s foo");
649 assert_eq!("100 foo", logf1!(log1));
650
651 let mut log2 = Log2 { p_0: "foo %s %s".to_string(), p_1: true, p_2: U256::from(100) };
652 assert_eq!("foo true 100", logf2!(log2));
653 log2.p_0 = String::from("foo");
654 assert_eq!("foo true 100", logf2!(log2));
655 log2.p_0 = String::from("%s %s foo");
656 assert_eq!("true 100 foo", logf2!(log2));
657
658 let log3 = Log3 {
659 p_0: String::from("foo %s %%s %s and %d foo %%"),
660 p_1: address!("0xdEADBEeF00000000000000000000000000000000"),
661 p_2: true,
662 p_3: U256::from(21),
663 };
664 assert_eq!(
665 "foo 0xdEADBEeF00000000000000000000000000000000 %s true and 21 foo %",
666 logf3!(log3)
667 );
668
669 let log4 = Log1 { p_0: String::from("%5e"), p_1: U256::from(123456789) };
671 assert_eq!("1234.56789", logf1!(log4));
672
673 let log5 = Log1 { p_0: String::from("foo %3e bar"), p_1: U256::from(123456789) };
674 assert_eq!("foo 123456.789 bar", logf1!(log5));
675
676 let log6 =
677 Log2 { p_0: String::from("%e and %12e"), p_1: false, p_2: U256::from(123456789) };
678 assert_eq!("NaN and 0.000123456789", logf2!(log6));
679 }
680
681 #[test]
682 fn test_derive_format() {
683 let log1 = Log1 { p_0: String::from("foo %s bar"), p_1: U256::from(42) };
684 assert_eq!(log1.fmt(Default::default()), "foo 42 bar");
685 let call = Logs::Log1(log1);
686 assert_eq!(call.fmt(Default::default()), "foo 42 bar");
687 }
688
689 #[test]
690 fn test_console_table_format() {
691 let values: &[&dyn ConsoleFmt] = &[&U256::from(100), &U256::from(200), &U256::from(300)];
693 assert_eq!(
694 console_table_format(None, values),
695 "┌─────────┬────────┐\n\
696 │ (index) │ Values │\n\
697 ├─────────┼────────┤\n\
698 │ 0 │ 100 │\n\
699 │ 1 │ 200 │\n\
700 │ 2 │ 300 │\n\
701 └─────────┴────────┘"
702 );
703
704 let keys: &[&dyn ConsoleFmt] =
707 &[&String::from("alice"), &String::from("bob"), &String::from("charlie123")];
708 let values: &[&dyn ConsoleFmt] = &[
709 &U256::ONE,
710 &U256::from_str("20000000000000000").unwrap(),
711 &U256::from_str("30000000000").unwrap(),
712 ];
713 assert_eq!(
714 console_table_format(Some(keys), values),
715 "┌────────────┬───────────────────┐\n\
716 │ (index) │ Values │\n\
717 ├────────────┼───────────────────┤\n\
718 │ alice │ 1 │\n\
719 │ bob │ 20000000000000000 │\n\
720 │ charlie123 │ 30000000000 │\n\
721 └────────────┴───────────────────┘"
722 );
723
724 assert_eq!(
726 console_table_format(None, &[]),
727 "┌─────────┬────────┐\n\
728 │ (index) │ Values │\n\
729 ├─────────┼────────┤\n\
730 └─────────┴────────┘"
731 );
732
733 let keys: &[&dyn ConsoleFmt] =
735 &[&String::from("alice"), &String::from("bob"), &String::from("charlie")];
736 let values: &[&dyn ConsoleFmt] = &[&U256::ONE, &U256::from(2)];
737 assert_eq!(
738 console_table_format(Some(keys), values),
739 "┌─────────┬────────┐\n\
740 │ (index) │ Values │\n\
741 ├─────────┼────────┤\n\
742 │ alice │ 1 │\n\
743 │ bob │ 2 │\n\
744 │ charlie │ │\n\
745 └─────────┴────────┘"
746 );
747
748 let keys: &[&dyn ConsoleFmt] = &[&String::from("alice"), &String::from("bob")];
750 let values: &[&dyn ConsoleFmt] =
751 &[&U256::ONE, &U256::from(2), &U256::from(3), &U256::from(4)];
752 assert_eq!(
753 console_table_format(Some(keys), values),
754 "┌─────────┬────────┐\n\
755 │ (index) │ Values │\n\
756 ├─────────┼────────┤\n\
757 │ alice │ 1 │\n\
758 │ bob │ 2 │\n\
759 │ │ 3 │\n\
760 │ │ 4 │\n\
761 └─────────┴────────┘"
762 );
763 }
764}