Skip to main content

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