defmt-decoder 1.1.0

Decodes defmt log frames
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
use super::{DefmtRecord, Payload};
use crate::Frame;
use colored::{Color, ColoredString, Colorize, Styles};
use dissimilar::Chunk;
use log::{Level, Record as LogRecord};
use regex::Regex;
use std::{fmt::Write, path::Path};

mod parser;

/// Representation of what a [LogSegment] can be.
#[derive(Debug, PartialEq, Clone)]
#[non_exhaustive]
pub(super) enum LogMetadata {
    /// `{c}` format specifier.
    ///
    /// Prints the name of the crate where the log is coming from.
    CrateName,

    /// `{f}` format specifier.
    ///
    /// This specifier may be repeated up to 255 times.
    /// For a file "/path/to/crate/src/foo/bar.rs":
    /// - `{f}` prints "bar.rs".
    /// - `{ff}` prints "foo/bar.rs".
    /// - `{fff}` prints "src/foo/bar.rs"
    FileName(u8),

    /// `{F}` format specifier.
    ///
    /// For a file "/path/to/crate/src/foo/bar.rs"
    /// this option prints "/path/to/crate/src/foo/bar.rs".
    FilePath,

    /// `{l}` format specifier.
    ///
    /// Prints the line number where the log is coming from.
    LineNumber,

    /// `{s}` format specifier.
    ///
    /// Prints the actual log contents.
    /// For `defmt::info!("hello")`, this prints "hello".
    Log,

    /// `{L}` format specifier.
    ///
    /// Prints the log level.
    /// For `defmt::info!("hello")`, this prints "INFO".
    LogLevel,

    /// `{m}` format specifier.
    ///
    /// Prints the module path of the function where the log is coming from.
    /// For the following log:
    ///
    /// ```ignore
    /// // crate: my_crate
    /// mod foo {
    ///     fn bar() {
    ///         defmt::info!("hello");
    ///     }
    /// }
    /// ```
    /// this prints "my_crate::foo::bar".
    ModulePath,

    /// Represents the parts of the formatting string that is not specifiers.
    String(String),

    /// `{t}` format specifier.
    ///
    /// Prints the timestamp at which something was logged.
    /// For a log printed with a timestamp 123456 ms, this prints "123456".
    Timestamp,

    /// Represents formats specified within nested curly brackets in the formatting string.
    NestedLogSegments(Vec<LogSegment>),
}

impl LogMetadata {
    /// Checks whether this `LogMetadata` came from a specifier such as
    /// {t}, {f}, etc.
    fn is_metadata_specifier(&self) -> bool {
        !matches!(
            self,
            LogMetadata::String(_) | LogMetadata::NestedLogSegments(_)
        )
    }
}

/// Coloring options for [LogSegment]s.
#[derive(Debug, PartialEq, Clone, Copy)]
pub(super) enum LogColor {
    /// User-defined color.
    ///
    /// Use a string that can be parsed by the FromStr implementation
    /// of [colored::Color].
    Color(colored::Color),

    /// Color matching the default color for the log level.
    /// Use `"severity"` as a format parameter to use this option.
    SeverityLevel,

    /// Color matching the default color for the log level,
    /// but only if the log level is WARN or ERROR.
    ///
    /// Use `"werror"` as a format parameter to use this option.
    WarnError,
}

/// Alignment options for [LogSegment]s.
#[derive(Debug, PartialEq, Clone, Copy)]
pub(super) enum Alignment {
    Center,
    Left,
    Right,
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub(super) enum Padding {
    Space,
    Zero,
}

/// Representation of a segment of the formatting string.
#[derive(Debug, PartialEq, Clone)]
pub(super) struct LogSegment {
    pub(super) metadata: LogMetadata,
    pub(super) format: LogFormat,
}

#[derive(Debug, PartialEq, Clone, Default)]
pub(super) struct LogFormat {
    pub(super) width: Option<usize>,
    pub(super) color: Option<LogColor>,
    pub(super) style: Option<Vec<colored::Styles>>,
    pub(super) alignment: Option<Alignment>,
    pub(super) padding: Option<Padding>,
}

impl LogSegment {
    pub(super) const fn new(metadata: LogMetadata) -> Self {
        Self {
            metadata,
            format: LogFormat {
                color: None,
                style: None,
                width: None,
                alignment: None,
                padding: None,
            },
        }
    }

