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 use super::*;
442 use alloy_primitives::{B256, address};
443 use foundry_macros::ConsoleFmt;
444 use std::str::FromStr;
445
446 macro_rules! logf1 {
447 ($a:ident) => {
448 console_format(&$a.p_0, &[&$a.p_1])
449 };
450 }
451
452 macro_rules! logf2 {
453 ($a:ident) => {
454 console_format(&$a.p_0, &[&$a.p_1, &$a.p_2])
455 };
456 }
457
458 macro_rules! logf3 {
459 ($a:ident) => {
460 console_format(&$a.p_0, &[&$a.p_1, &$a.p_2, &$a.p_3])
461 };
462 }
463
464 #[derive(Clone, Debug, ConsoleFmt)]
465 struct Log1 {
466 p_0: String,
467 p_1: U256,
468 }
469
470 #[derive(Clone, Debug, ConsoleFmt)]
471 struct Log2 {
472 p_0: String,
473 p_1: bool,
474 p_2: U256,
475 }
476
477 #[derive(Clone, Debug, ConsoleFmt)]
478 struct Log3 {
479 p_0: String,
480 p_1: Address,
481 p_2: bool,
482 p_3: U256,
483 }
484
485 #[expect(unused)]
486 #[derive(Clone, Debug, ConsoleFmt)]
487 enum Logs {
488 Log1(Log1),
489 Log2(Log2),
490 Log3(Log3),
491 }
492
493 #[test]
494 fn test_console_log_format_specifiers() {
495 let fmt_1 = |spec: &str, arg: &dyn ConsoleFmt| console_format(spec, &[arg]);
496
497 assert_eq!("foo", fmt_1("%s", &String::from("foo")));
498 assert_eq!("NaN", fmt_1("%d", &String::from("foo")));
499 assert_eq!("NaN", fmt_1("%i", &String::from("foo")));
500 assert_eq!("NaN", fmt_1("%e", &String::from("foo")));
501 assert_eq!("NaN", fmt_1("%x", &String::from("foo")));
502 assert_eq!("'foo'", fmt_1("%o", &String::from("foo")));
503 assert_eq!("%s foo", fmt_1("%%s", &String::from("foo")));
504 assert_eq!("% foo", fmt_1("%", &String::from("foo")));
505 assert_eq!("% foo", fmt_1("%%", &String::from("foo")));
506
507 assert_eq!("true", fmt_1("%s", &true));
508 assert_eq!("1", fmt_1("%d", &true));
509 assert_eq!("0", fmt_1("%d", &false));
510 assert_eq!("NaN", fmt_1("%i", &true));
511 assert_eq!("NaN", fmt_1("%e", &true));
512 assert_eq!("NaN", fmt_1("%x", &true));
513 assert_eq!("'true'", fmt_1("%o", &true));
514
515 let b32 =
516 B256::from_str("0xdeadbeef00000000000000000000000000000000000000000000000000000000")
517 .unwrap();
518 assert_eq!(
519 "0xdeadbeef00000000000000000000000000000000000000000000000000000000",
520 fmt_1("%s", &b32)
521 );
522 assert_eq!(
523 "0xdeadbeef00000000000000000000000000000000000000000000000000000000",
524 fmt_1("%x", &b32)
525 );
526 assert_eq!("NaN", fmt_1("%d", &b32));
527 assert_eq!("NaN", fmt_1("%i", &b32));
528 assert_eq!("NaN", fmt_1("%e", &b32));
529 assert_eq!(
530 "'0xdeadbeef00000000000000000000000000000000000000000000000000000000'",
531 fmt_1("%o", &b32)
532 );
533
534 let addr = address!("0xdEADBEeF00000000000000000000000000000000");
535 assert_eq!("0xdEADBEeF00000000000000000000000000000000", fmt_1("%s", &addr));
536 assert_eq!("NaN", fmt_1("%d", &addr));
537 assert_eq!("NaN", fmt_1("%i", &addr));
538 assert_eq!("NaN", fmt_1("%e", &addr));
539 assert_eq!("0xdEADBEeF00000000000000000000000000000000", fmt_1("%x", &addr));
540 assert_eq!("'0xdEADBEeF00000000000000000000000000000000'", fmt_1("%o", &addr));
541
542 let bytes = Bytes::from_str("0xdeadbeef").unwrap();
543 assert_eq!("0xdeadbeef", fmt_1("%s", &bytes));
544 assert_eq!("NaN", fmt_1("%d", &bytes));
545 assert_eq!("NaN", fmt_1("%i", &bytes));
546 assert_eq!("NaN", fmt_1("%e", &bytes));
547 assert_eq!("0xdeadbeef", fmt_1("%x", &bytes));
548 assert_eq!("'0xdeadbeef'", fmt_1("%o", &bytes));
549
550 assert_eq!("100", fmt_1("%s", &U256::from(100)));
551 assert_eq!("100", fmt_1("%d", &U256::from(100)));
552 assert_eq!("100", fmt_1("%i", &U256::from(100)));
553 assert_eq!("1e2", fmt_1("%e", &U256::from(100)));
554 assert_eq!("1.0023e6", fmt_1("%e", &U256::from(1002300)));
555 assert_eq!("1.23e5", fmt_1("%e", &U256::from(123000)));
556 assert_eq!("0x64", fmt_1("%x", &U256::from(100)));
557 assert_eq!("100", fmt_1("%o", &U256::from(100)));
558
559 assert_eq!("100", fmt_1("%s", &I256::try_from(100).unwrap()));
560 assert_eq!("100", fmt_1("%d", &I256::try_from(100).unwrap()));
561 assert_eq!("100", fmt_1("%i", &I256::try_from(100).unwrap()));
562 assert_eq!("1e2", fmt_1("%e", &I256::try_from(100).unwrap()));
563 assert_eq!("-1e2", fmt_1("%e", &I256::try_from(-100).unwrap()));
564 assert_eq!("-1.0023e6", fmt_1("%e", &I256::try_from(-1002300).unwrap()));
565 assert_eq!("-1.23e5", fmt_1("%e", &I256::try_from(-123000).unwrap()));
566 assert_eq!("1.0023e6", fmt_1("%e", &I256::try_from(1002300).unwrap()));
567 assert_eq!("1.23e5", fmt_1("%e", &I256::try_from(123000).unwrap()));
568
569 assert_eq!("10", fmt_1("%1e", &I256::try_from(100).unwrap()));
571 assert_eq!("-1", fmt_1("%2e", &I256::try_from(-100).unwrap()));
572 assert_eq!("123000", fmt_1("%0e", &I256::try_from(123000).unwrap()));
573 assert_eq!("12300", fmt_1("%1e", &I256::try_from(123000).unwrap()));
574 assert_eq!("0.0123", fmt_1("%7e", &I256::try_from(123000).unwrap()));
575 assert_eq!("-0.0123", fmt_1("%7e", &I256::try_from(-123000).unwrap()));
576
577 assert_eq!("0x64", fmt_1("%x", &I256::try_from(100).unwrap()));
578 assert_eq!(
579 "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c",
580 fmt_1("%x", &I256::try_from(-100).unwrap())
581 );
582 assert_eq!(
583 "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffe8b7891800",
584 fmt_1("%x", &I256::try_from(-100000000000i64).unwrap())
585 );
586 assert_eq!("100", fmt_1("%o", &I256::try_from(100).unwrap()));
587
588 assert_eq!("%333d%3e%5F", console_format("%333d%3e%5F", &[]));
590 assert_eq!(
591 "%5d123456.789%2f%3f%e1",
592 console_format("%5d%3e%2f%3f%e1", &[&U256::from(123456789)])
593 );
594 }
595
596 #[test]
598 fn test_console_log_exponential_precision_overflow() {
599 let fmt_1 = |spec: &str, arg: &dyn ConsoleFmt| console_format(spec, &[arg]);
600
601 assert_eq!(format!("0.{}1", "0".repeat(255)), fmt_1("%256e", &U256::from(1)));
603
604 let ten_pow_77 = U256::from(10).pow(U256::from(77u64));
606 assert_eq!("0.1", fmt_1("%78e", &ten_pow_77));
607
608 assert_eq!("1", fmt_1("%77e", &ten_pow_77));
609
610 assert_eq!(format!("0.{}1", "0".repeat(76)), fmt_1("%77e", &I256::try_from(1).unwrap()));
612 assert_eq!(format!("-0.{}1", "0".repeat(76)), fmt_1("%77e", &I256::try_from(-1).unwrap()));
613
614 assert_eq!(format!("0.{}1", "0".repeat(1023)), fmt_1("%1024e", &U256::from(1)));
616
617 assert_eq!("%1025e 1", fmt_1("%1025e", &U256::from(1)));
619 assert_eq!("%99999999999999999999e 1", fmt_1("%99999999999999999999e", &U256::from(1)));
620
621 assert_eq!("1", fmt_1("%18e", &U256::from(1_000_000_000_000_000_000u64)));
622
623 assert_eq!("0", fmt_1("%0e", &U256::from(0)));
624 assert_eq!("0", fmt_1("%256e", &U256::from(0)));
625
626 let expect_fallback = |digits: String, precision: usize, sign: &str| {
628 let padded = format!("{digits:0>precision$}");
629 let trimmed = padded.trim_end_matches('0');
630 if trimmed.is_empty() { format!("{sign}0") } else { format!("{sign}0.{trimmed}") }
631 };
632 assert_eq!(expect_fallback(U256::MAX.to_string(), 78, ""), fmt_1("%78e", &U256::MAX));
633 assert_eq!(
634 expect_fallback(I256::MIN.unsigned_abs().to_string(), 77, "-"),
635 fmt_1("%77e", &I256::MIN)
636 );
637 assert_eq!(
638 expect_fallback(I256::MAX.unsigned_abs().to_string(), 77, ""),
639 fmt_1("%77e", &I256::MAX)
640 );
641 }
642
643 #[test]
644 fn test_console_log_format() {
645 let mut log1 = Log1 { p_0: "foo %s".to_string(), p_1: U256::from(100) };
646 assert_eq!("foo 100", logf1!(log1));
647 log1.p_0 = String::from("foo");
648 assert_eq!("foo 100", logf1!(log1));
649 log1.p_0 = String::from("%s foo");
650 assert_eq!("100 foo", logf1!(log1));
651
652 let mut log2 = Log2 { p_0: "foo %s %s".to_string(), p_1: true, p_2: U256::from(100) };
653 assert_eq!("foo true 100", logf2!(log2));
654 log2.p_0 = String::from("foo");
655 assert_eq!("foo true 100", logf2!(log2));
656 log2.p_0 = String::from("%s %s foo");
657 assert_eq!("true 100 foo", logf2!(log2));
658
659 let log3 = Log3 {
660 p_0: String::from("foo %s %%s %s and %d foo %%"),
661 p_1: address!("0xdEADBEeF00000000000000000000000000000000"),
662 p_2: true,
663 p_3: U256::from(21),
664 };
665 assert_eq!(
666 "foo 0xdEADBEeF00000000000000000000000000000000 %s true and 21 foo %",
667 logf3!(log3)
668 );
669
670 let log4 = Log1 { p_0: String::from("%5e"), p_1: U256::from(123456789) };
672 assert_eq!("1234.56789", logf1!(log4));
673
674 let log5 = Log1 { p_0: String::from("foo %3e bar"), p_1: U256::from(123456789) };
675 assert_eq!("foo 123456.789 bar", logf1!(log5));
676
677 let log6 =
678 Log2 { p_0: String::from("%e and %12e"), p_1: false, p_2: U256::from(123456789) };
679 assert_eq!("NaN and 0.000123456789", logf2!(log6));
680 }
681
682 #[test]
683 fn test_derive_format() {
684 let log1 = Log1 { p_0: String::from("foo %s bar"), p_1: U256::from(42) };
685 assert_eq!(log1.fmt(Default::default()), "foo 42 bar");
686 let call = Logs::Log1(log1);
687 assert_eq!(call.fmt(Default::default()), "foo 42 bar");
688 }
689
690 #[test]
691 fn test_console_table_format() {
692 let values: &[&dyn ConsoleFmt] = &[&U256::from(100), &U256::from(200), &U256::from(300)];
694 assert_eq!(
695 console_table_format(None, values),
696 "┌─────────┬────────┐\n\
697 │ (index) │ Values │\n\
698 ├─────────┼────────┤\n\
699 │ 0 │ 100 │\n\
700 │ 1 │ 200 │\n\
701 │ 2 │ 300 │\n\
702 └─────────┴────────┘"
703 );
704
705 let keys: &[&dyn ConsoleFmt] =
708 &[&String::from("alice"), &String::from("bob"), &String::from("charlie123")];
709 let values: &[&dyn ConsoleFmt] = &[
710 &U256::from(1),
711 &U256::from_str("20000000000000000").unwrap(),
712 &U256::from_str("30000000000").unwrap(),
713 ];
714 assert_eq!(
715 console_table_format(Some(keys), values),
716 "┌────────────┬───────────────────┐\n\
717 │ (index) │ Values │\n\
718 ├────────────┼───────────────────┤\n\
719 │ alice │ 1 │\n\
720 │ bob │ 20000000000000000 │\n\
721 │ charlie123 │ 30000000000 │\n\
722 └────────────┴───────────────────┘"
723 );
724
725 assert_eq!(
727 console_table_format(None, &[]),
728 "┌─────────┬────────┐\n\
729 │ (index) │ Values │\n\
730 ├─────────┼────────┤\n\
731 └─────────┴────────┘"
732 );
733
734 let keys: &[&dyn ConsoleFmt] =
736 &[&String::from("alice"), &String::from("bob"), &String::from("charlie")];
737 let values: &[&dyn ConsoleFmt] = &[&U256::from(1), &U256::from(2)];
738 assert_eq!(
739 console_table_format(Some(keys), values),
740 "┌─────────┬────────┐\n\
741 │ (index) │ Values │\n\
742 ├─────────┼────────┤\n\
743 │ alice │ 1 │\n\
744 │ bob │ 2 │\n\
745 │ charlie │ │\n\
746 └─────────┴────────┘"
747 );
748
749 let keys: &[&dyn ConsoleFmt] = &[&String::from("alice"), &String::from("bob")];
751 let values: &[&dyn ConsoleFmt] =
752 &[&U256::from(1), &U256::from(2), &U256::from(3), &U256::from(4)];
753 assert_eq!(
754 console_table_format(Some(keys), values),
755 "┌─────────┬────────┐\n\
756 │ (index) │ Values │\n\
757 ├─────────┼────────┤\n\
758 │ alice │ 1 │\n\
759 │ bob │ 2 │\n\
760 │ │ 3 │\n\
761 │ │ 4 │\n\
762 └─────────┴────────┘"
763 );
764 }
765}