File: debug.rs

package info (click to toggle)
rustc-web 1.85.0%2Bdfsg3-1~deb12u3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 1,759,988 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,056; lisp: 29; perl: 29; ruby: 19; sql: 11
file content (80 lines) | stat: -rw-r--r-- 2,433 bytes parent folder | download | duplicates (4)
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
//! This primarily benchmarks `impl Debug for str`,
//! and it also explicitly tests that we minimizes calls to the underlying `Write`r.
//! While that is an implementation detail and there are no guarantees about it,
//! we should still try to minimize those calls over time rather than regress them.

use std::fmt::{self, Write};

use test::{Bencher, black_box};

#[derive(Default)]
struct CountingWriter {
    buf: String,
    write_calls: usize,
}

impl Write for CountingWriter {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.buf.push_str(s);
        self.write_calls += 1;
        Ok(())
    }
}

fn assert_fmt(s: &str, expected: &str, expected_write_calls: usize) {
    let mut w = CountingWriter::default();

    write!(&mut w, "{s:?}").unwrap();
    assert_eq!(s.len(), 64);
    assert_eq!(w.buf, expected);
    assert_eq!(w.write_calls, expected_write_calls);
}

#[bench]
fn ascii_only(b: &mut Bencher) {
    let s = "just a bit of ascii text that has no escapes. 64 bytes exactly!!";
    assert_fmt(s, r#""just a bit of ascii text that has no escapes. 64 bytes exactly!!""#, 3);
    b.iter(|| {
        black_box(format!("{:?}", black_box(s)));
    });
}

#[bench]
fn ascii_escapes(b: &mut Bencher) {
    let s = "some\tmore\tascii\ttext\nthis time with some \"escapes\", also 64 byte";
    assert_fmt(
        s,
        r#""some\tmore\tascii\ttext\nthis time with some \"escapes\", also 64 byte""#,
        15,
    );
    b.iter(|| {
        black_box(format!("{:?}", black_box(s)));
    });
}

#[bench]
fn some_unicode(b: &mut Bencher) {
    let s = "egy kis szöveg néhány unicode betűvel. legyen ez is 64 byte.";
    assert_fmt(s, r#""egy kis szöveg néhány unicode betűvel. legyen ez is 64 byte.""#, 3);
    b.iter(|| {
        black_box(format!("{:?}", black_box(s)));
    });
}

#[bench]
fn mostly_unicode(b: &mut Bencher) {
    let s = "предложение из кириллических букв.";
    assert_fmt(s, r#""предложение из кириллических букв.""#, 3);
    b.iter(|| {
        black_box(format!("{:?}", black_box(s)));
    });
}

#[bench]
fn mixed(b: &mut Bencher) {
    let s = "\"❤️\"\n\"hűha ez betű\"\n\"кириллических букв\".";
    assert_fmt(s, r#""\"❤\u{fe0f}\"\n\"hűha ez betű\"\n\"кириллических букв\".""#, 21);
    b.iter(|| {
        black_box(format!("{:?}", black_box(s)));
    });
}