    #[cfg(test)]
    pub(crate) const fn with_color(mut self, color: LogColor) -> Self {
        self.format.color = Some(color);
        self
    }

    #[cfg(test)]
    pub(crate) fn with_style(mut self, style: colored::Styles) -> Self {
        let mut styles = self.format.style.unwrap_or_default();
        styles.push(style);
        self.format.style = Some(styles);
        self
    }

    #[cfg(test)]
    pub(crate) const fn with_width(mut self, width: usize) -> Self {
        self.format.width = Some(width);
        self
    }

    #[cfg(test)]
    pub(crate) const fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.format.alignment = Some(alignment);
        self
    }

    #[cfg(test)]
    pub(crate) const fn with_padding(mut self, padding: Padding) -> Self {
        self.format.padding = Some(padding);
        self
    }
}

/// A formatter for microcontroller-generated frames
pub struct Formatter {
    formatter: InternalFormatter,
}

impl Formatter {
    /// Create a new formatter, using the given configuration.
    pub fn new(config: FormatterConfig) -> Self {
        Self {
            formatter: InternalFormatter::new(config, Source::Defmt),
        }
    }

    /// Format a defmt frame using this formatter.
    pub fn format_frame<'a>(
        &self,
        frame: Frame<'a>,
        file: Option<&'a str>,
        line: Option<u32>,
        module_path: Option<&str>,
    ) -> String {
        let (timestamp, level) = super::timestamp_and_level_from_frame(&frame);

        // HACK: use match instead of let, because otherwise compilation fails
        #[allow(clippy::match_single_binding)]
        match format_args!("{}", frame.display_message()) {
            args => {
                let log_record = &LogRecord::builder()
                    .args(args)
                    .module_path(module_path)
                    .file(file)
                    .line(line)
                    .build();

                let record = DefmtRecord {
                    log_record,
                    payload: Payload { level, timestamp },
                };

                self.format(&record)
            }
        }
    }

    /// Format the given [`DefmtRecord`] (which is an internal type).
    pub(super) fn format(&self, record: &DefmtRecord) -> String {
        self.formatter.format(&Record::Defmt(record))
    }
}

/// A formatter for host-generated frames
pub struct HostFormatter {
    formatter: InternalFormatter,
}

impl HostFormatter {
    /// Create a new host formatter using the given config
    pub fn new(config: FormatterConfig) -> Self {
        Self {
            formatter: InternalFormatter::new(config, Source::Host),
        }
    }

    /// Format the given [`log::Record`].
    pub fn format(&self, record: &LogRecord) -> String {
        self.formatter.format(&Record::Host(record))
    }
}

#[derive(Debug)]
struct InternalFormatter {
    format: Vec<LogSegment>,
}

#[derive(Clone, Copy, PartialEq)]
enum Source {
    Defmt,
    Host,
}

enum Record<'a> {
    Defmt(&'a DefmtRecord<'a>),
    Host(&'a LogRecord<'a>),
}

#[derive(Debug)]
#[non_exhaustive]
pub enum FormatterFormat<'a> {
    /// The classic defmt two-line format.
    ///
    /// Looks like:
    ///
    /// ```text
    /// INFO This is a log message
    /// └─ test_lib::hello @ /Users/jonathan/Documents/knurling/test-lib/src/lib.rs:8
    /// ```
    Default {
        with_location: bool,
    },
    /// A one-line format.
    ///
    /// Looks like:
    ///
    /// ```text
    /// [INFO ] This is a log message (crate_name test-lib/src/lib.rs:8)
    /// ```
    OneLine {
        with_location: bool,
    },
    Custom(&'a str),
}

