bitstream_io/
write.rs

1// Copyright 2017 Brian Langenberger
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Traits and implementations for writing bits to a stream.
10//!
11//! ## Example
12//!
13//! Writing the initial STREAMINFO block to a FLAC file,
14//! as documented in its
15//! [specification](https://xiph.org/flac/format.html#stream).
16//!
17//! ```
18//! use std::convert::TryInto;
19//! use std::io::Write;
20//! use std::num::NonZero;
21//! use bitstream_io::{BigEndian, BitWriter, BitWrite, ByteWriter, ByteWrite, LittleEndian, ToBitStream};
22//!
23//! #[derive(Debug, PartialEq, Eq)]
24//! struct BlockHeader {
25//!     last_block: bool,  // 1 bit
26//!     block_type: u8,    // 7 bits
27//!     block_size: u32,   // 24 bits
28//! }
29//!
30//! impl ToBitStream for BlockHeader {
31//!     type Error = std::io::Error;
32//!
33//!     fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> std::io::Result<()> {
34//!         w.write_bit(self.last_block)?;
35//!         w.write::<7, _>(self.block_type)?;
36//!         w.write::<24, _>(self.block_size)
37//!     }
38//! }
39//!
40//! #[derive(Debug, PartialEq, Eq)]
41//! struct Streaminfo {
42//!     minimum_block_size: u16,      // 16 bits
43//!     maximum_block_size: u16,      // 16 bits
44//!     minimum_frame_size: u32,      // 24 bits
45//!     maximum_frame_size: u32,      // 24 bits
46//!     sample_rate: u32,             // 20 bits
47//!     channels: NonZero<u8>,        // 3 bits
48//!     bits_per_sample: NonZero<u8>, // 5 bits
49//!     total_samples: u64,           // 36 bits
50//!     md5: [u8; 16],                // 16 bytes
51//! }
52//!
53//! impl ToBitStream for Streaminfo {
54//!     type Error = std::io::Error;
55//!
56//!     fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> std::io::Result<()> {
57//!         w.write_from(self.minimum_block_size)?;
58//!         w.write_from(self.maximum_block_size)?;
59//!         w.write::<24, _>(self.minimum_frame_size)?;
60//!         w.write::<24, _>(self.maximum_frame_size)?;
61//!         w.write::<20, _>(self.sample_rate)?;
62//!         w.write::<3,  _>(self.channels)?;
63//!         w.write::<5,  _>(self.bits_per_sample)?;
64//!         w.write::<36, _>(self.total_samples)?;
65//!         w.write_bytes(&self.md5)
66//!     }
67//! }
68//!
69//! #[derive(Debug, PartialEq, Eq)]
70//! struct VorbisComment {
71//!     vendor: String,
72//!     comment: Vec<String>,
73//! }
74//!
75//! impl VorbisComment {
76//!     fn len(&self) -> usize {
77//!         4 + self.vendor.len() + 4 + self.comment.iter().map(|c| 4 + c.len()).sum::<usize>()
78//!     }
79//!
80//!     fn write<W: std::io::Write>(&self, w: &mut ByteWriter<W, LittleEndian>) -> std::io::Result<()> {
81//!         use std::convert::TryInto;
82//!
83//!         fn write_entry<W: std::io::Write>(
84//!             w: &mut ByteWriter<W, LittleEndian>,
85//!             s: &str,
86//!         ) -> std::io::Result<()> {
87//!             w.write::<u32>(s.len().try_into().unwrap())?;
88//!             w.write_bytes(s.as_bytes())
89//!         }
90//!
91//!         write_entry(w, &self.vendor)?;
92//!         w.write::<u32>(self.comment.len().try_into().unwrap())?;
93//!         self.comment.iter().try_for_each(|s| write_entry(w, s))
94//!     }
95//! }
96//!
97//! let mut flac: Vec<u8> = Vec::new();
98//!
99//! let mut writer = BitWriter::endian(&mut flac, BigEndian);
100//!
101//! // stream marker
102//! writer.write_bytes(b"fLaC").unwrap();
103//!
104//! // metadata block header
105//! writer.build(&BlockHeader { last_block: false, block_type: 0, block_size: 34 }).unwrap();
106//!
107//! // STREAMINFO block
108//! writer.build(&Streaminfo {
109//!     minimum_block_size: 4096,
110//!     maximum_block_size: 4096,
111//!     minimum_frame_size: 1542,
112//!     maximum_frame_size: 8546,
113//!     sample_rate: 44100,
114//!     channels: NonZero::new(2).unwrap(),
115//!     bits_per_sample: NonZero::new(16).unwrap(),
116//!     total_samples: 304844,
117//!     md5: *b"\xFA\xF2\x69\x2F\xFD\xEC\x2D\x5B\x30\x01\x76\xB4\x62\x88\x7D\x92",
118//! }).unwrap();
119//!
120//! let comment = VorbisComment {
121//!     vendor: "reference libFLAC 1.1.4 20070213".to_string(),
122//!     comment: vec![
123//!         "title=2ch 44100  16bit".to_string(),
124//!         "album=Test Album".to_string(),
125//!         "artist=Assorted".to_string(),
126//!         "tracknumber=1".to_string(),
127//!     ],
128//! };
129//!
130//! // metadata block header
131//! writer.build(
132//!     &BlockHeader {
133//!         last_block: false,
134//!         block_type: 4,
135//!         block_size: comment.len().try_into().unwrap(),
136//!     }
137//! ).unwrap();
138//!
139//! // VORBIS_COMMENT block (little endian)
140//! comment.write(&mut ByteWriter::new(writer.writer().unwrap())).unwrap();
141//!
142//! assert_eq!(flac, vec![0x66,0x4c,0x61,0x43,0x00,0x00,0x00,0x22,
143//!                       0x10,0x00,0x10,0x00,0x00,0x06,0x06,0x00,
144//!                       0x21,0x62,0x0a,0xc4,0x42,0xf0,0x00,0x04,
145//!                       0xa6,0xcc,0xfa,0xf2,0x69,0x2f,0xfd,0xec,
146//!                       0x2d,0x5b,0x30,0x01,0x76,0xb4,0x62,0x88,
147//!                       0x7d,0x92,0x04,0x00,0x00,0x7a,0x20,0x00,
148//!                       0x00,0x00,0x72,0x65,0x66,0x65,0x72,0x65,
149//!                       0x6e,0x63,0x65,0x20,0x6c,0x69,0x62,0x46,
150//!                       0x4c,0x41,0x43,0x20,0x31,0x2e,0x31,0x2e,
151//!                       0x34,0x20,0x32,0x30,0x30,0x37,0x30,0x32,
152//!                       0x31,0x33,0x04,0x00,0x00,0x00,0x16,0x00,
153//!                       0x00,0x00,0x74,0x69,0x74,0x6c,0x65,0x3d,
154//!                       0x32,0x63,0x68,0x20,0x34,0x34,0x31,0x30,
155//!                       0x30,0x20,0x20,0x31,0x36,0x62,0x69,0x74,
156//!                       0x10,0x00,0x00,0x00,0x61,0x6c,0x62,0x75,
157//!                       0x6d,0x3d,0x54,0x65,0x73,0x74,0x20,0x41,
158//!                       0x6c,0x62,0x75,0x6d,0x0f,0x00,0x00,0x00,
159//!                       0x61,0x72,0x74,0x69,0x73,0x74,0x3d,0x41,
160//!                       0x73,0x73,0x6f,0x72,0x74,0x65,0x64,0x0d,
161//!                       0x00,0x00,0x00,0x74,0x72,0x61,0x63,0x6b,
162//!                       0x6e,0x75,0x6d,0x62,0x65,0x72,0x3d,0x31]);
163//! ```
164
165#![warn(missing_docs)]
166
167#[cfg(not(feature = "std"))]
168use core2::io;
169
170use alloc::vec::Vec;
171use core::{
172    convert::{From, TryFrom, TryInto},
173    fmt,
174};
175#[cfg(feature = "std")]
176use std::io;
177
178use super::{
179    BitCount, Endianness, Integer, Numeric, PhantomData, Primitive, SignedBitCount, SignedInteger,
180    UnsignedInteger,
181};
182
183/// For writing bit values to an underlying stream in a given endianness.
184///
185/// Because this only writes whole bytes to the underlying stream,
186/// it is important that output is byte-aligned before the bitstream
187/// writer's lifetime ends.
188/// **Partial bytes will be lost** if the writer is disposed of
189/// before they can be written.
190pub struct BitWriter<W: io::Write, E: Endianness> {
191    // our underlying writer
192    writer: W,
193    // our partial byte
194    value: u8,
195    // the number of bits in our partial byte
196    bits: u32,
197    // a container for our endianness
198    phantom: PhantomData<E>,
199}
200
201impl<W: io::Write, E: Endianness> BitWriter<W, E> {
202    /// Wraps a BitWriter around something that implements `Write`
203    pub fn new(writer: W) -> BitWriter<W, E> {
204        BitWriter {
205            writer,
206            value: 0,
207            bits: 0,
208            phantom: PhantomData,
209        }
210    }
211
212    /// Wraps a BitWriter around something that implements `Write`
213    /// with the given endianness.
214    pub fn endian(writer: W, _endian: E) -> BitWriter<W, E> {
215        BitWriter {
216            writer,
217            value: 0,
218            bits: 0,
219            phantom: PhantomData,
220        }
221    }
222
223    /// Unwraps internal writer and disposes of BitWriter.
224    ///
225    /// # Warning
226    ///
227    /// Any unwritten partial bits are discarded.
228    #[inline]
229    pub fn into_writer(self) -> W {
230        self.writer
231    }
232
233    /// If stream is byte-aligned, provides mutable reference
234    /// to internal writer.  Otherwise returns `None`
235    #[inline]
236    pub fn writer(&mut self) -> Option<&mut W> {
237        if BitWrite::byte_aligned(self) {
238            Some(&mut self.writer)
239        } else {
240            None
241        }
242    }
243
244    /// Returns byte-aligned mutable reference to internal writer.
245    ///
246    /// Bytes aligns stream if it is not already aligned.
247    ///
248    /// # Errors
249    ///
250    /// Passes along any I/O error from the underlying stream.
251    #[inline]
252    pub fn aligned_writer(&mut self) -> io::Result<&mut W> {
253        BitWrite::byte_align(self)?;
254        Ok(&mut self.writer)
255    }
256
257    /// Converts `BitWriter` to `ByteWriter` in the same endianness.
258    ///
259    /// # Warning
260    ///
261    /// Any written partial bits are discarded.
262    #[inline]
263    pub fn into_bytewriter(self) -> ByteWriter<W, E> {
264        ByteWriter::new(self.into_writer())
265    }
266
267    /// If stream is byte-aligned, provides temporary `ByteWriter`
268    /// in the same endianness.  Otherwise returns `None`
269    ///
270    /// # Warning
271    ///
272    /// Any unwritten bits left over when `ByteWriter` is dropped are lost.
273    #[inline]
274    pub fn bytewriter(&mut self) -> Option<ByteWriter<&mut W, E>> {
275        self.writer().map(ByteWriter::new)
276    }
277
278    /// Flushes output stream to disk, if necessary.
279    /// Any partial bytes are not flushed.
280    ///
281    /// # Errors
282    ///
283    /// Passes along any errors from the underlying stream.
284    #[inline(always)]
285    pub fn flush(&mut self) -> io::Result<()> {
286        self.writer.flush()
287    }
288}
289
290/// A trait for anything that can write a variable number of
291/// potentially un-aligned values to an output stream
292pub trait BitWrite {
293    /// Writes a single bit to the stream.
294    /// `true` indicates 1, `false` indicates 0
295    ///
296    /// # Errors
297    ///
298    /// Passes along any I/O error from the underlying stream.
299    ///
300    /// # Examples
301    /// ```
302    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
303    ///
304    /// let mut w  = BitWriter::endian(vec![], BigEndian);
305    /// assert!(w.write_bit(true).is_ok());
306    /// assert!(w.write_bit(false).is_ok());
307    /// assert!(w.write_bit(false).is_ok());
308    /// assert!(w.write_bit(false).is_ok());
309    /// assert!(w.write_bit(true).is_ok());
310    /// assert!(w.write_bit(true).is_ok());
311    /// assert!(w.write_bit(true).is_ok());
312    /// assert!(w.write_bit(false).is_ok());
313    /// assert_eq!(w.into_writer(), &[0b1000_1110]);
314    /// ```
315    ///
316    /// ```
317    /// use bitstream_io::{BitWriter, BitWrite, LittleEndian};
318    ///
319    /// let mut w  = BitWriter::endian(vec![], LittleEndian);
320    /// assert!(w.write_bit(false).is_ok());
321    /// assert!(w.write_bit(true).is_ok());
322    /// assert!(w.write_bit(true).is_ok());
323    /// assert!(w.write_bit(true).is_ok());
324    /// assert!(w.write_bit(false).is_ok());
325    /// assert!(w.write_bit(false).is_ok());
326    /// assert!(w.write_bit(false).is_ok());
327    /// assert!(w.write_bit(true).is_ok());
328    /// assert_eq!(w.into_writer(), &[0b1000_1110]);
329    /// ```
330    #[inline]
331    fn write_bit(&mut self, bit: bool) -> io::Result<()> {
332        self.write_unsigned::<1, u8>(u8::from(bit))
333    }
334
335    /// Writes a signed or unsigned value to the stream using the given
336    /// const number of bits.
337    ///
338    /// # Errors
339    ///
340    /// Passes along any I/O error from the underlying stream.
341    /// Returns an error if the value is too large
342    /// to fit the given number of bits.
343    /// A compile-time error occurs if the given number of bits
344    /// is larger than the output type.
345    ///
346    /// # Examples
347    /// ```
348    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
349    ///
350    /// let mut w = BitWriter::endian(vec![], BigEndian);
351    /// // writing unsigned value is ok
352    /// assert!(w.write::<4, u8>(1).is_ok());
353    /// // writing signed value is ok
354    /// assert!(w.write::<4, i8>(-1).is_ok());
355    /// // writing an array of bits is ok too
356    /// assert!(w.write::<1, [bool; 4]>([true, false, true, true]).is_ok());
357    /// // writing an array of any Integer type is ok
358    /// assert!(w.write::<2, [u8; 2]>([0b11, 0b00]).is_ok());
359    /// // trying to write a value larger than 4 bits in 4 bits is an error
360    /// assert!(w.write::<4, u8>(u8::MAX).is_err());
361    ///
362    /// assert_eq!(w.into_writer(), &[0b0001_1111, 0b1011_11_00]);
363    /// ```
364    ///
365    /// ```rust,compile_fail
366    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
367    ///
368    /// let mut w = BitWriter::endian(vec![], BigEndian);
369    /// // trying to write 9 bits from a u8 is a compile-time error
370    /// w.write::<9, u8>(1);
371    /// ```
372    #[inline]
373    fn write<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
374    where
375        I: Integer,
376    {
377        Integer::write::<BITS, Self>(value, self)
378    }
379
380    /// Writes a signed or unsigned value to the stream using the given
381    /// number of bits.
382    ///
383    /// # Errors
384    ///
385    /// Passes along any I/O error from the underlying stream.
386    /// Returns an error if the input type is too small
387    /// to hold the given number of bits.
388    /// Returns an error if the value is too large
389    /// to fit the given number of bits.
390    ///
391    /// # Examples
392    /// ```
393    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
394    ///
395    /// let mut w = BitWriter::endian(vec![], BigEndian);
396    /// // writing unsigned value is ok
397    /// assert!(w.write_var::<u8>(4, 1).is_ok());
398    /// // writing signed value is also ok
399    /// assert!(w.write_var::<i8>(4, -1).is_ok());
400    /// assert_eq!(w.into_writer(), &[0b0001_1111]);
401    /// ```
402    ///
403    /// ```
404    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
405    ///
406    /// let mut w = BitWriter::endian(vec![], BigEndian);
407    /// // writing a value larger than 4 bits in 4 bits is a runtime error
408    /// assert!(w.write_var::<u8>(4, u8::MAX).is_err());
409    /// // writing 9 bits from a u8 is also a runtime error
410    /// assert!(w.write_var::<u8>(9, 0).is_err());
411    /// ```
412    #[inline]
413    fn write_var<I>(&mut self, bits: u32, value: I) -> io::Result<()>
414    where
415        I: Integer,
416    {
417        self.write_counted(BitCount::unknown(bits), value)
418    }
419
420    /// Writes an unsigned value to the stream using the given
421    /// const number of bits.
422    ///
423    /// # Errors
424    ///
425    /// Passes along any I/O error from the underlying stream.
426    /// Returns an error if the value is too large
427    /// to fit the given number of bits.
428    /// A compile-time error occurs if the given number of bits
429    /// is larger than the output type.
430    ///
431    /// # Examples
432    /// ```
433    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
434    ///
435    /// let mut writer = BitWriter::endian(vec![], BigEndian);
436    /// writer.write_unsigned::<1, u8>(0b1).unwrap();
437    /// writer.write_unsigned::<2, u8>(0b01).unwrap();
438    /// writer.write_unsigned::<5, u8>(0b10111).unwrap();
439    /// assert_eq!(writer.into_writer(), [0b1_01_10111]);
440    /// ```
441    ///
442    /// ```
443    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
444    ///
445    /// let mut writer = BitWriter::endian(vec![], LittleEndian);
446    /// writer.write_unsigned::<1, u8>(0b1).unwrap();
447    /// writer.write_unsigned::<2, u8>(0b11).unwrap();
448    /// writer.write_unsigned::<5, u8>(0b10110).unwrap();
449    /// assert_eq!(writer.into_writer(), [0b10110_11_1]);
450    /// ```
451    ///
452    /// ```rust,compile_fail
453    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
454    ///
455    /// let mut writer = BitWriter::endian(vec![], BigEndian);
456    /// // trying to write 9 bits from a u8 is a compile-time error
457    /// writer.write_unsigned::<9, u8>(1);
458    /// ```
459    ///
460    /// ```
461    /// use std::io::{Write, sink};
462    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
463    ///
464    /// let mut w = BitWriter::endian(sink(), BigEndian);
465    /// assert!(w.write_unsigned::<1, u8>(2).is_err());    // can't write   2 in 1 bit
466    /// assert!(w.write_unsigned::<2, u8>(4).is_err());    // can't write   4 in 2 bits
467    /// assert!(w.write_unsigned::<3, u8>(8).is_err());    // can't write   8 in 3 bits
468    /// assert!(w.write_unsigned::<4, u8>(16).is_err());   // can't write  16 in 4 bits
469    /// ```
470    #[inline]
471    fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
472    where
473        U: UnsignedInteger,
474    {
475        self.write_unsigned_var(BITS, value)
476    }
477
478    /// Writes an unsigned value to the stream using the given
479    /// number of bits.
480    ///
481    /// # Errors
482    ///
483    /// Passes along any I/O error from the underlying stream.
484    /// Returns an error if the input type is too small
485    /// to hold the given number of bits.
486    /// Returns an error if the value is too large
487    /// to fit the given number of bits.
488    ///
489    /// # Examples
490    /// ```
491    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
492    ///
493    /// let mut writer = BitWriter::endian(vec![], BigEndian);
494    /// writer.write_unsigned_var::<u8>(1, 0b1).unwrap();
495    /// writer.write_unsigned_var::<u8>(2, 0b01).unwrap();
496    /// writer.write_unsigned_var::<u8>(5, 0b10111).unwrap();
497    /// assert_eq!(writer.into_writer(), [0b1_01_10111]);
498    /// ```
499    ///
500    /// ```
501    /// use std::io::Write;
502    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
503    ///
504    /// let mut writer = BitWriter::endian(vec![], LittleEndian);
505    /// writer.write_unsigned_var::<u8>(1, 0b1).unwrap();
506    /// writer.write_unsigned_var::<u8>(2, 0b11).unwrap();
507    /// writer.write_unsigned_var::<u8>(5, 0b10110).unwrap();
508    /// assert_eq!(writer.into_writer(), [0b10110_11_1]);
509    /// ```
510    ///
511    /// ```
512    /// use std::io::{Write, sink};
513    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
514    ///
515    /// let mut w = BitWriter::endian(sink(), BigEndian);
516    /// assert!(w.write_unsigned_var::<u8>(9, 0).is_err());    // can't write  u8 in 9 bits
517    /// assert!(w.write_unsigned_var::<u16>(17, 0).is_err());  // can't write u16 in 17 bits
518    /// assert!(w.write_unsigned_var::<u32>(33, 0).is_err());  // can't write u32 in 33 bits
519    /// assert!(w.write_unsigned_var::<u64>(65, 0).is_err());  // can't write u64 in 65 bits
520    /// assert!(w.write_unsigned_var::<u8>(1, 2).is_err());    // can't write   2 in 1 bit
521    /// assert!(w.write_unsigned_var::<u8>(2, 4).is_err());    // can't write   4 in 2 bits
522    /// assert!(w.write_unsigned_var::<u8>(3, 8).is_err());    // can't write   8 in 3 bits
523    /// assert!(w.write_unsigned_var::<u8>(4, 16).is_err());   // can't write  16 in 4 bits
524    /// ```
525    fn write_unsigned_var<U>(&mut self, bits: u32, value: U) -> io::Result<()>
526    where
527        U: UnsignedInteger,
528    {
529        self.write_unsigned_counted(BitCount::unknown(bits), value)
530    }
531
532    /// Writes a twos-complement signed value to the stream
533    /// with the given const number of bits.
534    ///
535    /// # Errors
536    ///
537    /// Passes along any I/O error from the underlying stream.
538    /// Returns an error if the value is too large
539    /// to fit the given number of bits.
540    /// A compile-time error occurs if the number of bits is 0,
541    /// since one bit is always needed for the sign.
542    /// A compile-time error occurs if the given number of bits
543    /// is larger than the output type.
544    ///
545    /// # Examples
546    /// ```
547    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
548    ///
549    /// let mut writer = BitWriter::endian(vec![], BigEndian);
550    /// writer.write_signed::<4, i8>(-5).unwrap();
551    /// writer.write_signed::<4, i8>(7).unwrap();
552    /// assert_eq!(writer.into_writer(), [0b10110111]);
553    /// ```
554    ///
555    /// ```
556    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
557    ///
558    /// let mut writer = BitWriter::endian(vec![], LittleEndian);
559    /// writer.write_signed::<4, i8>(7).unwrap();
560    /// writer.write_signed::<4, i8>(-5).unwrap();
561    /// assert_eq!(writer.into_writer(), [0b10110111]);
562    /// ```
563    ///
564    /// ```
565    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
566    ///
567    /// let mut writer = BitWriter::endian(vec![], LittleEndian);
568    /// // writing a value too large for 4 bits in 4 bits is a runtime error
569    /// assert!(writer.write_signed::<4, i8>(i8::MAX).is_err());
570    /// ```
571    ///
572    /// ```rust,compile_fail
573    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
574    ///
575    /// let mut writer = BitWriter::endian(vec![], LittleEndian);
576    /// // writing 9 bits from an i8 is a compile-time error
577    /// assert!(writer.write_signed::<9, i8>(1).is_err());
578    /// ```
579    fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
580    where
581        S: SignedInteger,
582    {
583        self.write_signed_var(BITS, value)
584    }
585
586    /// Writes a twos-complement signed value to the stream
587    /// with the given number of bits.
588    ///
589    /// # Errors
590    ///
591    /// Passes along any I/O error from the underlying stream.
592    /// Returns an error if the input type is too small
593    /// to hold the given number of bits.
594    /// Returns an error if the number of bits is 0,
595    /// since one bit is always needed for the sign.
596    /// Returns an error if the value is too large
597    /// to fit the given number of bits.
598    ///
599    /// # Examples
600    /// ```
601    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
602    ///
603    /// let mut writer = BitWriter::endian(vec![], BigEndian);
604    /// writer.write_signed_var(4, -5).unwrap();
605    /// writer.write_signed_var(4, 7).unwrap();
606    /// assert_eq!(writer.into_writer(), [0b10110111]);
607    /// ```
608    ///
609    /// ```
610    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
611    ///
612    /// let mut writer = BitWriter::endian(vec![], LittleEndian);
613    /// writer.write_signed_var(4, 7).unwrap();
614    /// writer.write_signed_var(4, -5).unwrap();
615    /// assert_eq!(writer.into_writer(), [0b10110111]);
616    /// ```
617    #[inline(always)]
618    fn write_signed_var<S>(&mut self, bits: u32, value: S) -> io::Result<()>
619    where
620        S: SignedInteger,
621    {
622        self.write_signed_counted(BitCount::unknown(bits), value)
623    }
624
625    /// Writes the given bit count to the stream
626    /// with the necessary maximum number of bits.
627    ///
628    /// For example, if the maximum bit count is 15 - or `0b1111` -
629    /// writes the bit count to the stream as a 4-bit unsigned value
630    /// which can be used in subsequent writes.
631    ///
632    /// Note that `MAX` must be greater than 0.
633    /// Unlike the bit reader, the bit count need not be an exact
634    /// power of two when writing.  Any bits higher than the
635    /// bit count can reach are simply left 0.
636    ///
637    /// # Errors
638    ///
639    /// Passes along an I/O error from the underlying stream.
640    ///
641    /// ```
642    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
643    ///
644    /// let mut w = BitWriter::endian(vec![], BigEndian);
645    /// let count = 4;
646    /// w.write::<3, u32>(count).unwrap();
647    /// // may need to verify count is not larger than u8 at runtime
648    /// w.write_var::<u8>(count, 0b1111).unwrap();
649    /// w.byte_align().unwrap();
650    /// assert_eq!(w.into_writer(), &[0b100_11110]);
651    /// ```
652    ///
653    /// ```
654    /// use bitstream_io::{BigEndian, BitWriter, BitWrite, BitCount};
655    ///
656    /// let mut w = BitWriter::endian(vec![], BigEndian);
657    /// // a bit count of 4, with a maximum of 7 (0b111)
658    /// let count: BitCount<0b111> = BitCount::new::<4>();
659    /// w.write_count(count).unwrap();
660    /// // maximum size of count is known to be 7 bits at compile-time
661    /// // so no need to check that 7 bits is larger than a u8 at runtime
662    /// w.write_counted::<0b111, u8>(count, 0b1111).unwrap();
663    /// w.byte_align().unwrap();
664    /// assert_eq!(w.into_writer(), &[0b100_11110]);
665    /// ```
666    ///
667    /// ```
668    /// use bitstream_io::{BigEndian, BitWriter, BitWrite, BitCount};
669    ///
670    /// let mut w = BitWriter::endian(vec![], BigEndian);
671    /// // a bit count of 4, with a maximum of 6 (0b110)
672    /// let count: BitCount<0b110> = BitCount::new::<4>();
673    /// w.write_count(count).unwrap();
674    /// w.write_counted::<0b110, u8>(count, 0b1111).unwrap();
675    /// w.byte_align().unwrap();
676    /// // bit count is written in 3 bits
677    /// // while actual value is written in 4 bits
678    /// assert_eq!(w.into_writer(), &[0b100_11110]);
679    /// ```
680    fn write_count<const MAX: u32>(&mut self, BitCount { bits }: BitCount<MAX>) -> io::Result<()> {
681        const {
682            assert!(MAX > 0, "MAX value must be > 0");
683        }
684
685        self.write_unsigned_var(
686            if MAX == u32::MAX {
687                32
688            } else if (MAX + 1).is_power_of_two() {
689                (MAX + 1).ilog2()
690            } else {
691                (MAX + 1).ilog2() + 1
692            },
693            bits,
694        )
695    }
696
697    /// Writes a signed or unsigned value to the stream with
698    /// the given number of bits.
699    ///
700    /// # Errors
701    ///
702    /// Passes along any I/O error from the underlying stream.
703    /// Returns an error if the value is too large
704    /// to fit the given number of bits.
705    ///
706    /// # Examples
707    /// ```
708    /// use bitstream_io::{BitWriter, BitWrite, BigEndian, BitCount};
709    ///
710    /// let mut w = BitWriter::endian(vec![], BigEndian);
711    /// // writing 4 bits with a maximum of 8 will fit into a u8
712    /// // so we only need check the value fits into 4 bits
713    /// assert!(w.write_counted::<4, u8>(BitCount::new::<4>(), 0b1111).is_ok());
714    /// assert!(w.write_counted::<4, u8>(BitCount::new::<4>(), 0b1111 + 1).is_err());
715    /// // writing 4 bits with a maximum of 64 might not fit into a u8
716    /// // so need to verify this at runtime
717    /// assert!(w.write_counted::<64, u8>(BitCount::new::<4>(), 0b0000).is_ok());
718    /// assert_eq!(w.into_writer(), &[0b1111_0000]);
719    /// ```
720    fn write_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>, value: I) -> io::Result<()>
721    where
722        I: Integer + Sized,
723    {
724        I::write_var::<MAX, _>(value, self, bits)
725    }
726
727    /// Writes a signed value to the stream with
728    /// the given number of bits.
729    ///
730    /// # Errors
731    ///
732    /// Passes along any I/O error from the underlying stream.
733    /// Returns an error if the value is too large
734    /// to fit the given number of bits.
735    ///
736    /// # Examples
737    /// ```
738    /// use bitstream_io::{BitWriter, BitWrite, BigEndian, BitCount};
739    ///
740    /// let mut w = BitWriter::endian(vec![], BigEndian);
741    /// // writing 4 bits with a maximum of 8 will fit into a u8
742    /// // so we only need check the value fits into 4 bits
743    /// assert!(w.write_unsigned_counted::<4, u8>(BitCount::new::<4>(), 0b1111).is_ok());
744    /// assert!(w.write_unsigned_counted::<4, u8>(BitCount::new::<4>(), 0b1111 + 1).is_err());
745    /// // writing 4 bits with a maximum of 64 might not fit into a u8
746    /// // so need to verify this at runtime
747    /// assert!(w.write_unsigned_counted::<64, u8>(BitCount::new::<4>(), 0b0000).is_ok());
748    /// assert_eq!(w.into_writer(), &[0b1111_0000]);
749    /// ```
750    fn write_unsigned_counted<const BITS: u32, U>(
751        &mut self,
752        bits: BitCount<BITS>,
753        value: U,
754    ) -> io::Result<()>
755    where
756        U: UnsignedInteger;
757
758    /// Writes an unsigned value to the stream with
759    /// the given number of bits.
760    ///
761    /// # Errors
762    ///
763    /// Passes along any I/O error from the underlying stream.
764    /// Returns an error if the value is too large
765    /// to fit the given number of bits.
766    ///
767    /// # Examples
768    /// ```
769    /// use bitstream_io::{BitWriter, BitWrite, BigEndian, BitCount};
770    ///
771    /// let mut w = BitWriter::endian(vec![], BigEndian);
772    /// // writing 4 bits with a maximum of 8 will fit into an i8
773    /// // so we only need check the value fits into 4 bits
774    /// assert!(w.write_signed_counted::<4, i8>(BitCount::new::<4>(), 0b0111).is_ok());
775    /// assert!(w.write_signed_counted::<4, i8>(BitCount::new::<4>(), 0b0111 + 1).is_err());
776    /// // writing 4 bits with a maximum of 64 might not fit into a i8
777    /// // so need to verify this at runtime
778    /// assert!(w.write_signed_counted::<64, i8>(BitCount::new::<4>(), 0b0000).is_ok());
779    /// assert_eq!(w.into_writer(), &[0b0111_0000]);
780    /// ```
781    fn write_signed_counted<const MAX: u32, S>(
782        &mut self,
783        bits: impl TryInto<SignedBitCount<MAX>>,
784        value: S,
785    ) -> io::Result<()>
786    where
787        S: SignedInteger;
788
789    /// Writes the given constant value to the stream with
790    /// the given number of bits.
791    ///
792    /// Due to current limitations of constant parameters,
793    /// this is limited to `u32` values.
794    ///
795    /// # Errors
796    ///
797    /// Passes along any I/O error from the underlying stream.
798    /// A compile-time error occurs if the number of bits is larger
799    /// than 32 or if the value is too large too fit the
800    /// requested number of bits.
801    ///
802    /// # Examples
803    ///
804    /// ```
805    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
806    ///
807    /// let mut w = BitWriter::endian(vec![], BigEndian);
808    /// assert!(w.write_const::<4, 0b1000>().is_ok());
809    /// assert!(w.write_const::<4, 0b1011>().is_ok());
810    /// assert_eq!(w.into_writer(), &[0b1000_1011]);
811    /// ```
812    ///
813    /// ```rust,compile_fail
814    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
815    ///
816    /// let mut w = BitWriter::endian(vec![], BigEndian);
817    /// // trying to write a 5 bit value in 4 bits is a compile-time error
818    /// w.write_const::<4, 0b11111>();
819    /// ```
820    ///
821    /// ```rust,compile_fail
822    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
823    ///
824    /// let mut w = BitWriter::endian(vec![], BigEndian);
825    /// // trying to write a 33 bit value is also a compile-time error
826    /// w.write_const::<33, 1>();
827    /// ```
828    #[inline]
829    fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
830        const {
831            assert!(
832                BITS == 0 || VALUE <= (u32::ALL >> (u32::BITS_SIZE - BITS)),
833                "excessive value for bits written"
834            );
835        }
836
837        self.write::<BITS, u32>(VALUE)
838    }
839
840    /// Writes whole value to the stream whose size in bits
841    /// is equal to its type's size.
842    ///
843    /// # Errors
844    ///
845    /// Passes along any I/O error from the underlying stream.
846    ///
847    /// # Examples
848    /// ```
849    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
850    ///
851    /// let mut w = BitWriter::endian(vec![], BigEndian);
852    /// assert!(w.write_from::<u32>(0x12_34_56_78).is_ok());
853    /// assert_eq!(w.into_writer(), &[0x12, 0x34, 0x56, 0x78]);
854    /// ```
855    ///
856    /// ```
857    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
858    ///
859    /// let mut w = BitWriter::endian(vec![], BigEndian);
860    /// assert!(w.write_from::<[u8; 4]>([0x12, 0x34, 0x56, 0x78]).is_ok());
861    /// assert_eq!(w.into_writer(), &[0x12, 0x34, 0x56, 0x78]);
862    /// ```
863    fn write_from<V>(&mut self, value: V) -> io::Result<()>
864    where
865        V: Primitive;
866
867    /// Writes whole value to the stream whose size in bits
868    /// is equal to its type's size in an endianness that may
869    /// be different from the stream's endianness.
870    ///
871    /// # Errors
872    ///
873    /// Passes along any I/O error from the underlying stream.
874    ///
875    /// # Examples
876    /// ```
877    /// use bitstream_io::{BitWriter, BitWrite, BigEndian, LittleEndian};
878    ///
879    /// let mut w = BitWriter::endian(vec![], BigEndian);
880    /// assert!(w.write_as_from::<LittleEndian, u32>(0x12_34_56_78).is_ok());
881    /// assert_eq!(w.into_writer(), &[0x78, 0x56, 0x34, 0x12]);
882    /// ```
883    fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
884    where
885        F: Endianness,
886        V: Primitive;
887
888    /// Pads the stream by writing 0 over the given number of bits.
889    ///
890    /// # Errors
891    ///
892    /// Passes along any I/O error from the underlying stream.
893    ///
894    /// # Example
895    ///
896    /// ```
897    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
898    ///
899    /// let mut w = BitWriter::endian(vec![], BigEndian);
900    /// assert!(w.write_bit(true).is_ok());
901    /// assert!(w.pad(7).is_ok());
902    /// assert_eq!(w.into_writer(), &[0b1_0000000]);
903    /// ```
904    fn pad(&mut self, mut bits: u32) -> io::Result<()> {
905        loop {
906            match bits {
907                0 => break Ok(()),
908                bits @ 1..64 => break self.write_var(bits, 0u64),
909                _ => {
910                    self.write::<64, u64>(0)?;
911                    bits -= 64;
912                }
913            }
914        }
915    }
916
917    /// Writes the entirety of a byte buffer to the stream.
918    ///
919    /// # Errors
920    ///
921    /// Passes along any I/O error from the underlying stream.
922    ///
923    /// # Example
924    ///
925    /// ```
926    /// use std::io::Write;
927    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
928    /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
929    /// writer.write_var(8, 0x66u8).unwrap();
930    /// writer.write_var(8, 0x6Fu8).unwrap();
931    /// writer.write_var(8, 0x6Fu8).unwrap();
932    /// writer.write_bytes(b"bar").unwrap();
933    /// assert_eq!(writer.into_writer(), b"foobar");
934    /// ```
935    #[inline]
936    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
937        buf.iter().try_for_each(|b| self.write_unsigned::<8, _>(*b))
938    }
939
940    /// Writes `value` number of non `STOP_BIT` bits to the stream
941    /// and then writes a `STOP_BIT`.  This field is variably-sized.
942    /// `STOP_BIT` must be 0 or 1.
943    ///
944    /// # Errors
945    ///
946    /// Passes along any I/O error from the underyling stream.
947    ///
948    /// # Examples
949    /// ```
950    /// use std::io::Write;
951    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
952    /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
953    /// writer.write_unary::<0>(0).unwrap();
954    /// writer.write_unary::<0>(3).unwrap();
955    /// writer.write_unary::<0>(10).unwrap();
956    /// assert_eq!(writer.into_writer(), [0b01110111, 0b11111110]);
957    /// ```
958    ///
959    /// ```
960    /// use std::io::Write;
961    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
962    /// let mut writer = BitWriter::endian(Vec::new(), LittleEndian);
963    /// writer.write_unary::<0>(0).unwrap();
964    /// writer.write_unary::<0>(3).unwrap();
965    /// writer.write_unary::<0>(10).unwrap();
966    /// assert_eq!(writer.into_writer(), [0b11101110, 0b01111111]);
967    /// ```
968    ///
969    /// ```
970    /// use std::io::Write;
971    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
972    /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
973    /// writer.write_unary::<1>(0).unwrap();
974    /// writer.write_unary::<1>(3).unwrap();
975    /// writer.write_unary::<1>(10).unwrap();
976    /// assert_eq!(writer.into_writer(), [0b10001000, 0b00000001]);
977    /// ```
978    ///
979    /// ```
980    /// use std::io::Write;
981    /// use bitstream_io::{LittleEndian, BitWriter, BitWrite};
982    /// let mut writer = BitWriter::endian(Vec::new(), LittleEndian);
983    /// writer.write_unary::<1>(0).unwrap();
984    /// writer.write_unary::<1>(3).unwrap();
985    /// writer.write_unary::<1>(10).unwrap();
986    /// assert_eq!(writer.into_writer(), [0b00010001, 0b10000000]);
987    /// ```
988    fn write_unary<const STOP_BIT: u8>(&mut self, mut value: u32) -> io::Result<()> {
989        const {
990            assert!(matches!(STOP_BIT, 0 | 1), "stop bit must be 0 or 1");
991        }
992
993        // a simple implementation which works anywhere
994        let continue_bit = match STOP_BIT {
995            0 => 1,
996            1 => 0,
997            _ => unreachable!(),
998        };
999
1000        while value > 0 {
1001            self.write::<1, u8>(continue_bit)?;
1002            value -= 1;
1003        }
1004        self.write::<1, _>(STOP_BIT)
1005    }
1006
1007    /// Builds and writes complex type
1008    fn build<T: ToBitStream>(&mut self, build: &T) -> Result<(), T::Error> {
1009        build.to_writer(self)
1010    }
1011
1012    /// Builds and writes complex type with context
1013    fn build_with<'a, T: ToBitStreamWith<'a>>(
1014        &mut self,
1015        build: &T,
1016        context: &T::Context,
1017    ) -> Result<(), T::Error> {
1018        build.to_writer(self, context)
1019    }
1020
1021    /// Returns true if the stream is aligned at a whole byte.
1022    ///
1023    /// # Example
1024    /// ```
1025    /// use std::io::{Write, sink};
1026    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
1027    /// let mut writer = BitWriter::endian(sink(), BigEndian);
1028    /// assert_eq!(writer.byte_aligned(), true);
1029    /// writer.write_var(1, 0u8).unwrap();
1030    /// assert_eq!(writer.byte_aligned(), false);
1031    /// writer.write_var(7, 0u8).unwrap();
1032    /// assert_eq!(writer.byte_aligned(), true);
1033    /// ```
1034    fn byte_aligned(&self) -> bool;
1035
1036    /// Pads the stream with 0 bits until it is aligned at a whole byte.
1037    /// Does nothing if the stream is already aligned.
1038    ///
1039    /// # Errors
1040    ///
1041    /// Passes along any I/O error from the underyling stream.
1042    ///
1043    /// # Example
1044    /// ```
1045    /// use std::io::Write;
1046    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
1047    /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
1048    /// writer.write_var(1, 0u8).unwrap();
1049    /// writer.byte_align().unwrap();
1050    /// writer.write_var(8, 0xFFu8).unwrap();
1051    /// assert_eq!(writer.into_writer(), [0x00, 0xFF]);
1052    /// ```
1053    fn byte_align(&mut self) -> io::Result<()> {
1054        while !BitWrite::byte_aligned(self) {
1055            self.write_bit(false)?;
1056        }
1057        Ok(())
1058    }
1059
1060    /// Given a symbol, writes its representation to the output stream as bits.
1061    /// Generates no output if the symbol isn't defined in the Huffman tree.
1062    ///
1063    /// # Errors
1064    ///
1065    /// Passes along any I/O error from the underlying stream.
1066    ///
1067    /// # Example
1068    /// ```
1069    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
1070    /// use bitstream_io::define_huffman_tree;
1071    ///
1072    /// define_huffman_tree!(TreeName : char = ['a', ['b', ['c', 'd']]]);
1073    /// // 'a' is 0
1074    /// // 'b' is 1 -> 0
1075    /// // 'c' is 1 -> 1 -> 0
1076    /// // 'd' is 1 -> 1 -> 1
1077    ///
1078    /// let mut writer = BitWriter::endian(vec![], BigEndian);
1079    /// writer.write_huffman::<TreeName>('b').unwrap();
1080    /// writer.write_huffman::<TreeName>('c').unwrap();
1081    /// writer.write_huffman::<TreeName>('d').unwrap();
1082    /// assert_eq!(writer.into_writer(), [0b10_110_111]);
1083    /// ```
1084    fn write_huffman<T>(&mut self, value: T::Symbol) -> io::Result<()>
1085    where
1086        T: crate::huffman::ToBits,
1087    {
1088        T::to_bits(value, |b| self.write_bit(b))
1089    }
1090
1091    /// Creates a "by reference" adaptor for this `BitWrite`
1092    ///
1093    /// The returned adapter also implements `BitWrite`
1094    /// and will borrow the current reader.
1095    ///
1096    /// # Example
1097    /// ```
1098    /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
1099    ///
1100    /// fn build<W: BitWrite>(w: W) {
1101    ///     // perform some building
1102    /// }
1103    ///
1104    /// let mut writer = BitWriter::endian(vec![], BigEndian);
1105    /// // performing building by reference
1106    /// build(writer.by_ref());
1107    /// // original owned writer still available
1108    /// writer.write::<8, u8>(0).unwrap();
1109    /// assert_eq!(writer.into_writer(), &[0]);
1110    /// ```
1111    #[inline]
1112    fn by_ref(&mut self) -> &mut Self {
1113        self
1114    }
1115}
1116
1117impl<W: BitWrite + ?Sized> BitWrite for &mut W {
1118    #[inline]
1119    fn write_bit(&mut self, bit: bool) -> io::Result<()> {
1120        (**self).write_bit(bit)
1121    }
1122
1123    #[inline]
1124    fn write<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
1125    where
1126        I: Integer,
1127    {
1128        (**self).write::<BITS, I>(value)
1129    }
1130
1131    #[inline]
1132    fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
1133        (**self).write_const::<BITS, VALUE>()
1134    }
1135
1136    #[inline]
1137    fn write_var<I>(&mut self, bits: u32, value: I) -> io::Result<()>
1138    where
1139        I: Integer,
1140    {
1141        (**self).write_var(bits, value)
1142    }
1143
1144    #[inline]
1145    fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1146    where
1147        U: UnsignedInteger,
1148    {
1149        (**self).write_unsigned::<BITS, U>(value)
1150    }
1151
1152    #[inline]
1153    fn write_unsigned_var<U>(&mut self, bits: u32, value: U) -> io::Result<()>
1154    where
1155        U: UnsignedInteger,
1156    {
1157        (**self).write_unsigned_var(bits, value)
1158    }
1159
1160    #[inline]
1161    fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1162    where
1163        S: SignedInteger,
1164    {
1165        (**self).write_signed::<BITS, S>(value)
1166    }
1167
1168    #[inline(always)]
1169    fn write_signed_var<S>(&mut self, bits: u32, value: S) -> io::Result<()>
1170    where
1171        S: SignedInteger,
1172    {
1173        (**self).write_signed_var(bits, value)
1174    }
1175
1176    #[inline]
1177    fn write_count<const MAX: u32>(&mut self, count: BitCount<MAX>) -> io::Result<()> {
1178        (**self).write_count::<MAX>(count)
1179    }
1180
1181    #[inline]
1182    fn write_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>, value: I) -> io::Result<()>
1183    where
1184        I: Integer + Sized,
1185    {
1186        (**self).write_counted::<MAX, I>(bits, value)
1187    }
1188
1189    #[inline]
1190    fn write_unsigned_counted<const BITS: u32, U>(
1191        &mut self,
1192        bits: BitCount<BITS>,
1193        value: U,
1194    ) -> io::Result<()>
1195    where
1196        U: UnsignedInteger,
1197    {
1198        (**self).write_unsigned_counted::<BITS, U>(bits, value)
1199    }
1200
1201    #[inline]
1202    fn write_signed_counted<const MAX: u32, S>(
1203        &mut self,
1204        bits: impl TryInto<SignedBitCount<MAX>>,
1205        value: S,
1206    ) -> io::Result<()>
1207    where
1208        S: SignedInteger,
1209    {
1210        (**self).write_signed_counted::<MAX, S>(bits, value)
1211    }
1212
1213    #[inline]
1214    fn write_from<V>(&mut self, value: V) -> io::Result<()>
1215    where
1216        V: Primitive,
1217    {
1218        (**self).write_from::<V>(value)
1219    }
1220
1221    #[inline]
1222    fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1223    where
1224        F: Endianness,
1225        V: Primitive,
1226    {
1227        (**self).write_as_from::<F, V>(value)
1228    }
1229
1230    #[inline]
1231    fn pad(&mut self, bits: u32) -> io::Result<()> {
1232        (**self).pad(bits)
1233    }
1234
1235    #[inline]
1236    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1237        (**self).write_bytes(buf)
1238    }
1239
1240    #[inline]
1241    fn write_unary<const STOP_BIT: u8>(&mut self, value: u32) -> io::Result<()> {
1242        (**self).write_unary::<STOP_BIT>(value)
1243    }
1244
1245    #[inline]
1246    fn build<T: ToBitStream>(&mut self, build: &T) -> Result<(), T::Error> {
1247        (**self).build(build)
1248    }
1249
1250    #[inline]
1251    fn build_with<'a, T: ToBitStreamWith<'a>>(
1252        &mut self,
1253        build: &T,
1254        context: &T::Context,
1255    ) -> Result<(), T::Error> {
1256        (**self).build_with(build, context)
1257    }
1258
1259    #[inline]
1260    fn byte_aligned(&self) -> bool {
1261        (**self).byte_aligned()
1262    }
1263
1264    #[inline]
1265    fn byte_align(&mut self) -> io::Result<()> {
1266        (**self).byte_align()
1267    }
1268
1269    #[inline]
1270    fn write_huffman<T>(&mut self, value: T::Symbol) -> io::Result<()>
1271    where
1272        T: crate::huffman::ToBits,
1273    {
1274        (**self).write_huffman::<T>(value)
1275    }
1276}
1277
1278/// A compatibility trait for older code implementing [`BitWrite`]
1279///
1280/// This is a trait largely compatible with older code
1281/// from the 2.X.X version,
1282/// which one can use with a named import as needed.
1283///
1284/// New code should prefer the regular [`BitWrite`] trait.
1285///
1286/// # Example
1287/// ```
1288/// use bitstream_io::BitWrite2 as BitWrite;
1289/// use bitstream_io::{BitWriter, BigEndian};
1290/// let mut byte = vec![];
1291/// let mut writer = BitWriter::endian(byte, BigEndian);
1292/// writer.write::<u8>(4, 0b1111).unwrap();
1293/// writer.write_out::<4, u8>(0b0000).unwrap();
1294/// assert_eq!(writer.into_writer(), [0b1111_0000]);
1295/// ```
1296pub trait BitWrite2 {
1297    /// Writes a single bit to the stream.
1298    /// `true` indicates 1, `false` indicates 0
1299    ///
1300    /// # Errors
1301    ///
1302    /// Passes along any I/O error from the underlying stream.
1303    fn write_bit(&mut self, bit: bool) -> io::Result<()> {
1304        self.write_unsigned_out::<1, u8>(u8::from(bit))
1305    }
1306
1307    /// Writes a signed or unsigned value to the stream using the given
1308    /// number of bits.
1309    ///
1310    /// # Errors
1311    ///
1312    /// Passes along any I/O error from the underlying stream.
1313    /// Returns an error if the input type is too small
1314    /// to hold the given number of bits.
1315    /// Returns an error if the value is too large
1316    /// to fit the given number of bits.
1317    fn write<I>(&mut self, bits: u32, value: I) -> io::Result<()>
1318    where
1319        I: Integer;
1320
1321    /// Writes a signed or unsigned value to the stream using the given
1322    /// const number of bits.
1323    ///
1324    /// # Errors
1325    ///
1326    /// Passes along any I/O error from the underlying stream.
1327    /// Returns an error if the value is too large
1328    /// to fit the given number of bits.
1329    /// A compile-time error occurs if the given number of bits
1330    /// is larger than the output type.
1331    fn write_out<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
1332    where
1333        I: Integer;
1334
1335    /// Writes an unsigned value to the stream using the given
1336    /// number of bits.
1337    ///
1338    /// # Errors
1339    ///
1340    /// Passes along any I/O error from the underlying stream.
1341    /// Returns an error if the input type is too small
1342    /// to hold the given number of bits.
1343    /// Returns an error if the value is too large
1344    /// to fit the given number of bits.
1345    fn write_unsigned<U>(&mut self, bits: u32, value: U) -> io::Result<()>
1346    where
1347        U: UnsignedInteger;
1348
1349    /// Writes an unsigned value to the stream using the given
1350    /// const number of bits.
1351    ///
1352    /// # Errors
1353    ///
1354    /// Passes along any I/O error from the underlying stream.
1355    /// Returns an error if the value is too large
1356    /// to fit the given number of bits.
1357    /// A compile-time error occurs if the given number of bits
1358    /// is larger than the output type.
1359    #[inline]
1360    fn write_unsigned_out<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1361    where
1362        U: UnsignedInteger,
1363    {
1364        self.write_unsigned(BITS, value)
1365    }
1366
1367    /// Writes a twos-complement signed value to the stream
1368    /// with the given number of bits.
1369    ///
1370    /// # Errors
1371    ///
1372    /// Passes along any I/O error from the underlying stream.
1373    /// Returns an error if the input type is too small
1374    /// to hold the given number of bits.
1375    /// Returns an error if the number of bits is 0,
1376    /// since one bit is always needed for the sign.
1377    /// Returns an error if the value is too large
1378    /// to fit the given number of bits.
1379    fn write_signed<S>(&mut self, bits: u32, value: S) -> io::Result<()>
1380    where
1381        S: SignedInteger;
1382
1383    /// Writes a twos-complement signed value to the stream
1384    /// with the given const number of bits.
1385    ///
1386    /// # Errors
1387    ///
1388    /// Passes along any I/O error from the underlying stream.
1389    /// Returns an error if the value is too large
1390    /// to fit the given number of bits.
1391    /// A compile-time error occurs if the number of bits is 0,
1392    /// since one bit is always needed for the sign.
1393    /// A compile-time error occurs if the given number of bits
1394    /// is larger than the output type.
1395    fn write_signed_out<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1396    where
1397        S: SignedInteger,
1398    {
1399        self.write_signed(BITS, value)
1400    }
1401
1402    /// Writes whole value to the stream whose size in bits
1403    /// is equal to its type's size.
1404    ///
1405    /// # Errors
1406    ///
1407    /// Passes along any I/O error from the underlying stream.
1408    fn write_from<V>(&mut self, value: V) -> io::Result<()>
1409    where
1410        V: Primitive;
1411
1412    /// Writes whole value to the stream whose size in bits
1413    /// is equal to its type's size in an endianness that may
1414    /// be different from the stream's endianness.
1415    ///
1416    /// # Errors
1417    ///
1418    /// Passes along any I/O error from the underlying stream.
1419    fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1420    where
1421        F: Endianness,
1422        V: Primitive;
1423
1424    /// Pads the stream by writing 0 over the given number of bits.
1425    ///
1426    /// # Errors
1427    ///
1428    /// Passes along any I/O error from the underlying stream.
1429    fn pad(&mut self, mut bits: u32) -> io::Result<()> {
1430        loop {
1431            match bits {
1432                0 => break Ok(()),
1433                bits @ 1..64 => break self.write(bits, 0u64),
1434                _ => {
1435                    self.write_out::<64, u64>(0)?;
1436                    bits -= 64;
1437                }
1438            }
1439        }
1440    }
1441
1442    /// Writes the entirety of a byte buffer to the stream.
1443    ///
1444    /// # Errors
1445    ///
1446    /// Passes along any I/O error from the underlying stream.
1447    ///
1448    /// # Example
1449    ///
1450    /// ```
1451    /// use std::io::Write;
1452    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
1453    /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
1454    /// writer.write_var(8, 0x66u8).unwrap();
1455    /// writer.write_var(8, 0x6Fu8).unwrap();
1456    /// writer.write_var(8, 0x6Fu8).unwrap();
1457    /// writer.write_bytes(b"bar").unwrap();
1458    /// assert_eq!(writer.into_writer(), b"foobar");
1459    /// ```
1460    #[inline]
1461    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1462        buf.iter()
1463            .try_for_each(|b| self.write_unsigned_out::<8, _>(*b))
1464    }
1465
1466    /// Writes `value` number of 1 bits to the stream
1467    /// and then writes a 0 bit.  This field is variably-sized.
1468    ///
1469    /// # Errors
1470    ///
1471    /// Passes along any I/O error from the underyling stream.
1472    fn write_unary0(&mut self, value: u32) -> io::Result<()>;
1473
1474    /// Writes `value` number of 0 bits to the stream
1475    /// and then writes a 1 bit.  This field is variably-sized.
1476    ///
1477    /// # Errors
1478    ///
1479    /// Passes along any I/O error from the underyling stream.
1480    fn write_unary1(&mut self, value: u32) -> io::Result<()>;
1481
1482    /// Builds and writes complex type
1483    fn build<T: ToBitStream>(&mut self, build: &T) -> Result<(), T::Error>
1484    where
1485        Self: BitWrite,
1486    {
1487        build.to_writer(self)
1488    }
1489
1490    /// Builds and writes complex type with context
1491    fn build_with<'a, T: ToBitStreamWith<'a>>(
1492        &mut self,
1493        build: &T,
1494        context: &T::Context,
1495    ) -> Result<(), T::Error>
1496    where
1497        Self: BitWrite,
1498    {
1499        build.to_writer(self, context)
1500    }
1501
1502    /// Returns true if the stream is aligned at a whole byte.
1503    fn byte_aligned(&self) -> bool;
1504
1505    /// Pads the stream with 0 bits until it is aligned at a whole byte.
1506    /// Does nothing if the stream is already aligned.
1507    ///
1508    /// # Errors
1509    ///
1510    /// Passes along any I/O error from the underyling stream.
1511    ///
1512    /// # Example
1513    /// ```
1514    /// use std::io::Write;
1515    /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
1516    /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
1517    /// writer.write_var(1, 0u8).unwrap();
1518    /// writer.byte_align().unwrap();
1519    /// writer.write_var(8, 0xFFu8).unwrap();
1520    /// assert_eq!(writer.into_writer(), [0x00, 0xFF]);
1521    /// ```
1522    fn byte_align(&mut self) -> io::Result<()> {
1523        while !self.byte_aligned() {
1524            self.write_bit(false)?;
1525        }
1526        Ok(())
1527    }
1528
1529    /// Given a symbol, writes its representation to the output stream as bits.
1530    /// Generates no output if the symbol isn't defined in the Huffman tree.
1531    ///
1532    /// # Errors
1533    ///
1534    /// Passes along any I/O error from the underlying stream.
1535    ///
1536    /// # Example
1537    /// ```
1538    /// use std::io::Write;
1539    /// use bitstream_io::{BigEndian, BitWriter, BitWrite2};
1540    /// use bitstream_io::define_huffman_tree;
1541    /// define_huffman_tree!(TreeName : char = ['a', ['b', ['c', 'd']]]);
1542    /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
1543    /// writer.write_huffman::<TreeName>('b').unwrap();
1544    /// writer.write_huffman::<TreeName>('c').unwrap();
1545    /// writer.write_huffman::<TreeName>('d').unwrap();
1546    /// assert_eq!(writer.into_writer(), [0b10_110_111]);
1547    /// ```
1548    fn write_huffman<T>(&mut self, value: T::Symbol) -> io::Result<()>
1549    where
1550        T: crate::huffman::ToBits,
1551    {
1552        T::to_bits(value, |b| self.write_bit(b))
1553    }
1554}
1555
1556impl<W: BitWrite> BitWrite2 for W {
1557    #[inline]
1558    fn write_bit(&mut self, bit: bool) -> io::Result<()> {
1559        BitWrite::write_bit(self, bit)
1560    }
1561
1562    #[inline]
1563    fn write<I>(&mut self, bits: u32, value: I) -> io::Result<()>
1564    where
1565        I: Integer,
1566    {
1567        BitWrite::write_var(self, bits, value)
1568    }
1569
1570    #[inline]
1571    fn write_out<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
1572    where
1573        I: Integer,
1574    {
1575        BitWrite::write::<BITS, I>(self, value)
1576    }
1577
1578    #[inline]
1579    fn write_unsigned<U>(&mut self, bits: u32, value: U) -> io::Result<()>
1580    where
1581        U: UnsignedInteger,
1582    {
1583        BitWrite::write_unsigned_var::<U>(self, bits, value)
1584    }
1585
1586    #[inline]
1587    fn write_unsigned_out<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1588    where
1589        U: UnsignedInteger,
1590    {
1591        BitWrite::write_unsigned::<BITS, U>(self, value)
1592    }
1593
1594    #[inline]
1595    fn write_signed<S>(&mut self, bits: u32, value: S) -> io::Result<()>
1596    where
1597        S: SignedInteger,
1598    {
1599        BitWrite::write_signed_var::<S>(self, bits, value)
1600    }
1601
1602    #[inline]
1603    fn write_signed_out<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1604    where
1605        S: SignedInteger,
1606    {
1607        BitWrite::write_signed::<BITS, S>(self, value)
1608    }
1609
1610    #[inline]
1611    fn write_from<V>(&mut self, value: V) -> io::Result<()>
1612    where
1613        V: Primitive,
1614    {
1615        BitWrite::write_from(self, value)
1616    }
1617
1618    #[inline]
1619    fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1620    where
1621        F: Endianness,
1622        V: Primitive,
1623    {
1624        BitWrite::write_as_from::<F, V>(self, value)
1625    }
1626
1627    #[inline]
1628    fn pad(&mut self, bits: u32) -> io::Result<()> {
1629        BitWrite::pad(self, bits)
1630    }
1631
1632    #[inline]
1633    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1634        BitWrite::write_bytes(self, buf)
1635    }
1636
1637    #[inline]
1638    fn write_unary0(&mut self, value: u32) -> io::Result<()> {
1639        BitWrite::write_unary::<0>(self, value)
1640    }
1641
1642    #[inline]
1643    fn write_unary1(&mut self, value: u32) -> io::Result<()> {
1644        BitWrite::write_unary::<1>(self, value)
1645    }
1646
1647    #[inline]
1648    fn byte_aligned(&self) -> bool {
1649        BitWrite::byte_aligned(self)
1650    }
1651
1652    #[inline]
1653    fn byte_align(&mut self) -> io::Result<()> {
1654        BitWrite::byte_align(self)
1655    }
1656}
1657
1658impl<W: io::Write, E: Endianness> BitWrite for BitWriter<W, E> {
1659    fn write_bit(&mut self, bit: bool) -> io::Result<()> {
1660        match E::push_bit_flush(&mut self.value, &mut self.bits, bit) {
1661            None => Ok(()),
1662            Some(byte) => write_byte(&mut self.writer, byte),
1663        }
1664    }
1665
1666    #[inline(always)]
1667    fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1668    where
1669        U: UnsignedInteger,
1670    {
1671        let Self {
1672            value: queue_value,
1673            bits: queue_bits,
1674            writer,
1675            ..
1676        } = self;
1677        E::write_bits_fixed::<BITS, W, U>(writer, queue_value, queue_bits, value)
1678    }
1679
1680    fn write_unsigned_counted<const BITS: u32, U>(
1681        &mut self,
1682        bits: BitCount<BITS>,
1683        value: U,
1684    ) -> io::Result<()>
1685    where
1686        U: UnsignedInteger,
1687    {
1688        let Self {
1689            value: queue_value,
1690            bits: queue_bits,
1691            writer,
1692            ..
1693        } = self;
1694        E::write_bits::<BITS, W, U>(writer, queue_value, queue_bits, bits, value)
1695    }
1696
1697    #[inline(always)]
1698    fn write_signed_counted<const BITS: u32, S>(
1699        &mut self,
1700        bits: impl TryInto<SignedBitCount<BITS>>,
1701        value: S,
1702    ) -> io::Result<()>
1703    where
1704        S: SignedInteger,
1705    {
1706        E::write_signed_counted(
1707            self,
1708            bits.try_into().map_err(|_| {
1709                io::Error::new(
1710                    io::ErrorKind::InvalidInput,
1711                    "signed writes need at least 1 bit for sign",
1712                )
1713            })?,
1714            value,
1715        )
1716    }
1717
1718    #[inline]
1719    fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1720    where
1721        S: SignedInteger,
1722    {
1723        E::write_signed_fixed::<_, BITS, S>(self, value)
1724    }
1725
1726    #[inline]
1727    fn write_from<V>(&mut self, value: V) -> io::Result<()>
1728    where
1729        V: Primitive,
1730    {
1731        E::write_bytes::<8, _>(
1732            &mut self.writer,
1733            &mut self.value,
1734            self.bits,
1735            E::primitive_to_bytes(value).as_ref(),
1736        )
1737    }
1738
1739    #[inline]
1740    fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1741    where
1742        F: Endianness,
1743        V: Primitive,
1744    {
1745        F::write_bytes::<8, _>(
1746            &mut self.writer,
1747            &mut self.value,
1748            self.bits,
1749            F::primitive_to_bytes(value).as_ref(),
1750        )
1751    }
1752
1753    fn write_unary<const STOP_BIT: u8>(&mut self, mut value: u32) -> io::Result<()> {
1754        const {
1755            assert!(matches!(STOP_BIT, 0 | 1), "stop bit must be 0 or 1");
1756        }
1757
1758        loop {
1759            match value {
1760                0 => break BitWrite::write::<1, _>(self, STOP_BIT),
1761                1..64 => {
1762                    BitWrite::write_var(
1763                        self,
1764                        value,
1765                        match STOP_BIT {
1766                            0 => u64::MAX >> (64 - value),
1767                            1 => 0,
1768                            _ => unreachable!(),
1769                        },
1770                    )?;
1771                    break BitWrite::write::<1, _>(self, STOP_BIT);
1772                }
1773                64.. => {
1774                    BitWrite::write::<64, _>(
1775                        self,
1776                        match STOP_BIT {
1777                            0 => u64::MAX,
1778                            1 => 0,
1779                            _ => unreachable!(),
1780                        },
1781                    )?;
1782                    value -= 64;
1783                }
1784            }
1785        }
1786    }
1787
1788    #[inline]
1789    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1790        E::write_bytes::<1024, _>(&mut self.writer, &mut self.value, self.bits, buf)
1791    }
1792
1793    #[inline(always)]
1794    fn byte_aligned(&self) -> bool {
1795        self.bits == 0
1796    }
1797}
1798
1799/// An error returned if performing math operations would overflow
1800#[derive(Copy, Clone, Debug)]
1801pub struct Overflowed;
1802
1803impl fmt::Display for Overflowed {
1804    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1805        "overflow occured in counter".fmt(f)
1806    }
1807}
1808
1809impl core::error::Error for Overflowed {}
1810
1811impl From<Overflowed> for io::Error {
1812    fn from(Overflowed: Overflowed) -> Self {
1813        io::Error::new(
1814            #[cfg(feature = "std")]
1815            {
1816                io::ErrorKind::StorageFull
1817            },
1818            #[cfg(not(feature = "std"))]
1819            {
1820                io::ErrorKind::Other
1821            },
1822            "bitstream accumulator overflow",
1823        )
1824    }
1825}
1826
1827/// A common trait for integer types for performing math operations
1828/// which may check for overflow.
1829pub trait Counter: Default + Sized + From<u8> + TryFrom<u32> + TryFrom<usize> {
1830    /// add rhs to self, returning `Overflowed` if the result is too large
1831    fn checked_add_assign(&mut self, rhs: Self) -> Result<(), Overflowed>;
1832
1833    /// multiply self by rhs, returning `Overflowed` if the result is too large
1834    fn checked_mul(self, rhs: Self) -> Result<Self, Overflowed>;
1835
1836    /// returns `true` if the number if bits written is divisible by 8
1837    fn byte_aligned(&self) -> bool;
1838}
1839
1840macro_rules! define_counter {
1841    ($t:ty) => {
1842        impl Counter for $t {
1843            fn checked_add_assign(&mut self, rhs: Self) -> Result<(), Overflowed> {
1844                *self = <$t>::checked_add(*self, rhs).ok_or(Overflowed)?;
1845                Ok(())
1846            }
1847
1848            fn checked_mul(self, rhs: Self) -> Result<Self, Overflowed> {
1849                <$t>::checked_mul(self, rhs).ok_or(Overflowed)
1850            }
1851
1852            fn byte_aligned(&self) -> bool {
1853                self % 8 == 0
1854            }
1855        }
1856    };
1857}
1858
1859define_counter!(u8);
1860define_counter!(u16);
1861define_counter!(u32);
1862define_counter!(u64);
1863define_counter!(u128);
1864
1865/// For counting the number of bits written but generating no output.
1866///
1867/// # Example
1868/// ```
1869/// use bitstream_io::{BitWrite, BitCounter};
1870/// let mut writer: BitCounter<u32> = BitCounter::new();
1871/// writer.write_var(1, 0b1u8).unwrap();
1872/// writer.write_var(2, 0b01u8).unwrap();
1873/// writer.write_var(5, 0b10111u8).unwrap();
1874/// assert_eq!(writer.written(), 8);
1875/// ```
1876#[derive(Default)]
1877pub struct BitCounter<N> {
1878    bits: N,
1879}
1880
1881impl<N: Default> BitCounter<N> {
1882    /// Creates new counter
1883    #[inline]
1884    pub fn new() -> Self {
1885        BitCounter { bits: N::default() }
1886    }
1887}
1888
1889impl<N: Copy> BitCounter<N> {
1890    /// Returns number of bits written
1891    #[inline]
1892    pub fn written(&self) -> N {
1893        self.bits
1894    }
1895}
1896
1897impl<N> BitCounter<N> {
1898    /// Returns number of bits written
1899    #[inline]
1900    pub fn into_written(self) -> N {
1901        self.bits
1902    }
1903}
1904
1905impl<N: Counter> BitWrite for BitCounter<N> {
1906    #[inline]
1907    fn write_bit(&mut self, _bit: bool) -> io::Result<()> {
1908        self.bits.checked_add_assign(1u8.into())?;
1909        Ok(())
1910    }
1911
1912    #[inline]
1913    fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
1914        const {
1915            assert!(
1916                BITS == 0 || VALUE <= (u32::ALL >> (u32::BITS_SIZE - BITS)),
1917                "excessive value for bits written"
1918            );
1919        }
1920
1921        self.bits
1922            .checked_add_assign(BITS.try_into().map_err(|_| Overflowed)?)?;
1923        Ok(())
1924    }
1925
1926    #[inline]
1927    fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1928    where
1929        U: UnsignedInteger,
1930    {
1931        const {
1932            assert!(BITS <= U::BITS_SIZE, "excessive bits for type written");
1933        }
1934
1935        if BITS == 0 {
1936            Ok(())
1937        } else if value <= (U::ALL >> (U::BITS_SIZE - BITS)) {
1938            self.bits
1939                .checked_add_assign(BITS.try_into().map_err(|_| Overflowed)?)?;
1940            Ok(())
1941        } else {
1942            Err(io::Error::new(
1943                io::ErrorKind::InvalidInput,
1944                "excessive value for bits written",
1945            ))
1946        }
1947    }
1948
1949    #[inline]
1950    fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1951    where
1952        S: SignedInteger,
1953    {
1954        let SignedBitCount {
1955            bits: BitCount { bits },
1956            unsigned,
1957        } = const {
1958            assert!(BITS <= S::BITS_SIZE, "excessive bits for type written");
1959            let count = BitCount::<BITS>::new::<BITS>().signed_count();
1960            assert!(
1961                count.is_some(),
1962                "signed writes need at least 1 bit for sign"
1963            );
1964            count.unwrap()
1965        };
1966
1967        // doesn't matter which side the sign is on
1968        // so long as it's added to the bit count
1969        self.bits.checked_add_assign(1u8.into())?;
1970
1971        self.write_unsigned_counted(
1972            unsigned,
1973            if value.is_negative() {
1974                value.as_negative(bits)
1975            } else {
1976                value.as_non_negative()
1977            },
1978        )
1979    }
1980
1981    #[inline]
1982    fn write_unsigned_counted<const MAX: u32, U>(
1983        &mut self,
1984        BitCount { bits }: BitCount<MAX>,
1985        value: U,
1986    ) -> io::Result<()>
1987    where
1988        U: UnsignedInteger,
1989    {
1990        if MAX <= U::BITS_SIZE || bits <= U::BITS_SIZE {
1991            if bits == 0 {
1992                Ok(())
1993            } else if value <= U::ALL >> (U::BITS_SIZE - bits) {
1994                self.bits
1995                    .checked_add_assign(bits.try_into().map_err(|_| Overflowed)?)?;
1996                Ok(())
1997            } else {
1998                Err(io::Error::new(
1999                    io::ErrorKind::InvalidInput,
2000                    "excessive value for bits written",
2001                ))
2002            }
2003        } else {
2004            Err(io::Error::new(
2005                io::ErrorKind::InvalidInput,
2006                "excessive bits for type written",
2007            ))
2008        }
2009    }
2010
2011    #[inline]
2012    fn write_signed_counted<const MAX: u32, S>(
2013        &mut self,
2014        bits: impl TryInto<SignedBitCount<MAX>>,
2015        value: S,
2016    ) -> io::Result<()>
2017    where
2018        S: SignedInteger,
2019    {
2020        let SignedBitCount {
2021            bits: BitCount { bits },
2022            unsigned,
2023        } = bits.try_into().map_err(|_| {
2024            io::Error::new(
2025                io::ErrorKind::InvalidInput,
2026                "signed writes need at least 1 bit for sign",
2027            )
2028        })?;
2029
2030        if MAX <= S::BITS_SIZE || bits <= S::BITS_SIZE {
2031            // doesn't matter which side the sign is on
2032            // so long as it's added to the bit count
2033            self.bits.checked_add_assign(1u8.into())?;
2034
2035            self.write_unsigned_counted(
2036                unsigned,
2037                if value.is_negative() {
2038                    value.as_negative(bits)
2039                } else {
2040                    value.as_non_negative()
2041                },
2042            )
2043        } else {
2044            Err(io::Error::new(
2045                io::ErrorKind::InvalidInput,
2046                "excessive bits for type written",
2047            ))
2048        }
2049    }
2050
2051    #[inline]
2052    fn write_from<V>(&mut self, _: V) -> io::Result<()>
2053    where
2054        V: Primitive,
2055    {
2056        self.bits.checked_add_assign(
2057            N::try_from(core::mem::size_of::<V>())
2058                .map_err(|_| Overflowed)?
2059                .checked_mul(8u8.into())?,
2060        )?;
2061        Ok(())
2062    }
2063
2064    #[inline]
2065    fn write_as_from<F, V>(&mut self, _: V) -> io::Result<()>
2066    where
2067        F: Endianness,
2068        V: Primitive,
2069    {
2070        self.bits.checked_add_assign(
2071            N::try_from(core::mem::size_of::<V>())
2072                .map_err(|_| Overflowed)?
2073                .checked_mul(8u8.into())?,
2074        )?;
2075        Ok(())
2076    }
2077
2078    #[inline]
2079    fn pad(&mut self, bits: u32) -> io::Result<()> {
2080        self.bits
2081            .checked_add_assign(bits.try_into().map_err(|_| Overflowed)?)?;
2082        Ok(())
2083    }
2084
2085    #[inline]
2086    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
2087        self.bits.checked_add_assign(
2088            N::try_from(buf.len())
2089                .map_err(|_| Overflowed)?
2090                .checked_mul(8u8.into())?,
2091        )?;
2092        Ok(())
2093    }
2094
2095    fn write_unary<const STOP_BIT: u8>(&mut self, value: u32) -> io::Result<()> {
2096        const {
2097            assert!(matches!(STOP_BIT, 0 | 1), "stop bit must be 0 or 1");
2098        }
2099
2100        self.bits
2101            .checked_add_assign(value.try_into().map_err(|_| Overflowed)?)?;
2102        self.bits.checked_add_assign(1u8.into())?;
2103        Ok(())
2104    }
2105
2106    #[inline]
2107    fn byte_aligned(&self) -> bool {
2108        self.bits.byte_aligned()
2109    }
2110}
2111
2112/// For recording writes in order to play them back on another writer
2113/// # Example
2114/// ```
2115/// use std::io::Write;
2116/// use bitstream_io::{BigEndian, BitWriter, BitWrite, BitRecorder};
2117/// let mut recorder: BitRecorder<u32, BigEndian> = BitRecorder::new();
2118/// recorder.write_var(1, 0b1u8).unwrap();
2119/// recorder.write_var(2, 0b01u8).unwrap();
2120/// recorder.write_var(5, 0b10111u8).unwrap();
2121/// assert_eq!(recorder.written(), 8);
2122/// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
2123/// recorder.playback(&mut writer);
2124/// assert_eq!(writer.into_writer(), [0b10110111]);
2125/// ```
2126pub struct BitRecorder<N, E: Endianness> {
2127    writer: BitWriter<Vec<u8>, E>,
2128    phantom: PhantomData<N>,
2129}
2130
2131impl<N: Counter, E: Endianness> BitRecorder<N, E> {
2132    /// Creates new recorder
2133    #[inline]
2134    pub fn new() -> Self {
2135        BitRecorder {
2136            writer: BitWriter::new(Vec::new()),
2137            phantom: PhantomData,
2138        }
2139    }
2140
2141    /// Creates new recorder sized for the given number of bytes
2142    #[inline]
2143    pub fn with_capacity(bytes: usize) -> Self {
2144        BitRecorder {
2145            writer: BitWriter::new(Vec::with_capacity(bytes)),
2146            phantom: PhantomData,
2147        }
2148    }
2149
2150    /// Creates new recorder with the given endianness
2151    #[inline]
2152    pub fn endian(endian: E) -> Self {
2153        BitRecorder {
2154            writer: BitWriter::endian(Vec::new(), endian),
2155            phantom: PhantomData,
2156        }
2157    }
2158
2159    /// Returns number of bits written
2160    ///
2161    /// # Panics
2162    ///
2163    /// Panics if the number of bits written is
2164    /// larger than the maximum supported by the counter type.
2165    /// Use [`BitRecorder::written_checked`] for a non-panicking
2166    /// alternative.
2167    #[inline]
2168    pub fn written(&self) -> N {
2169        self.written_checked().unwrap()
2170    }
2171
2172    /// Returns number of bits written
2173    ///
2174    /// # Errors
2175    ///
2176    /// Returns an error if the number of bits written overflows
2177    /// our counter type.
2178    #[inline]
2179    pub fn written_checked(&self) -> Result<N, Overflowed> {
2180        let mut written = N::try_from(self.writer.writer.len())
2181            .map_err(|_| Overflowed)?
2182            .checked_mul(8u8.into())?;
2183
2184        written.checked_add_assign(N::try_from(self.writer.bits).map_err(|_| Overflowed)?)?;
2185
2186        Ok(written)
2187    }
2188
2189    /// Plays recorded writes to the given writer
2190    #[inline]
2191    pub fn playback<W: BitWrite>(&self, writer: &mut W) -> io::Result<()> {
2192        writer.write_bytes(self.writer.writer.as_slice())?;
2193        writer.write_var(self.writer.bits, self.writer.value)?;
2194        Ok(())
2195    }
2196
2197    /// Clears recorder, removing all values
2198    #[inline]
2199    pub fn clear(&mut self) {
2200        self.writer = BitWriter::new({
2201            let mut v = core::mem::take(&mut self.writer.writer);
2202            v.clear();
2203            v
2204        });
2205    }
2206}
2207
2208impl<N: Counter, E: Endianness> Default for BitRecorder<N, E> {
2209    #[inline]
2210    fn default() -> Self {
2211        Self::new()
2212    }
2213}
2214
2215impl<N, E> BitWrite for BitRecorder<N, E>
2216where
2217    E: Endianness,
2218    N: Counter,
2219{
2220    #[inline]
2221    fn write_bit(&mut self, bit: bool) -> io::Result<()> {
2222        BitWrite::write_bit(&mut self.writer, bit)
2223    }
2224
2225    #[inline]
2226    fn write<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
2227    where
2228        I: Integer,
2229    {
2230        BitWrite::write::<BITS, I>(&mut self.writer, value)
2231    }
2232
2233    #[inline]
2234    fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
2235        self.writer.write_const::<BITS, VALUE>()
2236    }
2237
2238    #[inline]
2239    fn write_var<I>(&mut self, bits: u32, value: I) -> io::Result<()>
2240    where
2241        I: Integer,
2242    {
2243        self.writer.write_var(bits, value)
2244    }
2245
2246    #[inline]
2247    fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
2248    where
2249        U: UnsignedInteger,
2250    {
2251        BitWrite::write_unsigned::<BITS, U>(&mut self.writer, value)
2252    }
2253
2254    #[inline]
2255    fn write_unsigned_var<U>(&mut self, bits: u32, value: U) -> io::Result<()>
2256    where
2257        U: UnsignedInteger,
2258    {
2259        self.writer.write_unsigned_var(bits, value)
2260    }
2261
2262    #[inline]
2263    fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
2264    where
2265        S: SignedInteger,
2266    {
2267        BitWrite::write_signed::<BITS, S>(&mut self.writer, value)
2268    }
2269
2270    #[inline(always)]
2271    fn write_signed_var<S>(&mut self, bits: u32, value: S) -> io::Result<()>
2272    where
2273        S: SignedInteger,
2274    {
2275        self.writer.write_signed_var(bits, value)
2276    }
2277
2278    #[inline]
2279    fn write_count<const MAX: u32>(&mut self, count: BitCount<MAX>) -> io::Result<()> {
2280        self.writer.write_count::<MAX>(count)
2281    }
2282
2283    #[inline]
2284    fn write_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>, value: I) -> io::Result<()>
2285    where
2286        I: Integer + Sized,
2287    {
2288        self.writer.write_counted::<MAX, I>(bits, value)
2289    }
2290
2291    #[inline]
2292    fn write_unsigned_counted<const BITS: u32, U>(
2293        &mut self,
2294        bits: BitCount<BITS>,
2295        value: U,
2296    ) -> io::Result<()>
2297    where
2298        U: UnsignedInteger,
2299    {
2300        self.writer.write_unsigned_counted::<BITS, U>(bits, value)
2301    }
2302
2303    #[inline]
2304    fn write_signed_counted<const MAX: u32, S>(
2305        &mut self,
2306        bits: impl TryInto<SignedBitCount<MAX>>,
2307        value: S,
2308    ) -> io::Result<()>
2309    where
2310        S: SignedInteger,
2311    {
2312        self.writer.write_signed_counted::<MAX, S>(bits, value)
2313    }
2314
2315    #[inline]
2316    fn write_from<V>(&mut self, value: V) -> io::Result<()>
2317    where
2318        V: Primitive,
2319    {
2320        BitWrite::write_from::<V>(&mut self.writer, value)
2321    }
2322
2323    #[inline]
2324    fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
2325    where
2326        F: Endianness,
2327        V: Primitive,
2328    {
2329        BitWrite::write_as_from::<F, V>(&mut self.writer, value)
2330    }
2331
2332    #[inline]
2333    fn pad(&mut self, bits: u32) -> io::Result<()> {
2334        BitWrite::pad(&mut self.writer, bits)
2335    }
2336
2337    #[inline]
2338    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
2339        BitWrite::write_bytes(&mut self.writer, buf)
2340    }
2341
2342    #[inline]
2343    fn write_unary<const STOP_BIT: u8>(&mut self, value: u32) -> io::Result<()> {
2344        self.writer.write_unary::<STOP_BIT>(value)
2345    }
2346
2347    #[inline]
2348    fn build<T: ToBitStream>(&mut self, build: &T) -> Result<(), T::Error> {
2349        BitWrite::build(&mut self.writer, build)
2350    }
2351
2352    #[inline]
2353    fn build_with<'a, T: ToBitStreamWith<'a>>(
2354        &mut self,
2355        build: &T,
2356        context: &T::Context,
2357    ) -> Result<(), T::Error> {
2358        BitWrite::build_with(&mut self.writer, build, context)
2359    }
2360
2361    #[inline]
2362    fn byte_aligned(&self) -> bool {
2363        BitWrite::byte_aligned(&self.writer)
2364    }
2365
2366    #[inline]
2367    fn byte_align(&mut self) -> io::Result<()> {
2368        BitWrite::byte_align(&mut self.writer)
2369    }
2370
2371    #[inline]
2372    fn write_huffman<T>(&mut self, value: T::Symbol) -> io::Result<()>
2373    where
2374        T: crate::huffman::ToBits,
2375    {
2376        BitWrite::write_huffman::<T>(&mut self.writer, value)
2377    }
2378}
2379
2380impl<N: PartialOrd + Counter + Copy, E: Endianness> BitRecorder<N, E> {
2381    /// Returns shortest option between ourself and candidate
2382    ///
2383    /// Executes fallible closure on emptied candidate recorder,
2384    /// compares the lengths of ourself and the candidate,
2385    /// and returns the shorter of the two.
2386    ///
2387    /// If the new candidate is shorter, we swap ourself and
2388    /// the candidate so any recorder capacity can be reused.
2389    ///
2390    /// # Example
2391    ///
2392    /// ```
2393    /// use bitstream_io::{BitRecorder, BitWrite, BigEndian};
2394    ///
2395    /// let mut best = BitRecorder::<u8, BigEndian>::new();
2396    /// let mut candidate = BitRecorder::new();
2397    ///
2398    /// // write an 8 bit value to our initial candidate
2399    /// best.write::<8, u8>(0);
2400    /// assert_eq!(best.written(), 8);
2401    ///
2402    /// // try another candidate which writes 4 bits
2403    /// best = best.best(&mut candidate, |w| {
2404    ///     w.write::<4, u8>(0)
2405    /// }).unwrap();
2406    ///
2407    /// // which becomes our new best candidate
2408    /// assert_eq!(best.written(), 4);
2409    ///
2410    /// // finally, try a not-so-best candidate
2411    /// // which writes 10 bits
2412    /// best = best.best(&mut candidate, |w| {
2413    ///     w.write::<10, u16>(0)
2414    /// }).unwrap();
2415    ///
2416    /// // so our best candidate remains 4 bits
2417    /// assert_eq!(best.written(), 4);
2418    /// ```
2419    pub fn best<F>(
2420        mut self,
2421        candidate: &mut Self,
2422        f: impl FnOnce(&mut Self) -> Result<(), F>,
2423    ) -> Result<Self, F> {
2424        candidate.clear();
2425
2426        f(candidate)?;
2427
2428        if candidate.written() < self.written() {
2429            core::mem::swap(&mut self, candidate);
2430        }
2431
2432        Ok(self)
2433    }
2434}
2435
2436#[inline]
2437fn write_byte<W>(mut writer: W, byte: u8) -> io::Result<()>
2438where
2439    W: io::Write,
2440{
2441    writer.write_all(core::slice::from_ref(&byte))
2442}
2443
2444/// For writing aligned bytes to a stream of bytes in a given endianness.
2445///
2446/// This only writes aligned values and maintains no internal state.
2447pub struct ByteWriter<W: io::Write, E: Endianness> {
2448    phantom: PhantomData<E>,
2449    writer: W,
2450}
2451
2452impl<W: io::Write, E: Endianness> ByteWriter<W, E> {
2453    /// Wraps a ByteWriter around something that implements `Write`
2454    pub fn new(writer: W) -> ByteWriter<W, E> {
2455        ByteWriter {
2456            phantom: PhantomData,
2457            writer,
2458        }
2459    }
2460
2461    /// Wraps a BitWriter around something that implements `Write`
2462    /// with the given endianness.
2463    pub fn endian(writer: W, _endian: E) -> ByteWriter<W, E> {
2464        ByteWriter {
2465            phantom: PhantomData,
2466            writer,
2467        }
2468    }
2469
2470    /// Unwraps internal writer and disposes of `ByteWriter`.
2471    /// Any unwritten partial bits are discarded.
2472    #[inline]
2473    pub fn into_writer(self) -> W {
2474        self.writer
2475    }
2476
2477    /// Provides mutable reference to internal writer.
2478    #[inline]
2479    pub fn writer(&mut self) -> &mut W {
2480        &mut self.writer
2481    }
2482
2483    /// Converts `ByteWriter` to `BitWriter` in the same endianness.
2484    #[inline]
2485    pub fn into_bitwriter(self) -> BitWriter<W, E> {
2486        BitWriter::new(self.into_writer())
2487    }
2488
2489    /// Provides temporary `BitWriter` in the same endianness.
2490    ///
2491    /// # Warning
2492    ///
2493    /// Any unwritten bits left over when `BitWriter` is dropped are lost.
2494    #[inline]
2495    pub fn bitwriter(&mut self) -> BitWriter<&mut W, E> {
2496        BitWriter::new(self.writer())
2497    }
2498}
2499
2500/// A trait for anything that can write aligned values to an output stream
2501pub trait ByteWrite {
2502    /// Writes whole numeric value to stream
2503    ///
2504    /// # Errors
2505    ///
2506    /// Passes along any I/O error from the underlying stream.
2507    /// # Examples
2508    /// ```
2509    /// use std::io::Write;
2510    /// use bitstream_io::{BigEndian, ByteWriter, ByteWrite};
2511    /// let mut writer = ByteWriter::endian(Vec::new(), BigEndian);
2512    /// writer.write(0b0000000011111111u16).unwrap();
2513    /// assert_eq!(writer.into_writer(), [0b00000000, 0b11111111]);
2514    /// ```
2515    ///
2516    /// ```
2517    /// use std::io::Write;
2518    /// use bitstream_io::{LittleEndian, ByteWriter, ByteWrite};
2519    /// let mut writer = ByteWriter::endian(Vec::new(), LittleEndian);
2520    /// writer.write(0b0000000011111111u16).unwrap();
2521    /// assert_eq!(writer.into_writer(), [0b11111111, 0b00000000]);
2522    /// ```
2523    fn write<V>(&mut self, value: V) -> io::Result<()>
2524    where
2525        V: Primitive;
2526
2527    /// Writes whole numeric value to stream in a potentially different endianness
2528    ///
2529    /// # Errors
2530    ///
2531    /// Passes along any I/O error from the underlying stream.
2532    ///
2533    /// # Examples
2534    /// ```
2535    /// use std::io::Write;
2536    /// use bitstream_io::{BigEndian, ByteWriter, ByteWrite, LittleEndian};
2537    /// let mut writer = ByteWriter::endian(Vec::new(), BigEndian);
2538    /// writer.write_as::<LittleEndian, u16>(0b0000000011111111).unwrap();
2539    /// assert_eq!(writer.into_writer(), [0b11111111, 0b00000000]);
2540    /// ```
2541    ///
2542    /// ```
2543    /// use std::io::Write;
2544    /// use bitstream_io::{BigEndian, ByteWriter, ByteWrite, LittleEndian};
2545    /// let mut writer = ByteWriter::endian(Vec::new(), LittleEndian);
2546    /// writer.write_as::<BigEndian, u16>(0b0000000011111111).unwrap();
2547    /// assert_eq!(writer.into_writer(), [0b00000000, 0b11111111]);
2548    /// ```
2549    fn write_as<F, V>(&mut self, value: V) -> io::Result<()>
2550    where
2551        F: Endianness,
2552        V: Primitive;
2553
2554    /// Writes the entirety of a byte buffer to the stream.
2555    ///
2556    /// # Errors
2557    ///
2558    /// Passes along any I/O error from the underlying stream.
2559    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()>;
2560
2561    /// Pads the stream by writing 0 over the given number of bytes.
2562    ///
2563    /// # Errors
2564    ///
2565    /// Passes along any I/O error from the underlying stream.
2566    fn pad(&mut self, bytes: u32) -> io::Result<()>;
2567
2568    /// Builds and writes complex type
2569    fn build<T: ToByteStream>(&mut self, build: &T) -> Result<(), T::Error> {
2570        build.to_writer(self)
2571    }
2572
2573    /// Builds and writes complex type with context
2574    fn build_with<'a, T: ToByteStreamWith<'a>>(
2575        &mut self,
2576        build: &T,
2577        context: &T::Context,
2578    ) -> Result<(), T::Error> {
2579        build.to_writer(self, context)
2580    }
2581
2582    /// Returns mutable reference to underlying writer
2583    fn writer_ref(&mut self) -> &mut dyn io::Write;
2584}
2585
2586impl<W: io::Write, E: Endianness> ByteWrite for ByteWriter<W, E> {
2587    #[inline]
2588    fn write<V>(&mut self, value: V) -> io::Result<()>
2589    where
2590        V: Primitive,
2591    {
2592        self.writer.write_all(E::primitive_to_bytes(value).as_ref())
2593    }
2594
2595    #[inline]
2596    fn write_as<F, V>(&mut self, value: V) -> io::Result<()>
2597    where
2598        F: Endianness,
2599        V: Primitive,
2600    {
2601        self.writer.write_all(F::primitive_to_bytes(value).as_ref())
2602    }
2603
2604    #[inline]
2605    fn pad(&mut self, mut bytes: u32) -> io::Result<()> {
2606        let buf = [0u8; 8];
2607
2608        while bytes > 0 {
2609            let to_write = bytes.min(8);
2610            self.write_bytes(&buf[0..to_write as usize])?;
2611            bytes -= to_write;
2612        }
2613        Ok(())
2614    }
2615
2616    #[inline]
2617    fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
2618        self.writer.write_all(buf)
2619    }
2620
2621    #[inline]
2622    fn writer_ref(&mut self) -> &mut dyn io::Write {
2623        &mut self.writer
2624    }
2625}
2626
2627/// Implemented by complex types that don't require any additional context
2628/// to build themselves to a writer
2629///
2630/// # Example
2631/// ```
2632/// use std::io::Read;
2633/// use bitstream_io::{BigEndian, BitWrite, BitWriter, ToBitStream};
2634///
2635/// #[derive(Debug, PartialEq, Eq)]
2636/// struct BlockHeader {
2637///     last_block: bool,
2638///     block_type: u8,
2639///     block_size: u32,
2640/// }
2641///
2642/// impl ToBitStream for BlockHeader {
2643///     type Error = std::io::Error;
2644///
2645///     fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> std::io::Result<()> {
2646///         w.write_bit(self.last_block)?;
2647///         w.write::<7, _>(self.block_type)?;
2648///         w.write::<24, _>(self.block_size)
2649///     }
2650/// }
2651///
2652/// let mut data = Vec::new();
2653/// let mut writer = BitWriter::endian(&mut data, BigEndian);
2654/// writer.build(&BlockHeader { last_block: false, block_type: 4, block_size: 122 }).unwrap();
2655/// assert_eq!(data, b"\x04\x00\x00\x7A");
2656/// ```
2657pub trait ToBitStream {
2658    /// Error generated during building, such as `io::Error`
2659    type Error;
2660
2661    /// Generate self to writer
2662    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error>
2663    where
2664        Self: Sized;
2665
2666    /// Returns total length of self, if possible
2667    fn bits_len<C: Counter>(&self) -> Result<C, Self::Error>
2668    where
2669        Self: Sized,
2670    {
2671        let mut c: BitCounter<C> = BitCounter::new();
2672        self.to_writer(&mut c)?;
2673        Ok(c.into_written())
2674    }
2675}
2676
2677/// Implemented by complex types that require additional context
2678/// to build themselves to a writer
2679pub trait ToBitStreamWith<'a> {
2680    /// Some context to use when writing
2681    type Context: 'a;
2682
2683    /// Error generated during building, such as `io::Error`
2684    type Error;
2685
2686    /// Generate self to writer
2687    fn to_writer<W: BitWrite + ?Sized>(
2688        &self,
2689        w: &mut W,
2690        context: &Self::Context,
2691    ) -> Result<(), Self::Error>
2692    where
2693        Self: Sized;
2694
2695    /// Returns total length of self, if possible
2696    fn bits_len<C: Counter>(&self, context: &Self::Context) -> Result<C, Self::Error>
2697    where
2698        Self: Sized,
2699    {
2700        let mut c: BitCounter<C> = BitCounter::new();
2701        self.to_writer(&mut c, context)?;
2702        Ok(c.into_written())
2703    }
2704}
2705
2706/// Implemented by complex types that don't require any additional context
2707/// to build themselves to a writer
2708pub trait ToByteStream {
2709    /// Error generated during building, such as `io::Error`
2710    type Error;
2711
2712    /// Generate self to writer
2713    fn to_writer<W: ByteWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error>
2714    where
2715        Self: Sized;
2716}
2717
2718/// Implemented by complex types that require additional context
2719/// to build themselves to a writer
2720pub trait ToByteStreamWith<'a> {
2721    /// Some context to use when writing
2722    type Context: 'a;
2723
2724    /// Error generated during building, such as `io::Error`
2725    type Error;
2726
2727    /// Generate self to writer
2728    fn to_writer<W: ByteWrite + ?Sized>(
2729        &self,
2730        w: &mut W,
2731        context: &Self::Context,
2732    ) -> Result<(), Self::Error>
2733    where
2734        Self: Sized;
2735}