|
| 1 | +use std::fmt::{self, Write}; |
| 2 | +use test::{black_box, Bencher}; |
| 3 | + |
| 4 | +#[derive(Default)] |
| 5 | +struct CountingWriter { |
| 6 | + buf: String, |
| 7 | + write_calls: usize, |
| 8 | +} |
| 9 | + |
| 10 | +impl Write for CountingWriter { |
| 11 | + fn write_str(&mut self, s: &str) -> fmt::Result { |
| 12 | + self.buf.push_str(s); |
| 13 | + self.write_calls += 1; |
| 14 | + Ok(()) |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +fn run_fmt(s: &str, expected: &str, expected_write_calls: usize) { |
| 19 | + let mut w = CountingWriter::default(); |
| 20 | + |
| 21 | + write!(&mut w, "{:?}", black_box(s)).unwrap(); |
| 22 | + assert_eq!(s.len(), 64); |
| 23 | + assert_eq!(w.buf, expected); |
| 24 | + assert_eq!(w.write_calls, expected_write_calls); |
| 25 | +} |
| 26 | + |
| 27 | +#[bench] |
| 28 | +fn ascii_only(b: &mut Bencher) { |
| 29 | + b.iter(|| { |
| 30 | + run_fmt( |
| 31 | + "just a bit of ascii text that has no escapes. 64 bytes exactly!!", |
| 32 | + r#""just a bit of ascii text that has no escapes. 64 bytes exactly!!""#, |
| 33 | + 3, |
| 34 | + ); |
| 35 | + }); |
| 36 | +} |
| 37 | + |
| 38 | +#[bench] |
| 39 | +fn ascii_escapes(b: &mut Bencher) { |
| 40 | + b.iter(|| { |
| 41 | + run_fmt( |
| 42 | + "some\tmore\tascii\ttext\nthis time with some \"escapes\", also 64 byte", |
| 43 | + r#""some\tmore\tascii\ttext\nthis time with some \"escapes\", also 64 byte""#, |
| 44 | + 21, |
| 45 | + ); |
| 46 | + }); |
| 47 | +} |
| 48 | + |
| 49 | +#[bench] |
| 50 | +fn some_unicode(b: &mut Bencher) { |
| 51 | + b.iter(|| { |
| 52 | + run_fmt( |
| 53 | + "egy kis szöveg néhány unicode betűvel. legyen ez is 64 byte.", |
| 54 | + r#""egy kis szöveg néhány unicode betűvel. legyen ez is 64 byte.""#, |
| 55 | + 3, |
| 56 | + ); |
| 57 | + }); |
| 58 | +} |
| 59 | + |
| 60 | +#[bench] |
| 61 | +fn mostly_unicode(b: &mut Bencher) { |
| 62 | + b.iter(|| { |
| 63 | + run_fmt("предложение из кириллических букв.", r#""предложение из кириллических букв.""#, 3); |
| 64 | + }); |
| 65 | +} |
| 66 | + |
| 67 | +#[bench] |
| 68 | +fn mixed(b: &mut Bencher) { |
| 69 | + b.iter(|| { |
| 70 | + run_fmt( |
| 71 | + "\"❤️\"\n\"hűha ez betű\"\n\"кириллических букв\".", |
| 72 | + r#""\"❤\u{fe0f}\"\n\"hűha ez betű\"\n\"кириллических букв\".""#, |
| 73 | + 36, |
| 74 | + ); |
| 75 | + }); |
| 76 | +} |
0 commit comments