impl FormatterFormat<'static> {
    /// Parse a string into a choice of [`FormatterFormat`].
    ///
    /// Unknown strings return `None`.
    pub fn from_string(s: &str, with_location: bool) -> Option<FormatterFormat<'static>> {
        match s {
            "default" => Some(FormatterFormat::Default { with_location }),
            "oneline" => Some(FormatterFormat::OneLine { with_location }),
            _ => None,
        }
    }

    /// Get a list of valid string names for the various format options.
    ///
    /// This will *not* include an entry for [`FormatterFormat::Custom`] because
    /// that requires a format string argument.
    pub fn get_options() -> impl Iterator<Item = &'static str> {
        ["default", "oneline"].iter().cloned()
    }
}

impl Default for FormatterFormat<'_> {
    fn default() -> Self {
        FormatterFormat::Default {
            with_location: false,
        }
    }
}

/// Describes one of the fixed format string sets.
trait Style {
    const FORMAT: &'static str;
    const FORMAT_WITH_TS: &'static str;
    const FORMAT_WITH_LOC: &'static str;
    const FORMAT_WITH_TS_LOC: &'static str;

    /// Return a suitable format string, given these options.
    fn get_string(with_location: bool, has_timestamp: bool) -> &'static str {
        match (with_location, has_timestamp) {
            (false, false) => Self::FORMAT,
            (false, true) => Self::FORMAT_WITH_TS,
            (true, false) => Self::FORMAT_WITH_LOC,
            (true, true) => Self::FORMAT_WITH_TS_LOC,
        }
    }
}

/// Implements the `FormatterFormat::Default` style.
struct DefaultStyle;

impl Style for DefaultStyle {
    const FORMAT: &'static str = "{L} {s}";
    const FORMAT_WITH_LOC: &'static str = "{L} {s}\n└─ {m} @ {F}:{l}";
    const FORMAT_WITH_TS: &'static str = "{t} {L} {s}";
    const FORMAT_WITH_TS_LOC: &'static str = "{t} {L} {s}\n└─ {m} @ {F}:{l}";
}

/// Implements the `FormatterFormat::OneLine` style.
struct OneLineStyle;

impl Style for OneLineStyle {
    const FORMAT: &'static str = "{[{L}]%bold} {s}";
    const FORMAT_WITH_LOC: &'static str = "{[{L}]%bold} {s} {({c:bold} {fff}:{l:1})%dimmed}";
    const FORMAT_WITH_TS: &'static str = "{t} {[{L}]%bold} {s}";
    const FORMAT_WITH_TS_LOC: &'static str = "{t} {[{L}]%bold} {s} {({c:bold} {fff}:{l:1})%dimmed}";
}

/// Settings that control how defmt frames should be formatted.
#[derive(Debug, Default)]
pub struct FormatterConfig<'a> {
    /// The format to use
    pub format: FormatterFormat<'a>,
    /// If `true`, then the logs should include a timestamp.
    ///
    /// Not all targets can supply a timestamp, and if not, it should be
    /// omitted.
    pub is_timestamp_available: bool,
}

impl<'a> FormatterConfig<'a> {
    /// Create a new custom formatter config.
    ///
    /// This allows the user to supply a custom log-format string. See the
    /// "Custom Log Output" section of the defmt book for details of the format.
    pub fn custom(format: &'a str) -> Self {
        FormatterConfig {
            format: FormatterFormat::from_string(format, true)
                .unwrap_or(FormatterFormat::Custom(format)),
            is_timestamp_available: false,
        }
    }

    /// Modify a formatter configuration, setting the 'timestamp available' flag
    /// to true.
    pub fn with_timestamp(mut self) -> Self {
        self.is_timestamp_available = true;
        self
    }

