1 // Copyright 2024 The Bazel examples and tutorials Authors & Contributors. // All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15
16 use bzip2::read::BzEncoder;
17 use bzip2::Compression;
18 use std::io::Read;
19
main()20 fn main() {
21 let stdin = std::io::stdin();
22 let stdin = stdin.lock();
23 let mut raw_counter = CountingStream::new(stdin);
24
25 let compressed_count = {
26 let compressor = BzEncoder::new(&mut raw_counter, Compression::Best);
27 let mut compressed_counter = CountingStream::new(compressor);
28 std::io::copy(&mut compressed_counter, &mut std::io::sink()).unwrap();
29 compressed_counter.count
30 };
31
32 println!(
33 "Compressed {} to {} bytes",
34 raw_counter.count, compressed_count
35 );
36 }
37
38 struct CountingStream<R: Read> {
39 stream: R,
40 count: usize,
41 }
42
43 impl<R: Read> CountingStream<R> {
new(stream: R) -> Self44 fn new(stream: R) -> Self {
45 CountingStream { stream, count: 0 }
46 }
47 }
48
49 impl<R: Read> Read for CountingStream<R> {
read(&mut self, buf: &mut [u8]) -> std::io::Result<usize>50 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
51 let result = self.stream.read(buf);
52 if let Ok(read_bytes) = result {
53 self.count += read_bytes;
54 }
55 result
56 }
57 }