forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

bitsink.rs71 lines, 1.6 KiBHistoryRawDownload
1//! `flacenc::bitsink`: where a written stream lands.
2
3use std::convert::Infallible;
4
5/// Somewhere bits can be written.
6///
7/// Only the part the replica needs: it constructs a [`ByteSink`], hands it to
8/// `Stream::write` and reads the bytes back.
9pub trait BitSink: Sized {
10 /// What writing can fail with.
11 type Error: std::error::Error;
12
13 /// Append whole bytes.
14 fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
15
16 /// Bits written so far.
17 fn bit_len(&self) -> usize;
18}
19
20/// A `Vec<u8>` sink — `flacenc::bitsink::ByteSink`.
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub struct ByteSink {
23 storage: Vec<u8>,
24}
25
26impl ByteSink {
27 /// An empty sink.
28 pub fn new() -> Self {
29 ByteSink::default()
30 }
31
32 /// An empty sink with room for `bits`.
33 pub fn with_capacity(bits: usize) -> Self {
34 ByteSink {
35 storage: Vec::with_capacity(bits.div_ceil(8)),
36 }
37 }
38
39 /// The bytes written so far.
40 pub fn as_slice(&self) -> &[u8] {
41 &self.storage
42 }
43
44 /// Take the bytes.
45 pub fn into_inner(self) -> Vec<u8> {
46 self.storage
47 }
48
49 /// Bytes written so far.
50 pub fn len(&self) -> usize {
51 self.storage.len()
52 }
53
54 /// True when nothing has been written.
55 pub fn is_empty(&self) -> bool {
56 self.storage.is_empty()
57 }
58}
59
60impl BitSink for ByteSink {
61 type Error = Infallible;
62
63 fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Infallible> {
64 self.storage.extend_from_slice(bytes);
65 Ok(())
66 }
67
68 fn bit_len(&self) -> usize {
69 self.storage.len() * 8
70 }
71}