    /// Modify a formatter configuration, setting the 'with_location' flag
    /// to true.
    ///
    /// Do not use this with a custom log formatter.
    pub fn with_location(mut self) -> Self {
        // TODO: Should we warn the user that trying to set a location
        //       for a custom format won't work?
        match self.format {
            FormatterFormat::OneLine { with_location: _ } => {
                self.format = FormatterFormat::OneLine {
                    with_location: true,
                };
                self
            }
            FormatterFormat::Default { with_location: _ } => {
                self.format = FormatterFormat::Default {
                    with_location: true,
                };
                self
            }
            _ => self,
        }
    }
}

impl InternalFormatter {
    fn new(config: FormatterConfig, source: Source) -> Self {
        let format = match config.format {
            FormatterFormat::Default { with_location } => {
                let mut format =
                    DefaultStyle::get_string(with_location, config.is_timestamp_available)
                        .to_string();
                if source == Source::Host {
                    format.push_str(" (HOST)");
                }

                format
            }
            FormatterFormat::OneLine { with_location } => {
                let mut format =
                    OneLineStyle::get_string(with_location, config.is_timestamp_available)
                        .to_string();

                if source == Source::Host {
                    format.push_str(" (HOST)");
                }

                format
            }
            FormatterFormat::Custom(format) => format.to_string(),
        };

        let format = parser::parse(&format).expect("log format is invalid '{format}'");

        if matches!(config.format, FormatterFormat::Custom(_)) {
            let format_has_timestamp = format_has_timestamp(&format);
            if format_has_timestamp && !config.is_timestamp_available {
                log::warn!(
                    "logger format contains timestamp but no timestamp implementation \
                    was provided; consider removing the timestamp (`{{t}}`) from the \
                    logger format or provide a `defmt::timestamp!` implementation"
                );
            } else if !format_has_timestamp && config.is_timestamp_available {
                log::warn!(
                    "`defmt::timestamp!` implementation was found, but timestamp is not \
                    part of the log format; consider adding the timestamp (`{{t}}`) \
                    argument to the log format"
                );
            }
        }

        Self { format }
    }

    fn format(&self, record: &Record) -> String {
        let mut buf = String::new();
        // Only format logs, not printlns
        // printlns do not have a log level
        if get_log_level_of_record(record).is_some() {
            for segment in &self.format {
                let s = self.build_segment(record, segment);
                write!(buf, "{s}").expect("writing to String cannot fail");
            }
        } else {
            let empty_format: LogFormat = Default::default();
            let s = self.build_log(record, &empty_format);
            write!(buf, "{s}").expect("writing to String cannot fail");
        }
        buf
    }

    fn build_segment(&self, record: &Record, segment: &LogSegment) -> String {
        match &segment.metadata {
            LogMetadata::String(s) => s.to_string(),
            LogMetadata::Timestamp => self.build_timestamp(record, &segment.format),
            LogMetadata::CrateName => self.build_crate_name(record, &segment.format),
            LogMetadata::FileName(n) => self.build_file_name(record, &segment.format, *n),
            LogMetadata::FilePath => self.build_file_path(record, &segment.format),
            LogMetadata::ModulePath => self.build_module_path(record, &segment.format),
            LogMetadata::LineNumber => self.build_line_number(record, &segment.format),
            LogMetadata::LogLevel => self.build_log_level(record, &segment.format),
            LogMetadata::Log => self.build_log(record, &segment.format),
            LogMetadata::NestedLogSegments(segments) => {
                self.build_nested(record, segments, &segment.format)
            }
        }
    }

