xref: /aosp_15_r20/external/bazelbuild-rules_rust/examples/sys/basic/src/main.rs (revision d4726bddaa87cc4778e7472feed243fa4b6c267f)
1 use bzip2::read::BzEncoder;
2 use bzip2::Compression;
3 use std::io::Read;
4 
main()5 fn main() {
6     let stdin = std::io::stdin();
7     let stdin = stdin.lock();
8     let mut raw_counter = CountingStream::new(stdin);
9 
10     let compressed_count = {
11         let compressor = BzEncoder::new(&mut raw_counter, Compression::Best);
12         let mut compressed_counter = CountingStream::new(compressor);
13         std::io::copy(&mut compressed_counter, &mut std::io::sink()).unwrap();
14         compressed_counter.count
15     };
16 
17     println!(
18         "Compressed {} to {} bytes",
19         raw_counter.count, compressed_count
20     );
21 }
22 
23 struct CountingStream<R: Read> {
24     stream: R,
25     count: usize,
26 }
27 
28 impl<R: Read> CountingStream<R> {
new(stream: R) -> Self29     fn new(stream: R) -> Self {
30         CountingStream { stream, count: 0 }
31     }
32 }
33 
34 impl<R: Read> Read for CountingStream<R> {
read(&mut self, buf: &mut [u8]) -> std::io::Result<usize>35     fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
36         let result = self.stream.read(buf);
37         if let Ok(read_bytes) = result {
38             self.count += read_bytes;
39         }
40         result
41     }
42 }
43