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