    fn build_nested(&self, record: &Record, segments: &[LogSegment], format: &LogFormat) -> String {
        let mut result = String::new();
        for segment in segments {
            let s = match &segment.metadata {
                LogMetadata::String(s) => s.to_string(),
                LogMetadata::Timestamp => self.build_timestamp(record, &segment.format),
                LogMetadata::CrateName => self.build_crate_name(record, &segment.format),
                LogMetadata::FileName(n) => self.build_file_name(record, &segment.format, *n),
                LogMetadata::FilePath => self.build_file_path(record, &segment.format),
                LogMetadata::ModulePath => self.build_module_path(record, &segment.format),
                LogMetadata::LineNumber => self.build_line_number(record, &segment.format),
                LogMetadata::LogLevel => self.build_log_level(record, &segment.format),
                LogMetadata::Log => self.build_log(record, &segment.format),
                LogMetadata::NestedLogSegments(segments) => {
                    self.build_nested(record, segments, &segment.format)
                }
            };
            result.push_str(&s);
        }

        build_formatted_string(
            &result,
            format,
            0,
            get_log_level_of_record(record),
            format.color,
        )
    }

    fn build_timestamp(&self, record: &Record, format: &LogFormat) -> String {
        let s = match record {
            Record::Defmt(record) if !record.timestamp().is_empty() => record.timestamp(),
            _ => "<time>",
        }
        .to_string();

        build_formatted_string(
            s.as_str(),
            format,
            0,
            get_log_level_of_record(record),
            format.color,
        )
    }

    fn build_log_level(&self, record: &Record, format: &LogFormat) -> String {
        let s = match get_log_level_of_record(record) {
            Some(level) => level.to_string(),
            None => "<lvl>".to_string(),
        };

        let color = format.color.unwrap_or(LogColor::SeverityLevel);

        build_formatted_string(
            s.as_str(),
            format,
            5,
            get_log_level_of_record(record),
            Some(color),
        )
    }

    fn build_file_path(&self, record: &Record, format: &LogFormat) -> String {
        let file_path = match record {
            Record::Defmt(record) => record.file(),
            Record::Host(record) => record.file(),
        }
        .unwrap_or("<file>");

        build_formatted_string(
            file_path,
            format,
            0,
            get_log_level_of_record(record),
            format.color,
        )
    }

    fn build_file_name(&self, record: &Record, format: &LogFormat, level_of_detail: u8) -> String {
        let file = match record {
            Record::Defmt(record) => record.file(),
            Record::Host(record) => record.file(),
        };

        let s = if let Some(file) = file {
            let path_iter = Path::new(file).iter();
            let number_of_components = path_iter.clone().count();

            let number_of_components_to_join = number_of_components.min(level_of_detail as usize);

            let number_of_elements_to_skip =
                number_of_components.saturating_sub(number_of_components_to_join);
            let s = path_iter
                .skip(number_of_elements_to_skip)
                .take(number_of_components)
                .fold(String::new(), |mut acc, s| {
                    acc.push_str(s.to_str().unwrap_or("<?>"));
                    acc.push('/');
                    acc
                });
            s.strip_suffix('/').unwrap().to_string()
        } else {
            "<file>".to_string()
        };

        build_formatted_string(&s, format, 0, get_log_level_of_record(record), format.color)
    }

    fn build_module_path(&self, record: &Record, format: &LogFormat) -> String {
        let s = match record {
            Record::Defmt(record) => record.module_path(),
            Record::Host(record) => record.module_path(),
        }
        .unwrap_or("<mod path>");

        build_formatted_string(s, format, 0, get_log_level_of_record(record), format.color)
    }

    fn build_crate_name(&self, record: &Record, format: &LogFormat) -> String {
        let module_path = match record {
            Record::Defmt(record) => record.module_path(),
            Record::Host(record) => record.module_path(),
        };

        let s = if let Some(module_path) = module_path {
            let path = module_path.split("::").collect::<Vec<_>>();

            // There need to be at least two elements, the crate and the function
            if path.len() >= 2 {
                path.first().unwrap()
            } else {
                "<crate>"
            }
        } else {
            "<crate>"
        };

        build_formatted_string(s, format, 0, get_log_level_of_record(record), format.color)
    }

