luff 0.2.1

Print files with formatting
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
//! Core processing pipeline for the WASM module.
//!
//! [`WasmProcessor`] is a stateless, allocation-friendly processor that
//! accepts an iterator of [`VirtualFile`]s, applies filtering and formatting,
//! and writes output to any [`fmt::Write`] sink.
//!
//! Rendering is delegated to [`super::render`] — this module is concerned
//! only with pipeline orchestration: collect → filter → sort → truncate →
//! dispatch to renderer → enforce output limits.

use std::fmt;

use crate::format::OutputFormat;

use super::error::WasmError;
use super::options::ProcessorOptions;
use super::render;
use super::virtual_fs::VirtualFile;

/// Outcome of a processing run.
///
/// This struct is `#[non_exhaustive]` — new fields may be added in
/// future minor releases without a semver bump.
///
/// `Serialize` and `Deserialize` are derived so that results can be
/// propagated across component boundaries (e.g. via `serde-wasm-bindgen`
/// or WIT canonical ABI).
#[derive(
    Clone, Copy, Debug, Default, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize,
)]
#[non_exhaustive]
pub struct ProcessResult {
    /// Number of files included in the output.
    pub files_processed: usize,
    /// Number of files excluded by filter rules (dotfiles, extensions, globs).
    pub files_skipped: usize,
    /// Number of files that passed filters but were excluded by `max_files` truncation.
    pub files_truncated: usize,
    /// Total output size in bytes.
    pub output_bytes: usize,
}

impl ProcessResult {
    /// Total number of input files (processed + skipped + truncated).
    #[must_use]
    pub const fn total_files(&self) -> usize {
        self.files_processed + self.files_skipped + self.files_truncated
    }
}

/// Stateless processor that formats virtual files according to
/// [`ProcessorOptions`].
///
/// Cheap to clone (glob sets use internal `Arc`s).
#[derive(Clone, Debug)]
pub struct WasmProcessor {
    /// The compiled processing options.
    options: ProcessorOptions,
}

impl Default for WasmProcessor {
    fn default() -> Self {
        Self::new(ProcessorOptions::default())
    }
}

impl From<ProcessorOptions> for WasmProcessor {
    fn from(options: ProcessorOptions) -> Self {
        Self::new(options)
    }
}

impl WasmProcessor {
    /// Creates a new processor with the given options.
    #[must_use]
    pub const fn new(options: ProcessorOptions) -> Self {
        Self { options }
    }

    /// Returns a reference to the processor's options.
    #[must_use]
    pub const fn options(&self) -> &ProcessorOptions {
        &self.options
    }

    /// Processes files and writes formatted output to `sink`.
    ///
    /// # Pipeline
    ///
    /// 1. Filter (dotfiles, extensions, globs) — before sort to reduce work.
    /// 2. Sort by `(path, content)` for deterministic output.
    /// 3. Truncate to `max_files`.
    /// 4. Format according to `output_format`.
    /// 5. Write to `sink` through `CountingWriter`.
    ///
    /// # Errors
    ///
    /// Returns [`WasmError::OutputTooLarge`] if `max_output_bytes` is set
    /// and the output exceeds it.
    /// Returns [`WasmError::Fmt`] on write failures.
    pub fn process<W: fmt::Write>(
        &self,
        files: impl IntoIterator<Item = VirtualFile>,
        sink: &mut W,
    ) -> super::Result<ProcessResult> {
        self.process_inner(files.into_iter().collect(), sink)
    }

    /// Convenience method that returns the formatted output as a `String`
    /// alongside the [`ProcessResult`] metadata.
    ///
    /// Pre-allocates based on estimated output size to reduce reallocations.
    ///
    /// # Errors
    ///
    /// Same as [`process`](Self::process).
    pub fn process_to_string(
        &self,
        files: impl IntoIterator<Item = VirtualFile>,
    ) -> super::Result<(String, ProcessResult)> {
        let files: Vec<VirtualFile> = files.into_iter().collect();
        // Pre-allocate: estimate ~1.5× total content size.
        let estimated_size: usize = files
            .iter()
            .map(|f| f.path().len() + f.content().len() + 64)
            .sum();
        let mut output = String::with_capacity(estimated_size);
        let result = self.process_inner(files, &mut output)?;
        Ok((output, result))
    }