    fn build_line_number(&self, record: &Record, format: &LogFormat) -> String {
        let s = match record {
            Record::Defmt(record) => record.line(),
            Record::Host(record) => record.line(),
        }
        .unwrap_or(0)
        .to_string();

        build_formatted_string(
            s.as_str(),
            format,
            4,
            get_log_level_of_record(record),
            format.color,
        )
    }

    fn build_log(&self, record: &Record, format: &LogFormat) -> String {
        let log_level = get_log_level_of_record(record);
        match record {
            Record::Defmt(record) => match color_diff(record.args().to_string()) {
                Ok(s) => s.to_string(),
                Err(s) => build_formatted_string(s.as_str(), format, 0, log_level, format.color),
            },
            Record::Host(record) => record.args().to_string(),
        }
    }
}

fn get_log_level_of_record(record: &Record) -> Option<Level> {
    match record {
        Record::Defmt(record) => record.level(),
        Record::Host(record) => Some(record.level()),
    }
}

// color the output of `defmt::assert_eq`
// HACK we should not re-parse formatted output but instead directly format into a color diff
// template; that may require specially tagging log messages that come from `defmt::assert_eq`
fn color_diff(text: String) -> Result<String, String> {
    let lines = text.lines().collect::<Vec<_>>();
    let nlines = lines.len();
    if nlines > 2 {
        let left = lines[nlines - 2];
        let right = lines[nlines - 1];

        const LEFT_START: &str = " left: `";
        const RIGHT_START: &str = "right: `";
        const END: &str = "`";
        if left.starts_with(LEFT_START)
            && left.ends_with(END)
            && right.starts_with(RIGHT_START)
            && right.ends_with(END)
        {
            // `defmt::assert_eq!` output
            let left = &left[LEFT_START.len()..left.len() - END.len()];
            let right = &right[RIGHT_START.len()..right.len() - END.len()];

            let mut buf = lines[..nlines - 2].join("\n").bold().to_string();
            buf.push('\n');

            let diffs = dissimilar::diff(left, right);

            writeln!(
                buf,
                "{} {} / {}",
                "diff".bold(),
                "< left".red(),
                "right >".green()
            )
            .ok();
            write!(buf, "{}", "<".red()).ok();
            for diff in &diffs {
                match diff {
                    Chunk::Equal(s) => {
                        write!(buf, "{}", s.red()).ok();
                    }
                    Chunk::Insert(_) => continue,
                    Chunk::Delete(s) => {
                        write!(buf, "{}", s.red().bold()).ok();
                    }
                }
            }
            buf.push('\n');

            write!(buf, "{}", ">".green()).ok();
            for diff in &diffs {
                match diff {
                    Chunk::Equal(s) => {
                        write!(buf, "{}", s.green()).ok();
                    }
                    Chunk::Delete(_) => continue,
                    Chunk::Insert(s) => {
                        write!(buf, "{}", s.green().bold()).ok();
                    }
                }
            }
            return Ok(buf);
        }
    }

    Err(text)
}

fn color_for_log_level(level: Level) -> Color {
    match level {
        Level::Error => Color::Red,
        Level::Warn => Color::Yellow,
        Level::Info => Color::Green,
        Level::Debug => Color::BrightWhite,
        Level::Trace => Color::BrightBlack,
    }
}

fn apply_color(
    s: ColoredString,
    log_color: Option<LogColor>,
    level: Option<Level>,
) -> ColoredString {
    match log_color {
        Some(color) => match color {
            LogColor::Color(c) => s.color(c),
            LogColor::SeverityLevel => match level {
                Some(level) => s.color(color_for_log_level(level)),
                None => s,
            },
            LogColor::WarnError => match level {
                Some(level @ (Level::Warn | Level::Error)) => s.color(color_for_log_level(level)),
                _ => s,
            },
        },
        None => s,
    }
}

fn apply_styles(s: ColoredString, log_style: Option<&Vec<Styles>>) -> ColoredString {
    let Some(log_styles) = log_style else {
        return s;
    };

    let mut stylized_string = s;
    for style in log_styles {
        stylized_string = match style {
            Styles::Bold => stylized_string.bold(),
            Styles::Italic => stylized_string.italic(),
            Styles::Underline => stylized_string.underline(),
            Styles::Strikethrough => stylized_string.strikethrough(),
            Styles::Dimmed => stylized_string.dimmed(),
            Styles::Clear => stylized_string.clear(),
            Styles::Reversed => stylized_string.reversed(),
            Styles::Blink => stylized_string.blink(),
            Styles::Hidden => stylized_string.hidden(),
        };
    }

    stylized_string
}

fn build_formatted_string(
    s: &str,
    format: &LogFormat,
    default_width: usize,
    level: Option<Level>,
    log_color: Option<LogColor>,
) -> String {
    let s = ColoredString::from(s);
    let styled_string_length = s.len();
    let length_without_styles = string_excluding_ansi(&s).len();
    let length_of_ansi_sequences = styled_string_length - length_without_styles;

    let s = apply_color(s, log_color, level);
    let colored_str = apply_styles(s, format.style.as_ref());

    let alignment = format.alignment.unwrap_or(Alignment::Left);
    let width = format.width.unwrap_or(default_width) + length_of_ansi_sequences;
    let padding = format.padding.unwrap_or(Padding::Space);

    let mut result = String::new();
    match (alignment, padding) {
        (Alignment::Left, Padding::Space) => write!(&mut result, "{colored_str:<0$}", width),
        (Alignment::Left, Padding::Zero) => write!(&mut result, "{colored_str:0<0$}", width),
        (Alignment::Center, Padding::Space) => write!(&mut result, "{colored_str:^0$}", width),
        (Alignment::Center, Padding::Zero) => write!(&mut result, "{colored_str:0^0$}", width),
        (Alignment::Right, Padding::Space) => write!(&mut result, "{colored_str:>0$}", width),
        (Alignment::Right, Padding::Zero) => write!(&mut result, "{colored_str:0>0$}", width),
    }
    .expect("Failed to format string: \"{colored_str}\"");
    result
}

fn format_has_timestamp(segments: &[LogSegment]) -> bool {
    for segment in segments {
        match &segment.metadata {
            LogMetadata::Timestamp => return true,
            LogMetadata::NestedLogSegments(s) => {
                if format_has_timestamp(s) {
                    return true;
                }
            }
            _ => continue,
        }
    }
    false
}

/// Returns the given string excluding ANSI control sequences.
fn string_excluding_ansi(s: &str) -> String {
    // Regular expression to match ANSI escape sequences
    let re = Regex::new(r"\x1b\[[0-9;]*m").unwrap();

    // Replace all ANSI sequences with an empty string
    re.replace_all(s, "").to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_left_aligned_styled_string() {
        let format = LogFormat {
            color: Some(LogColor::Color(Color::Green)),
            width: Some(10),
            alignment: Some(Alignment::Left),
            padding: Some(Padding::Space),
            style: Some(vec![Styles::Bold]),
        };

        let s = build_formatted_string("test", &format, 0, None, None);
        let string_without_styles = string_excluding_ansi(&s);
        assert_eq!(string_without_styles, "test      ");
    }

    #[test]
    fn test_right_aligned_styled_string() {
        let format = LogFormat {
            color: Some(LogColor::Color(Color::Green)),
            width: Some(10),
            alignment: Some(Alignment::Right),
            padding: Some(Padding::Space),
            style: Some(vec![Styles::Bold]),
        };

        let s = build_formatted_string("test", &format, 0, None, None);
        let string_without_styles = string_excluding_ansi(&s);
        assert_eq!(string_without_styles, "      test");
    }
}