    /// Core processing pipeline operating on a pre-collected `Vec`.
    ///
    /// Both [`process`](Self::process) and
    /// [`process_to_string`](Self::process_to_string) delegate here after
    /// a single collect, avoiding redundant allocations.
    fn process_inner<W: fmt::Write>(
        &self,
        mut files: Vec<VirtualFile>,
        sink: &mut W,
    ) -> super::Result<ProcessResult> {
        let total = files.len();

        // 1. Filter — runs before sort so we sort fewer elements.
        //    `retain` preserves relative order, which is irrelevant
        //    since we sort unconditionally in the next step.
        files.retain(|f| !self.should_ignore(f));

        let after_filter = files.len();
        let files_skipped = total - after_filter;

        // 2. Sort for deterministic output.
        files.sort();

        // 3. Truncate.
        let files_truncated = self.options.max_files.map_or(0, |max| {
            let before = files.len();
            files.truncate(max);
            before - files.len()
        });

        let files_processed = files.len();

        debug_assert_eq!(
            files_processed + files_skipped + files_truncated,
            total,
            "conservation invariant: processed + skipped + truncated == total"
        );

        // 4–5. Format and write.
        let mut counting_sink = CountingWriter::new(sink, self.options.max_output_bytes);

        let fmt_result = match self.options.output_format {
            OutputFormat::Markdown => render::write_markdown(&files, &mut counting_sink),
            OutputFormat::Tree => {
                render::write_tree(&files, &self.options.root_label, &mut counting_sink)
            }
        };

        // Distinguish output-too-large from genuine write errors.
        if let Err(e) = fmt_result {
            if counting_sink.overflowed() {
                return Err(WasmError::OutputTooLarge {
                    size: counting_sink.bytes_written(),
                    max: self
                        .options
                        .max_output_bytes
                        .expect("overflowed implies max_bytes is Some"),
                });
            }
            return Err(WasmError::Fmt(e));
        }

        Ok(ProcessResult {
            files_processed,
            files_skipped,
            files_truncated,
            output_bytes: counting_sink.bytes_written(),
        })
    }

    /// Returns `true` if the file should be excluded from output.
    fn should_ignore(&self, file: &VirtualFile) -> bool {
        // Dotfile check.
        if !self.options.include_dotfiles && file.is_dotfile() {
            return true;
        }

        // Extension check (case-insensitive).
        if let Some(ext) = file.extension() {
            if self
                .options
                .ignore_extensions
                .iter()
                .any(|e| e.eq_ignore_ascii_case(ext))
            {
                return true;
            }
        }

        // Glob check — use normalized_path so `./` prefixes don't
        // prevent matches against patterns like `src/**`.
        //
        // Note: `GlobSet::is_match` accepts `AsRef<Path>`. On non-
        // Windows platforms `&str → Path` is a no-op. On Windows,
        // `Path` would interpret `\` as a separator, but we reject
        // backslashes during path validation so this is safe on all
        // platforms.
        if self.options.ignore_globs.is_match(file.normalized_path()) {
            return true;
        }

        false
    }
}

/// A `fmt::Write` adapter that tracks bytes written and optionally
/// enforces a maximum output size.
///
/// When the limit is exceeded, `write_str` returns `fmt::Error` and
/// sets an internal `overflowed` flag. The caller inspects
/// [`overflowed`](Self::overflowed) to distinguish truncation from
/// genuine write failures.
///
/// Once overflowed, all subsequent `write_str` calls short-circuit
/// with `fmt::Error` without touching the inner writer.
///
/// # Note on `bytes_written` after overflow
///
/// When [`overflowed`](Self::overflowed) is `true`, [`bytes_written`](Self::bytes_written)
/// reflects the *attempted* total at the point of overflow (including the
/// rejected write), not the bytes actually forwarded to the inner writer.
/// This is intentional so that error reports can show the size that
/// triggered the limit.
struct CountingWriter<'a, W> {
    /// The underlying writer.
    inner: &'a mut W,
    /// Running total of bytes written (includes the write that
    /// triggered the overflow, so callers can report the actual size).
    bytes_written: usize,
    /// Optional ceiling; exceeding it yields `fmt::Error`.
    max_bytes: Option<usize>,
    /// Set to `true` when a write is rejected due to the size limit.
    overflowed: bool,
}

impl<'a, W> CountingWriter<'a, W> {
    /// Creates a new counting writer wrapping `inner`.
    const fn new(inner: &'a mut W, max_bytes: Option<usize>) -> Self {
        Self {
            inner,
            bytes_written: 0,
            max_bytes,
            overflowed: false,
        }
    }

    /// Returns the total number of bytes written (or attempted, if
    /// overflowed) so far.
    const fn bytes_written(&self) -> usize {
        self.bytes_written
    }

    /// Returns `true` if a write was rejected because the output
    /// size limit was exceeded.
    const fn overflowed(&self) -> bool {
        self.overflowed
    }
}

impl<W: fmt::Write> fmt::Write for CountingWriter<'_, W> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        // Fast path: once overflowed, reject immediately without
        // touching the inner writer or updating bytes_written.
        if self.overflowed {
            return Err(fmt::Error);
        }

        let new_total = self.bytes_written.saturating_add(s.len());
        if let Some(max) = self.max_bytes {
            if new_total > max {
                // Record the would-be total so the caller can report it,
                // and flag that we hit the limit (as opposed to a genuine
                // I/O error from the underlying writer).
                self.bytes_written = new_total;
                self.overflowed = true;
                return Err(fmt::Error);
            }
        }
        self.inner.write_str(s)?;
        self.bytes_written = new_total;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write;

    use super::*;

    fn file(path: &str, content: &str) -> VirtualFile {
        VirtualFile::new_unchecked(path, content)
    }

    fn default_processor() -> WasmProcessor {
        WasmProcessor::default()
    }

    mod prop {
        use super::*;
        use crate::wasm::test_strategies;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn process_never_panics(
                files in test_strategies::virtual_files(50),
                opts in test_strategies::processor_options(),
            ) {
                let proc = WasmProcessor::new(opts);
                // Must not panic — errors are fine.
                let _ = proc.process_to_string(files);
            }

            #[test]
            fn processed_plus_skipped_plus_truncated_equals_input(
                files in test_strategies::virtual_files(50),
                opts in test_strategies::processor_options(),
            ) {
                let total = files.len();
                let proc = WasmProcessor::new(opts);
                let mut sink = String::new();
                if let Ok(result) = proc.process(files, &mut sink) {
                    prop_assert_eq!(result.total_files(), total);
                }
            }

            #[test]
            fn output_is_deterministic(
                files in test_strategies::virtual_files(30),
                opts in test_strategies::processor_options(),
            ) {
                let proc = WasmProcessor::new(opts);
                let a = proc.process_to_string(files.clone());
                let b = proc.process_to_string(files);
                match (a, b) {
                    (Ok((out_a, res_a)), Ok((out_b, res_b))) => {
                        prop_assert_eq!(out_a, out_b);
                        prop_assert_eq!(res_a, res_b);
                    }
                    (Err(_), Err(_)) => {} // Both errored — fine.
                    (a, b) => {
                        prop_assert!(
                            false,
                            "divergent results: {a:?} vs {b:?}"
                        );
                    }
                }
            }

            #[test]
            fn max_files_respected(
                files in test_strategies::virtual_files(50),
            ) {
                let limit = 5;
                let opts = ProcessorOptions::builder()
                    .max_files(limit)
                    .include_dotfiles(true)
                    .build()
                    .unwrap();
                let proc = WasmProcessor::new(opts);
                let mut sink = String::new();
                if let Ok(result) = proc.process(files, &mut sink) {
                    prop_assert!(result.files_processed <= limit);
                }
            }

            #[test]
            fn process_result_is_copy(
                files in test_strategies::virtual_files(10),
            ) {
                let proc = WasmProcessor::default();
                let mut sink = String::new();
                if let Ok(result) = proc.process(files, &mut sink) {
                    // Copy semantics: use after implicit copy.
                    let a = result;
                    let b = result;
                    prop_assert_eq!(a, b);
                }
            }

            #[test]
            fn truncation_counted_separately_from_filtering(
                files in test_strategies::virtual_files(50),
            ) {
                let limit = 3;
                let opts = ProcessorOptions::builder()
                    .max_files(limit)
                    .include_dotfiles(true)
                    .build()
                    .unwrap();
                let proc = WasmProcessor::new(opts);
                let mut sink = String::new();
                if let Ok(result) = proc.process(files.clone(), &mut sink) {
                    // With include_dotfiles=true and no extension/glob filters,
                    // files_skipped should be 0 — everything that didn't make
                    // it in should be in files_truncated.
                    prop_assert_eq!(result.files_skipped, 0);
                    if files.len() > limit {
                        prop_assert_eq!(result.files_truncated, files.len() - limit);
                    }
                    prop_assert_eq!(result.total_files(), files.len());
                }
            }
        }
    }

    #[test]
    fn default_processor_uses_markdown() {
        let proc = WasmProcessor::default();
        assert_eq!(proc.options().output_format(), OutputFormat::Markdown);
    }

    #[test]
    fn from_options_is_equivalent_to_new() {
        let opts = ProcessorOptions::builder()
            .output_format(OutputFormat::Tree)
            .build()
            .unwrap();
        let via_new = WasmProcessor::new(opts.clone());
        let via_from = WasmProcessor::from(opts);
        assert_eq!(
            via_new.options().output_format(),
            via_from.options().output_format()
        );
    }

    #[test]
    fn markdown_single_file() {
        let proc = default_processor();
        let (result, meta) = proc
            .process_to_string(vec![file("src/main.rs", "fn main() {}\n")])
            .unwrap();

        assert_eq!(result, "## `src/main.rs`\n\n```rs\nfn main() {}\n```\n");
        assert_eq!(meta.files_processed, 1);
        assert_eq!(meta.files_skipped, 0);
        assert_eq!(meta.files_truncated, 0);
    }

    #[test]
    fn markdown_multiple_files_sorted() {
        let proc = default_processor();
        let (result, _) = proc
            .process_to_string(vec![file("b.py", "pass\n"), file("a.rs", "fn a() {}\n")])
            .unwrap();

        // Files should be sorted: a.rs before b.py.
        assert!(result.starts_with("## `a.rs`"));
        assert!(result.contains("## `b.py`"));
    }

    #[test]
    fn markdown_adds_trailing_newline() {
        let proc = default_processor();
        let (result, _) = proc
            .process_to_string(vec![file("f.txt", "no newline")])
            .unwrap();

        assert!(result.contains("no newline\n```"));
    }

    #[test]
    fn markdown_escapes_backtick_content() {
        let proc = default_processor();
        let content_with_fence = "before\n```\ninner\n```\nafter\n";
        let (result, _) = proc
            .process_to_string(vec![file("tricky.md", content_with_fence)])
            .unwrap();

        // The outer fence must be longer than the inner triple-backtick
        // runs to produce valid CommonMark.
        assert!(
            result.contains("````"),
            "fence should be at least 4 backticks when content contains ```"
        );
        // The content should appear verbatim inside the fence.
        assert!(result.contains(content_with_fence));
    }

    #[test]
    fn markdown_escapes_long_backtick_runs() {
        let proc = default_processor();
        let content = "some ```````` long run\n";
        let (result, _) = proc
            .process_to_string(vec![file("f.txt", content)])
            .unwrap();

        // 8 backticks in content → fence must be at least 9.
        assert!(
            result.contains("`````````"),
            "fence should be at least 9 backticks: {result}"
        );
    }

    #[test]
    fn tree_output() {
        let opts = ProcessorOptions::builder()
            .output_format(OutputFormat::Tree)
            .root_label("project")
            .build()
            .unwrap();
        let proc = WasmProcessor::new(opts);

        let (result, _) = proc
            .process_to_string(vec![
                file("src/main.rs", ""),
                file("src/lib.rs", ""),
                file("Cargo.toml", ""),
            ])
            .unwrap();

        assert!(result.starts_with("project\n"));
        assert!(result.contains("Cargo.toml"));
        assert!(result.contains("src/"));
        assert!(result.contains("main.rs"));
        assert!(result.contains("lib.rs"));
    }

    #[test]
    fn filters_dotfiles_by_default() {
        let proc = default_processor();
        let (result, meta) = proc
            .process_to_string(vec![
                file(".gitignore", ""),
                file("src/.hidden", ""),
                file("visible.rs", "fn v() {}\n"),
            ])
            .unwrap();

        assert!(!result.contains(".gitignore"));
        assert!(!result.contains(".hidden"));
        assert!(result.contains("visible.rs"));
        assert_eq!(meta.files_processed, 1);
        assert_eq!(meta.files_skipped, 2);
        assert_eq!(meta.files_truncated, 0);
    }

    #[test]
    fn output_too_large_error() {
        let opts = ProcessorOptions::builder()
            .max_output_bytes(10)
            .build()
            .unwrap();
        let proc = WasmProcessor::new(opts);

        let result = proc.process_to_string(vec![file(
            "big.txt",
            "this content is definitely longer than 10 bytes",
        )]);

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, WasmError::OutputTooLarge { .. }),
            "expected OutputTooLarge, got: {err}"
        );
    }

    #[test]
    fn process_result_counts() {
        let opts = ProcessorOptions::builder()
            .ignore_extensions(["lock"])
            .build()
            .unwrap();
        let proc = WasmProcessor::new(opts);

        let mut output = String::new();
        let result = proc
            .process(
                vec![
                    file("keep.rs", "fn keep() {}\n"),
                    file("skip.lock", ""),
                    file("also_keep.py", "pass\n"),
                ],
                &mut output,
            )
            .unwrap();

        assert_eq!(result.files_processed, 2);
        assert_eq!(result.files_skipped, 1);
        assert_eq!(result.files_truncated, 0);
        assert_eq!(result.total_files(), 3);
        assert!(result.output_bytes > 0);
    }

    #[test]
    fn process_result_distinguishes_skipped_from_truncated() {
        let opts = ProcessorOptions::builder()
            .ignore_extensions(["lock"])
            .max_files(1)
            .build()
            .unwrap();
        let proc = WasmProcessor::new(opts);

        let mut output = String::new();
        let result = proc
            .process(
                vec![
                    file("a.rs", "fn a() {}\n"),
                    file("b.rs", "fn b() {}\n"),
                    file("c.lock", ""),
                ],
                &mut output,
            )
            .unwrap();

        // c.lock filtered by extension, one of a.rs/b.rs truncated by max_files
        assert_eq!(result.files_processed, 1);
        assert_eq!(result.files_skipped, 1); // c.lock
        assert_eq!(result.files_truncated, 1); // whichever of a.rs/b.rs didn't make the cut
        assert_eq!(result.total_files(), 3);
    }

    #[test]
    fn processor_exposes_options() {
        let opts = ProcessorOptions::builder()
            .output_format(OutputFormat::Tree)
            .include_dotfiles(true)
            .build()
            .unwrap();
        let proc = WasmProcessor::new(opts);

        assert_eq!(proc.options().output_format(), OutputFormat::Tree);
        assert!(proc.options().include_dotfiles());
    }

    #[test]
    fn glob_matches_normalized_paths() {
        // A file with `./` prefix should still match a glob without it.
        let opts = ProcessorOptions::builder()
            .ignore_globs(["src/**"])
            .include_dotfiles(true)
            .build()
            .unwrap();
        let proc = WasmProcessor::new(opts);

        let (result, meta) = proc
            .process_to_string(vec![
                file("./src/main.rs", "fn main() {}"),
                file("README.md", "# Hello"),
            ])
            .unwrap();

        assert!(!result.contains("main.rs"));
        assert!(result.contains("README.md"));
        assert_eq!(meta.files_processed, 1);
        assert_eq!(meta.files_skipped, 1);
        assert_eq!(meta.files_truncated, 0);
    }

    #[test]
    fn process_result_serde_round_trip() {
        let result = ProcessResult {
            files_processed: 42,
            files_skipped: 7,
            files_truncated: 3,
            output_bytes: 12345,
        };
        let json = serde_json::to_string(&result).unwrap();
        let recovered: ProcessResult = serde_json::from_str(&json).unwrap();
        assert_eq!(result, recovered);
    }

    #[test]
    fn empty_input_produces_empty_output() {
        let proc = default_processor();
        let (output, meta) = proc.process_to_string(Vec::new()).unwrap();
        assert!(output.is_empty());
        assert_eq!(meta.files_processed, 0);
        assert_eq!(meta.files_skipped, 0);
        assert_eq!(meta.files_truncated, 0);
        assert_eq!(meta.output_bytes, 0);
    }

    #[test]
    fn counting_writer_short_circuits_after_overflow() {
        let mut buf = String::new();
        let mut writer = CountingWriter::new(&mut buf, Some(5));

        // First write: 6 bytes > 5 limit → overflow.
        assert!(writer.write_str("abcdef").is_err());
        assert!(writer.overflowed());
        let size_at_overflow = writer.bytes_written();

        // Second write: should short-circuit without changing
        // bytes_written or touching the inner buffer.
        assert!(writer.write_str("more").is_err());
        assert_eq!(
            writer.bytes_written(),
            size_at_overflow,
            "bytes_written must not change after overflow"
        );
        assert!(
            buf.is_empty(),
            "inner writer must not receive data after overflow"
        );
    }

    #[test]
    fn counting_writer_no_limit() {
        let mut buf = String::new();
        let mut writer = CountingWriter::new(&mut buf, None);
        writer.write_str("hello").unwrap();
        writer.write_str(" world").unwrap();
        assert_eq!(writer.bytes_written(), 11);
        assert!(!writer.overflowed());
        assert_eq!(buf, "hello world");
    }

    #[test]
    fn counting_writer_exact_limit() {
        let mut buf = String::new();
        let mut writer = CountingWriter::new(&mut buf, Some(5));
        writer.write_str("hello").unwrap();
        assert_eq!(writer.bytes_written(), 5);
        assert!(!writer.overflowed());
        assert_eq!(buf, "hello");
    }
}