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
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,
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 /// Creates a "by reference" adaptor for this `BitWrite`
966 ///
967 /// The returned adapter also implements `BitWrite`
968 /// and will borrow the current reader.
969 ///
970 /// # Example
971 /// ```
972 /// use bitstream_io::{BitWriter, BitWrite, BigEndian};
973 ///
974 /// fn build<W: BitWrite>(w: W) {
975 /// // perform some building
976 /// }
977 ///
978 /// let mut writer = BitWriter::endian(vec![], BigEndian);
979 /// // performing building by reference
980 /// build(writer.by_ref());
981 /// // original owned writer still available
982 /// writer.write::<8, u8>(0).unwrap();
983 /// assert_eq!(writer.into_writer(), &[0]);
984 /// ```
985 #[inline]
986 fn by_ref(&mut self) -> &mut Self {
987 self
988 }
989}
990
991impl<W: BitWrite + ?Sized> BitWrite for &mut W {
992 #[inline]
993 fn write_bit(&mut self, bit: bool) -> io::Result<()> {
994 (**self).write_bit(bit)
995 }
996
997 #[inline]
998 fn write<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
999 where
1000 I: Integer,
1001 {
1002 (**self).write::<BITS, I>(value)
1003 }
1004
1005 #[inline]
1006 fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
1007 (**self).write_const::<BITS, VALUE>()
1008 }
1009
1010 #[inline]
1011 fn write_var<I>(&mut self, bits: u32, value: I) -> io::Result<()>
1012 where
1013 I: Integer,
1014 {
1015 (**self).write_var(bits, value)
1016 }
1017
1018 #[inline]
1019 fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1020 where
1021 U: UnsignedInteger,
1022 {
1023 (**self).write_unsigned::<BITS, U>(value)
1024 }
1025
1026 #[inline]
1027 fn write_unsigned_var<U>(&mut self, bits: u32, value: U) -> io::Result<()>
1028 where
1029 U: UnsignedInteger,
1030 {
1031 (**self).write_unsigned_var(bits, value)
1032 }
1033
1034 #[inline]
1035 fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1036 where
1037 S: SignedInteger,
1038 {
1039 (**self).write_signed::<BITS, S>(value)
1040 }
1041
1042 #[inline(always)]
1043 fn write_signed_var<S>(&mut self, bits: u32, value: S) -> io::Result<()>
1044 where
1045 S: SignedInteger,
1046 {
1047 (**self).write_signed_var(bits, value)
1048 }
1049
1050 #[inline]
1051 fn write_count<const MAX: u32>(&mut self, count: BitCount<MAX>) -> io::Result<()> {
1052 (**self).write_count::<MAX>(count)
1053 }
1054
1055 #[inline]
1056 fn write_counted<const MAX: u32, I>(&mut self, bits: BitCount<MAX>, value: I) -> io::Result<()>
1057 where
1058 I: Integer + Sized,
1059 {
1060 (**self).write_counted::<MAX, I>(bits, value)
1061 }
1062
1063 #[inline]
1064 fn write_unsigned_counted<const BITS: u32, U>(
1065 &mut self,
1066 bits: BitCount<BITS>,
1067 value: U,
1068 ) -> io::Result<()>
1069 where
1070 U: UnsignedInteger,
1071 {
1072 (**self).write_unsigned_counted::<BITS, U>(bits, value)
1073 }
1074
1075 #[inline]
1076 fn write_signed_counted<const MAX: u32, S>(
1077 &mut self,
1078 bits: impl TryInto<SignedBitCount<MAX>>,
1079 value: S,
1080 ) -> io::Result<()>
1081 where
1082 S: SignedInteger,
1083 {
1084 (**self).write_signed_counted::<MAX, S>(bits, value)
1085 }
1086
1087 #[inline]
1088 fn write_from<V>(&mut self, value: V) -> io::Result<()>
1089 where
1090 V: Primitive,
1091 {
1092 (**self).write_from::<V>(value)
1093 }
1094
1095 #[inline]
1096 fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1097 where
1098 F: Endianness,
1099 V: Primitive,
1100 {
1101 (**self).write_as_from::<F, V>(value)
1102 }
1103
1104 #[inline]
1105 fn pad(&mut self, bits: u32) -> io::Result<()> {
1106 (**self).pad(bits)
1107 }
1108
1109 #[inline]
1110 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1111 (**self).write_bytes(buf)
1112 }
1113
1114 #[inline]
1115 fn write_unary<const STOP_BIT: u8>(&mut self, value: u32) -> io::Result<()> {
1116 (**self).write_unary::<STOP_BIT>(value)
1117 }
1118
1119 #[inline]
1120 fn write_checked<C: Checkable>(&mut self, value: C) -> io::Result<()> {
1121 (**self).write_checked(value)
1122 }
1123
1124 #[inline]
1125 fn build<T: ToBitStream>(&mut self, build: &T) -> Result<(), T::Error> {
1126 (**self).build(build)
1127 }
1128
1129 #[inline]
1130 fn build_with<'a, T: ToBitStreamWith<'a>>(
1131 &mut self,
1132 build: &T,
1133 context: &T::Context,
1134 ) -> Result<(), T::Error> {
1135 (**self).build_with(build, context)
1136 }
1137
1138 #[inline]
1139 fn byte_aligned(&self) -> bool {
1140 (**self).byte_aligned()
1141 }
1142
1143 #[inline]
1144 fn byte_align(&mut self) -> io::Result<()> {
1145 (**self).byte_align()
1146 }
1147
1148 #[inline]
1149 fn write_huffman<T>(&mut self, value: T::Symbol) -> io::Result<()>
1150 where
1151 T: crate::huffman::ToBits,
1152 {
1153 (**self).write_huffman::<T>(value)
1154 }
1155}
1156
1157/// A compatibility trait for older code implementing [`BitWrite`]
1158///
1159/// This is a trait largely compatible with older code
1160/// from the 2.X.X version,
1161/// which one can use with a named import as needed.
1162///
1163/// New code should prefer the regular [`BitWrite`] trait.
1164///
1165/// # Example
1166/// ```
1167/// use bitstream_io::BitWrite2 as BitWrite;
1168/// use bitstream_io::{BitWriter, BigEndian};
1169/// let mut byte = vec![];
1170/// let mut writer = BitWriter::endian(byte, BigEndian);
1171/// writer.write::<u8>(4, 0b1111).unwrap();
1172/// writer.write_out::<4, u8>(0b0000).unwrap();
1173/// assert_eq!(writer.into_writer(), [0b1111_0000]);
1174/// ```
1175pub trait BitWrite2 {
1176 /// Writes a single bit to the stream.
1177 /// `true` indicates 1, `false` indicates 0
1178 ///
1179 /// # Errors
1180 ///
1181 /// Passes along any I/O error from the underlying stream.
1182 fn write_bit(&mut self, bit: bool) -> io::Result<()> {
1183 self.write_unsigned_out::<1, u8>(u8::from(bit))
1184 }
1185
1186 /// Writes a signed or unsigned value to the stream using the given
1187 /// number of bits.
1188 ///
1189 /// # Errors
1190 ///
1191 /// Passes along any I/O error from the underlying stream.
1192 /// Returns an error if the input type is too small
1193 /// to hold the given number of bits.
1194 /// Returns an error if the value is too large
1195 /// to fit the given number of bits.
1196 fn write<I>(&mut self, bits: u32, value: I) -> io::Result<()>
1197 where
1198 I: Integer;
1199
1200 /// Writes a signed or unsigned value to the stream using the given
1201 /// const number of bits.
1202 ///
1203 /// # Errors
1204 ///
1205 /// Passes along any I/O error from the underlying stream.
1206 /// Returns an error if the value is too large
1207 /// to fit the given number of bits.
1208 /// A compile-time error occurs if the given number of bits
1209 /// is larger than the output type.
1210 fn write_out<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
1211 where
1212 I: Integer;
1213
1214 /// Writes an unsigned value to the stream using the given
1215 /// number of bits.
1216 ///
1217 /// # Errors
1218 ///
1219 /// Passes along any I/O error from the underlying stream.
1220 /// Returns an error if the input type is too small
1221 /// to hold the given number of bits.
1222 /// Returns an error if the value is too large
1223 /// to fit the given number of bits.
1224 fn write_unsigned<U>(&mut self, bits: u32, value: U) -> io::Result<()>
1225 where
1226 U: UnsignedInteger;
1227
1228 /// Writes an unsigned value to the stream using the given
1229 /// const number of bits.
1230 ///
1231 /// # Errors
1232 ///
1233 /// Passes along any I/O error from the underlying stream.
1234 /// Returns an error if the value is too large
1235 /// to fit the given number of bits.
1236 /// A compile-time error occurs if the given number of bits
1237 /// is larger than the output type.
1238 #[inline]
1239 fn write_unsigned_out<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1240 where
1241 U: UnsignedInteger,
1242 {
1243 self.write_unsigned(BITS, value)
1244 }
1245
1246 /// Writes a twos-complement signed value to the stream
1247 /// with the given number of bits.
1248 ///
1249 /// # Errors
1250 ///
1251 /// Passes along any I/O error from the underlying stream.
1252 /// Returns an error if the input type is too small
1253 /// to hold the given number of bits.
1254 /// Returns an error if the number of bits is 0,
1255 /// since one bit is always needed for the sign.
1256 /// Returns an error if the value is too large
1257 /// to fit the given number of bits.
1258 fn write_signed<S>(&mut self, bits: u32, value: S) -> io::Result<()>
1259 where
1260 S: SignedInteger;
1261
1262 /// Writes a twos-complement signed value to the stream
1263 /// with the given const number of bits.
1264 ///
1265 /// # Errors
1266 ///
1267 /// Passes along any I/O error from the underlying stream.
1268 /// Returns an error if the value is too large
1269 /// to fit the given number of bits.
1270 /// A compile-time error occurs if the number of bits is 0,
1271 /// since one bit is always needed for the sign.
1272 /// A compile-time error occurs if the given number of bits
1273 /// is larger than the output type.
1274 fn write_signed_out<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1275 where
1276 S: SignedInteger,
1277 {
1278 self.write_signed(BITS, value)
1279 }
1280
1281 /// Writes whole value to the stream whose size in bits
1282 /// is equal to its type's size.
1283 ///
1284 /// # Errors
1285 ///
1286 /// Passes along any I/O error from the underlying stream.
1287 fn write_from<V>(&mut self, value: V) -> io::Result<()>
1288 where
1289 V: Primitive;
1290
1291 /// Writes whole value to the stream whose size in bits
1292 /// is equal to its type's size in an endianness that may
1293 /// be different from the stream's endianness.
1294 ///
1295 /// # Errors
1296 ///
1297 /// Passes along any I/O error from the underlying stream.
1298 fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1299 where
1300 F: Endianness,
1301 V: Primitive;
1302
1303 /// Pads the stream by writing 0 over the given number of bits.
1304 ///
1305 /// # Errors
1306 ///
1307 /// Passes along any I/O error from the underlying stream.
1308 fn pad(&mut self, mut bits: u32) -> io::Result<()> {
1309 loop {
1310 match bits {
1311 0 => break Ok(()),
1312 bits @ 1..64 => break self.write(bits, 0u64),
1313 _ => {
1314 self.write_out::<64, u64>(0)?;
1315 bits -= 64;
1316 }
1317 }
1318 }
1319 }
1320
1321 /// Writes the entirety of a byte buffer to the stream.
1322 ///
1323 /// # Errors
1324 ///
1325 /// Passes along any I/O error from the underlying stream.
1326 ///
1327 /// # Example
1328 ///
1329 /// ```
1330 /// use std::io::Write;
1331 /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
1332 /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
1333 /// writer.write_var(8, 0x66u8).unwrap();
1334 /// writer.write_var(8, 0x6Fu8).unwrap();
1335 /// writer.write_var(8, 0x6Fu8).unwrap();
1336 /// writer.write_bytes(b"bar").unwrap();
1337 /// assert_eq!(writer.into_writer(), b"foobar");
1338 /// ```
1339 #[inline]
1340 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1341 buf.iter()
1342 .try_for_each(|b| self.write_unsigned_out::<8, _>(*b))
1343 }
1344
1345 /// Writes `value` number of 1 bits to the stream
1346 /// and then writes a 0 bit. This field is variably-sized.
1347 ///
1348 /// # Errors
1349 ///
1350 /// Passes along any I/O error from the underyling stream.
1351 fn write_unary0(&mut self, value: u32) -> io::Result<()>;
1352
1353 /// Writes `value` number of 0 bits to the stream
1354 /// and then writes a 1 bit. This field is variably-sized.
1355 ///
1356 /// # Errors
1357 ///
1358 /// Passes along any I/O error from the underyling stream.
1359 fn write_unary1(&mut self, value: u32) -> io::Result<()>;
1360
1361 /// Builds and writes complex type
1362 fn build<T: ToBitStream>(&mut self, build: &T) -> Result<(), T::Error>
1363 where
1364 Self: BitWrite,
1365 {
1366 build.to_writer(self)
1367 }
1368
1369 /// Builds and writes complex type with context
1370 fn build_with<'a, T: ToBitStreamWith<'a>>(
1371 &mut self,
1372 build: &T,
1373 context: &T::Context,
1374 ) -> Result<(), T::Error>
1375 where
1376 Self: BitWrite,
1377 {
1378 build.to_writer(self, context)
1379 }
1380
1381 /// Returns true if the stream is aligned at a whole byte.
1382 fn byte_aligned(&self) -> bool;
1383
1384 /// Pads the stream with 0 bits until it is aligned at a whole byte.
1385 /// Does nothing if the stream is already aligned.
1386 ///
1387 /// # Errors
1388 ///
1389 /// Passes along any I/O error from the underyling stream.
1390 ///
1391 /// # Example
1392 /// ```
1393 /// use std::io::Write;
1394 /// use bitstream_io::{BigEndian, BitWriter, BitWrite};
1395 /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
1396 /// writer.write_var(1, 0u8).unwrap();
1397 /// writer.byte_align().unwrap();
1398 /// writer.write_var(8, 0xFFu8).unwrap();
1399 /// assert_eq!(writer.into_writer(), [0x00, 0xFF]);
1400 /// ```
1401 fn byte_align(&mut self) -> io::Result<()> {
1402 while !self.byte_aligned() {
1403 self.write_bit(false)?;
1404 }
1405 Ok(())
1406 }
1407
1408 /// Given a symbol, writes its representation to the output stream as bits.
1409 /// Generates no output if the symbol isn't defined in the Huffman tree.
1410 ///
1411 /// # Errors
1412 ///
1413 /// Passes along any I/O error from the underlying stream.
1414 ///
1415 /// # Example
1416 /// ```
1417 /// use std::io::Write;
1418 /// use bitstream_io::{BigEndian, BitWriter, BitWrite2};
1419 /// use bitstream_io::define_huffman_tree;
1420 /// define_huffman_tree!(TreeName : char = ['a', ['b', ['c', 'd']]]);
1421 /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
1422 /// writer.write_huffman::<TreeName>('b').unwrap();
1423 /// writer.write_huffman::<TreeName>('c').unwrap();
1424 /// writer.write_huffman::<TreeName>('d').unwrap();
1425 /// assert_eq!(writer.into_writer(), [0b10_110_111]);
1426 /// ```
1427 fn write_huffman<T>(&mut self, value: T::Symbol) -> io::Result<()>
1428 where
1429 T: crate::huffman::ToBits,
1430 {
1431 T::to_bits(value, |b| self.write_bit(b))
1432 }
1433}
1434
1435impl<W: BitWrite> BitWrite2 for W {
1436 #[inline]
1437 fn write_bit(&mut self, bit: bool) -> io::Result<()> {
1438 BitWrite::write_bit(self, bit)
1439 }
1440
1441 #[inline]
1442 fn write<I>(&mut self, bits: u32, value: I) -> io::Result<()>
1443 where
1444 I: Integer,
1445 {
1446 BitWrite::write_var(self, bits, value)
1447 }
1448
1449 #[inline]
1450 fn write_out<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
1451 where
1452 I: Integer,
1453 {
1454 BitWrite::write::<BITS, I>(self, value)
1455 }
1456
1457 #[inline]
1458 fn write_unsigned<U>(&mut self, bits: u32, value: U) -> io::Result<()>
1459 where
1460 U: UnsignedInteger,
1461 {
1462 BitWrite::write_unsigned_var::<U>(self, bits, value)
1463 }
1464
1465 #[inline]
1466 fn write_unsigned_out<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1467 where
1468 U: UnsignedInteger,
1469 {
1470 BitWrite::write_unsigned::<BITS, U>(self, value)
1471 }
1472
1473 #[inline]
1474 fn write_signed<S>(&mut self, bits: u32, value: S) -> io::Result<()>
1475 where
1476 S: SignedInteger,
1477 {
1478 BitWrite::write_signed_var::<S>(self, bits, value)
1479 }
1480
1481 #[inline]
1482 fn write_signed_out<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1483 where
1484 S: SignedInteger,
1485 {
1486 BitWrite::write_signed::<BITS, S>(self, value)
1487 }
1488
1489 #[inline]
1490 fn write_from<V>(&mut self, value: V) -> io::Result<()>
1491 where
1492 V: Primitive,
1493 {
1494 BitWrite::write_from(self, value)
1495 }
1496
1497 #[inline]
1498 fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1499 where
1500 F: Endianness,
1501 V: Primitive,
1502 {
1503 BitWrite::write_as_from::<F, V>(self, value)
1504 }
1505
1506 #[inline]
1507 fn pad(&mut self, bits: u32) -> io::Result<()> {
1508 BitWrite::pad(self, bits)
1509 }
1510
1511 #[inline]
1512 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1513 BitWrite::write_bytes(self, buf)
1514 }
1515
1516 #[inline]
1517 fn write_unary0(&mut self, value: u32) -> io::Result<()> {
1518 BitWrite::write_unary::<0>(self, value)
1519 }
1520
1521 #[inline]
1522 fn write_unary1(&mut self, value: u32) -> io::Result<()> {
1523 BitWrite::write_unary::<1>(self, value)
1524 }
1525
1526 #[inline]
1527 fn byte_aligned(&self) -> bool {
1528 BitWrite::byte_aligned(self)
1529 }
1530
1531 #[inline]
1532 fn byte_align(&mut self) -> io::Result<()> {
1533 BitWrite::byte_align(self)
1534 }
1535}
1536
1537impl<W: io::Write, E: Endianness> BitWrite for BitWriter<W, E> {
1538 fn write_bit(&mut self, bit: bool) -> io::Result<()> {
1539 match E::push_bit_flush(&mut self.value, &mut self.bits, bit) {
1540 None => Ok(()),
1541 Some(byte) => write_byte(&mut self.writer, byte),
1542 }
1543 }
1544
1545 #[inline(always)]
1546 fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1547 where
1548 U: UnsignedInteger,
1549 {
1550 let Self {
1551 value: queue_value,
1552 bits: queue_bits,
1553 writer,
1554 ..
1555 } = self;
1556
1557 E::write_bits_checked(
1558 writer,
1559 queue_value,
1560 queue_bits,
1561 CheckedUnsigned::<BITS, U>::new_fixed::<BITS>(value)?,
1562 )
1563 }
1564
1565 fn write_unsigned_counted<const BITS: u32, U>(
1566 &mut self,
1567 count: BitCount<BITS>,
1568 value: U,
1569 ) -> io::Result<()>
1570 where
1571 U: UnsignedInteger,
1572 {
1573 let Self {
1574 value: queue_value,
1575 bits: queue_bits,
1576 writer,
1577 ..
1578 } = self;
1579
1580 E::write_bits_checked(
1581 writer,
1582 queue_value,
1583 queue_bits,
1584 CheckedUnsigned::new(count, value)?,
1585 )
1586 }
1587
1588 #[inline(always)]
1589 fn write_signed_counted<const BITS: u32, S>(
1590 &mut self,
1591 bits: impl TryInto<SignedBitCount<BITS>>,
1592 value: S,
1593 ) -> io::Result<()>
1594 where
1595 S: SignedInteger,
1596 {
1597 E::write_signed_bits_checked(
1598 &mut self.writer,
1599 &mut self.value,
1600 &mut self.bits,
1601 CheckedSigned::new(
1602 bits.try_into().map_err(|_| {
1603 io::Error::new(
1604 io::ErrorKind::InvalidInput,
1605 "signed writes need at least 1 bit for sign",
1606 )
1607 })?,
1608 value,
1609 )?,
1610 )
1611 }
1612
1613 #[inline]
1614 fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1615 where
1616 S: SignedInteger,
1617 {
1618 E::write_signed_bits_checked(
1619 &mut self.writer,
1620 &mut self.value,
1621 &mut self.bits,
1622 CheckedSigned::<BITS, _>::new_fixed::<BITS>(value)?,
1623 )
1624 }
1625
1626 #[inline]
1627 fn write_from<V>(&mut self, value: V) -> io::Result<()>
1628 where
1629 V: Primitive,
1630 {
1631 E::write_bytes::<8, _>(
1632 &mut self.writer,
1633 &mut self.value,
1634 self.bits,
1635 E::primitive_to_bytes(value).as_ref(),
1636 )
1637 }
1638
1639 #[inline]
1640 fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
1641 where
1642 F: Endianness,
1643 V: Primitive,
1644 {
1645 F::write_bytes::<8, _>(
1646 &mut self.writer,
1647 &mut self.value,
1648 self.bits,
1649 F::primitive_to_bytes(value).as_ref(),
1650 )
1651 }
1652
1653 #[inline]
1654 fn write_checked<C: Checkable>(&mut self, value: C) -> io::Result<()> {
1655 value.write_endian::<E, _>(&mut self.writer, &mut self.value, &mut self.bits)
1656 }
1657
1658 #[inline]
1659 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1660 E::write_bytes::<1024, _>(&mut self.writer, &mut self.value, self.bits, buf)
1661 }
1662
1663 #[inline(always)]
1664 fn byte_aligned(&self) -> bool {
1665 self.bits == 0
1666 }
1667}
1668
1669/// An error returned if performing math operations would overflow
1670#[derive(Copy, Clone, Debug)]
1671pub struct Overflowed;
1672
1673impl fmt::Display for Overflowed {
1674 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1675 "overflow occured in counter".fmt(f)
1676 }
1677}
1678
1679impl core::error::Error for Overflowed {}
1680
1681impl From<Overflowed> for io::Error {
1682 fn from(Overflowed: Overflowed) -> Self {
1683 io::Error::new(
1684 #[cfg(feature = "std")]
1685 {
1686 io::ErrorKind::StorageFull
1687 },
1688 #[cfg(not(feature = "std"))]
1689 {
1690 io::ErrorKind::Other
1691 },
1692 "bitstream accumulator overflow",
1693 )
1694 }
1695}
1696
1697/// A common trait for integer types for performing math operations
1698/// which may check for overflow.
1699pub trait Counter: Default + Sized + From<u8> + TryFrom<u32> + TryFrom<usize> {
1700 /// add rhs to self, returning `Overflowed` if the result is too large
1701 fn checked_add_assign(&mut self, rhs: Self) -> Result<(), Overflowed>;
1702
1703 /// multiply self by rhs, returning `Overflowed` if the result is too large
1704 fn checked_mul(self, rhs: Self) -> Result<Self, Overflowed>;
1705
1706 /// returns `true` if the number if bits written is divisible by 8
1707 fn byte_aligned(&self) -> bool;
1708}
1709
1710macro_rules! define_counter {
1711 ($t:ty) => {
1712 impl Counter for $t {
1713 fn checked_add_assign(&mut self, rhs: Self) -> Result<(), Overflowed> {
1714 *self = <$t>::checked_add(*self, rhs).ok_or(Overflowed)?;
1715 Ok(())
1716 }
1717
1718 fn checked_mul(self, rhs: Self) -> Result<Self, Overflowed> {
1719 <$t>::checked_mul(self, rhs).ok_or(Overflowed)
1720 }
1721
1722 fn byte_aligned(&self) -> bool {
1723 self % 8 == 0
1724 }
1725 }
1726 };
1727}
1728
1729define_counter!(u8);
1730define_counter!(u16);
1731define_counter!(u32);
1732define_counter!(u64);
1733define_counter!(u128);
1734
1735/// For counting the number of bits written but generating no output.
1736///
1737/// # Example
1738/// ```
1739/// use bitstream_io::{BigEndian, BitWrite, BitsWritten};
1740/// let mut writer: BitsWritten<u32> = BitsWritten::new();
1741/// writer.write_var(1, 0b1u8).unwrap();
1742/// writer.write_var(2, 0b01u8).unwrap();
1743/// writer.write_var(5, 0b10111u8).unwrap();
1744/// assert_eq!(writer.written(), 8);
1745/// ```
1746#[derive(Default)]
1747pub struct BitsWritten<N> {
1748 bits: N,
1749}
1750
1751impl<N: Default> BitsWritten<N> {
1752 /// Creates new empty BitsWritten value
1753 #[inline]
1754 pub fn new() -> Self {
1755 Self { bits: N::default() }
1756 }
1757}
1758
1759impl<N: Copy> BitsWritten<N> {
1760 /// Returns number of bits written
1761 #[inline]
1762 pub fn written(&self) -> N {
1763 self.bits
1764 }
1765}
1766
1767impl<N> BitsWritten<N> {
1768 /// Returns number of bits written
1769 #[inline]
1770 pub fn into_written(self) -> N {
1771 self.bits
1772 }
1773}
1774
1775impl<N: Counter> BitWrite for BitsWritten<N> {
1776 #[inline]
1777 fn write_bit(&mut self, _bit: bool) -> io::Result<()> {
1778 self.bits.checked_add_assign(1u8.into())?;
1779 Ok(())
1780 }
1781
1782 #[inline]
1783 fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
1784 const {
1785 assert!(
1786 BITS == 0 || VALUE <= (u32::ALL >> (u32::BITS_SIZE - BITS)),
1787 "excessive value for bits written"
1788 );
1789 }
1790
1791 self.bits
1792 .checked_add_assign(BITS.try_into().map_err(|_| Overflowed)?)?;
1793 Ok(())
1794 }
1795
1796 #[inline]
1797 fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
1798 where
1799 U: UnsignedInteger,
1800 {
1801 const {
1802 assert!(BITS <= U::BITS_SIZE, "excessive bits for type written");
1803 }
1804
1805 if BITS == 0 {
1806 Ok(())
1807 } else if value <= (U::ALL >> (U::BITS_SIZE - BITS)) {
1808 self.bits
1809 .checked_add_assign(BITS.try_into().map_err(|_| Overflowed)?)?;
1810 Ok(())
1811 } else {
1812 Err(io::Error::new(
1813 io::ErrorKind::InvalidInput,
1814 "excessive value for bits written",
1815 ))
1816 }
1817 }
1818
1819 #[inline]
1820 fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
1821 where
1822 S: SignedInteger,
1823 {
1824 let SignedBitCount {
1825 bits: BitCount { bits },
1826 unsigned,
1827 } = const {
1828 assert!(BITS <= S::BITS_SIZE, "excessive bits for type written");
1829 let count = BitCount::<BITS>::new::<BITS>().signed_count();
1830 assert!(
1831 count.is_some(),
1832 "signed writes need at least 1 bit for sign"
1833 );
1834 count.unwrap()
1835 };
1836
1837 // doesn't matter which side the sign is on
1838 // so long as it's added to the bit count
1839 self.bits.checked_add_assign(1u8.into())?;
1840
1841 self.write_unsigned_counted(
1842 unsigned,
1843 if value.is_negative() {
1844 value.as_negative(bits)
1845 } else {
1846 value.as_non_negative()
1847 },
1848 )
1849 }
1850
1851 #[inline]
1852 fn write_unsigned_counted<const MAX: u32, U>(
1853 &mut self,
1854 BitCount { bits }: BitCount<MAX>,
1855 value: U,
1856 ) -> io::Result<()>
1857 where
1858 U: UnsignedInteger,
1859 {
1860 if MAX <= U::BITS_SIZE || bits <= U::BITS_SIZE {
1861 if bits == 0 {
1862 Ok(())
1863 } else if value <= U::ALL >> (U::BITS_SIZE - bits) {
1864 self.bits
1865 .checked_add_assign(bits.try_into().map_err(|_| Overflowed)?)?;
1866 Ok(())
1867 } else {
1868 Err(io::Error::new(
1869 io::ErrorKind::InvalidInput,
1870 "excessive value for bits written",
1871 ))
1872 }
1873 } else {
1874 Err(io::Error::new(
1875 io::ErrorKind::InvalidInput,
1876 "excessive bits for type written",
1877 ))
1878 }
1879 }
1880
1881 #[inline]
1882 fn write_signed_counted<const MAX: u32, S>(
1883 &mut self,
1884 bits: impl TryInto<SignedBitCount<MAX>>,
1885 value: S,
1886 ) -> io::Result<()>
1887 where
1888 S: SignedInteger,
1889 {
1890 let SignedBitCount {
1891 bits: BitCount { bits },
1892 unsigned,
1893 } = bits.try_into().map_err(|_| {
1894 io::Error::new(
1895 io::ErrorKind::InvalidInput,
1896 "signed writes need at least 1 bit for sign",
1897 )
1898 })?;
1899
1900 if MAX <= S::BITS_SIZE || bits <= S::BITS_SIZE {
1901 // doesn't matter which side the sign is on
1902 // so long as it's added to the bit count
1903 self.bits.checked_add_assign(1u8.into())?;
1904
1905 self.write_unsigned_counted(
1906 unsigned,
1907 if value.is_negative() {
1908 value.as_negative(bits)
1909 } else {
1910 value.as_non_negative()
1911 },
1912 )
1913 } else {
1914 Err(io::Error::new(
1915 io::ErrorKind::InvalidInput,
1916 "excessive bits for type written",
1917 ))
1918 }
1919 }
1920
1921 #[inline]
1922 fn write_from<V>(&mut self, _: V) -> io::Result<()>
1923 where
1924 V: Primitive,
1925 {
1926 self.bits.checked_add_assign(
1927 N::try_from(core::mem::size_of::<V>())
1928 .map_err(|_| Overflowed)?
1929 .checked_mul(8u8.into())?,
1930 )?;
1931 Ok(())
1932 }
1933
1934 #[inline]
1935 fn write_as_from<F, V>(&mut self, _: V) -> io::Result<()>
1936 where
1937 F: Endianness,
1938 V: Primitive,
1939 {
1940 self.bits.checked_add_assign(
1941 N::try_from(core::mem::size_of::<V>())
1942 .map_err(|_| Overflowed)?
1943 .checked_mul(8u8.into())?,
1944 )?;
1945 Ok(())
1946 }
1947
1948 #[inline]
1949 fn pad(&mut self, bits: u32) -> io::Result<()> {
1950 self.bits
1951 .checked_add_assign(bits.try_into().map_err(|_| Overflowed)?)?;
1952 Ok(())
1953 }
1954
1955 #[inline]
1956 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
1957 self.bits.checked_add_assign(
1958 N::try_from(buf.len())
1959 .map_err(|_| Overflowed)?
1960 .checked_mul(8u8.into())?,
1961 )?;
1962 Ok(())
1963 }
1964
1965 fn write_unary<const STOP_BIT: u8>(&mut self, value: u32) -> io::Result<()> {
1966 const {
1967 assert!(matches!(STOP_BIT, 0 | 1), "stop bit must be 0 or 1");
1968 }
1969
1970 self.bits
1971 .checked_add_assign(value.try_into().map_err(|_| Overflowed)?)?;
1972 self.bits.checked_add_assign(1u8.into())?;
1973 Ok(())
1974 }
1975
1976 fn write_checked<C: Checkable>(&mut self, value: C) -> io::Result<()> {
1977 Ok(self
1978 .bits
1979 .checked_add_assign(value.written_bits().try_into().map_err(|_| Overflowed)?)?)
1980 }
1981
1982 #[inline]
1983 fn byte_aligned(&self) -> bool {
1984 self.bits.byte_aligned()
1985 }
1986}
1987
1988/// For counting the number of bits written but generating no output.
1989///
1990/// # Example
1991/// ```
1992/// use bitstream_io::{BigEndian, BitWrite, BitCounter};
1993/// let mut writer: BitCounter<u32, BigEndian> = BitCounter::new();
1994/// writer.write_var(1, 0b1u8).unwrap();
1995/// writer.write_var(2, 0b01u8).unwrap();
1996/// writer.write_var(5, 0b10111u8).unwrap();
1997/// assert_eq!(writer.written(), 8);
1998/// ```
1999#[derive(Default)]
2000#[deprecated(since = "4.0.0", note = "use of BitsWritten is preferred")]
2001pub struct BitCounter<N, E: Endianness> {
2002 bits: BitsWritten<N>,
2003 phantom: PhantomData<E>,
2004}
2005
2006#[allow(deprecated)]
2007impl<N: Default, E: Endianness> BitCounter<N, E> {
2008 /// Creates new counter
2009 #[inline]
2010 pub fn new() -> Self {
2011 BitCounter {
2012 bits: BitsWritten::new(),
2013 phantom: PhantomData,
2014 }
2015 }
2016}
2017
2018#[allow(deprecated)]
2019impl<N: Copy, E: Endianness> BitCounter<N, E> {
2020 /// Returns number of bits written
2021 #[inline]
2022 pub fn written(&self) -> N {
2023 self.bits.written()
2024 }
2025}
2026
2027#[allow(deprecated)]
2028impl<N, E: Endianness> BitCounter<N, E> {
2029 /// Returns number of bits written
2030 #[inline]
2031 pub fn into_written(self) -> N {
2032 self.bits.into_written()
2033 }
2034}
2035
2036#[allow(deprecated)]
2037impl<N, E> BitWrite for BitCounter<N, E>
2038where
2039 E: Endianness,
2040 N: Counter,
2041{
2042 #[inline]
2043 fn write_bit(&mut self, bit: bool) -> io::Result<()> {
2044 BitWrite::write_bit(&mut self.bits, bit)
2045 }
2046
2047 #[inline]
2048 fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
2049 BitWrite::write_const::<BITS, VALUE>(&mut self.bits)
2050 }
2051
2052 #[inline]
2053 fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
2054 where
2055 U: UnsignedInteger,
2056 {
2057 BitWrite::write_unsigned::<BITS, U>(&mut self.bits, value)
2058 }
2059
2060 #[inline]
2061 fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
2062 where
2063 S: SignedInteger,
2064 {
2065 BitWrite::write_signed::<BITS, S>(&mut self.bits, value)
2066 }
2067
2068 #[inline]
2069 fn write_unsigned_counted<const MAX: u32, U>(
2070 &mut self,
2071 count: BitCount<MAX>,
2072 value: U,
2073 ) -> io::Result<()>
2074 where
2075 U: UnsignedInteger,
2076 {
2077 BitWrite::write_unsigned_counted::<MAX, U>(&mut self.bits, count, value)
2078 }
2079
2080 #[inline]
2081 fn write_signed_counted<const MAX: u32, S>(
2082 &mut self,
2083 bits: impl TryInto<SignedBitCount<MAX>>,
2084 value: S,
2085 ) -> io::Result<()>
2086 where
2087 S: SignedInteger,
2088 {
2089 BitWrite::write_signed_counted::<MAX, S>(&mut self.bits, bits, value)
2090 }
2091
2092 #[inline]
2093 fn write_from<V>(&mut self, value: V) -> io::Result<()>
2094 where
2095 V: Primitive,
2096 {
2097 BitWrite::write_from(&mut self.bits, value)
2098 }
2099
2100 #[inline]
2101 fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
2102 where
2103 F: Endianness,
2104 V: Primitive,
2105 {
2106 BitWrite::write_as_from::<F, V>(&mut self.bits, value)
2107 }
2108
2109 #[inline]
2110 fn pad(&mut self, bits: u32) -> io::Result<()> {
2111 BitWrite::pad(&mut self.bits, bits)
2112 }
2113
2114 #[inline]
2115 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
2116 BitWrite::write_bytes(&mut self.bits, buf)
2117 }
2118
2119 fn write_unary<const STOP_BIT: u8>(&mut self, value: u32) -> io::Result<()> {
2120 BitWrite::write_unary::<STOP_BIT>(&mut self.bits, value)
2121 }
2122
2123 #[inline]
2124 fn byte_aligned(&self) -> bool {
2125 BitWrite::byte_aligned(&self.bits)
2126 }
2127}
2128
2129#[cfg(feature = "alloc")]
2130mod bit_recorder {
2131 use super::*;
2132
2133 /// For recording writes in order to play them back on another writer
2134 /// # Example
2135 /// ```
2136 /// use std::io::Write;
2137 /// use bitstream_io::{BigEndian, BitWriter, BitWrite, BitRecorder};
2138 /// let mut recorder: BitRecorder<u32, BigEndian> = BitRecorder::new();
2139 /// recorder.write_var(1, 0b1u8).unwrap();
2140 /// recorder.write_var(2, 0b01u8).unwrap();
2141 /// recorder.write_var(5, 0b10111u8).unwrap();
2142 /// assert_eq!(recorder.written(), 8);
2143 /// let mut writer = BitWriter::endian(Vec::new(), BigEndian);
2144 /// recorder.playback(&mut writer);
2145 /// assert_eq!(writer.into_writer(), [0b10110111]);
2146 /// ```
2147 #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
2148 pub struct BitRecorder<N, E: Endianness> {
2149 writer: BitWriter<Vec<u8>, E>,
2150 phantom: PhantomData<N>,
2151 }
2152
2153 impl<N: Counter, E: Endianness> BitRecorder<N, E> {
2154 /// Creates new recorder
2155 #[inline]
2156 pub fn new() -> Self {
2157 BitRecorder {
2158 writer: BitWriter::new(Vec::new()),
2159 phantom: PhantomData,
2160 }
2161 }
2162
2163 /// Creates new recorder sized for the given number of bytes
2164 #[inline]
2165 pub fn with_capacity(bytes: usize) -> Self {
2166 BitRecorder {
2167 writer: BitWriter::new(Vec::with_capacity(bytes)),
2168 phantom: PhantomData,
2169 }
2170 }
2171
2172 /// Creates new recorder with the given endianness
2173 #[inline]
2174 pub fn endian(endian: E) -> Self {
2175 BitRecorder {
2176 writer: BitWriter::endian(Vec::new(), endian),
2177 phantom: PhantomData,
2178 }
2179 }
2180
2181 /// Returns number of bits written
2182 ///
2183 /// # Panics
2184 ///
2185 /// Panics if the number of bits written is
2186 /// larger than the maximum supported by the counter type.
2187 /// Use [`BitRecorder::written_checked`] for a non-panicking
2188 /// alternative.
2189 #[inline]
2190 pub fn written(&self) -> N {
2191 self.written_checked().unwrap()
2192 }
2193
2194 /// Returns number of bits written
2195 ///
2196 /// # Errors
2197 ///
2198 /// Returns an error if the number of bits written overflows
2199 /// our counter type.
2200 #[inline]
2201 pub fn written_checked(&self) -> Result<N, Overflowed> {
2202 let mut written = N::try_from(self.writer.writer.len())
2203 .map_err(|_| Overflowed)?
2204 .checked_mul(8u8.into())?;
2205
2206 written.checked_add_assign(N::try_from(self.writer.bits).map_err(|_| Overflowed)?)?;
2207
2208 Ok(written)
2209 }
2210
2211 /// Plays recorded writes to the given writer
2212 #[inline]
2213 pub fn playback<W: BitWrite>(&self, writer: &mut W) -> io::Result<()> {
2214 writer.write_bytes(self.writer.writer.as_slice())?;
2215 writer.write_var(self.writer.bits, self.writer.value)?;
2216 Ok(())
2217 }
2218
2219 /// Clears recorder, removing all values
2220 #[inline]
2221 pub fn clear(&mut self) {
2222 self.writer = BitWriter::new({
2223 let mut v = core::mem::take(&mut self.writer.writer);
2224 v.clear();
2225 v
2226 });
2227 }
2228 }
2229
2230 impl<N: Counter, E: Endianness> Default for BitRecorder<N, E> {
2231 #[inline]
2232 fn default() -> Self {
2233 Self::new()
2234 }
2235 }
2236
2237 impl<N, E> BitWrite for BitRecorder<N, E>
2238 where
2239 E: Endianness,
2240 N: Counter,
2241 {
2242 #[inline]
2243 fn write_bit(&mut self, bit: bool) -> io::Result<()> {
2244 BitWrite::write_bit(&mut self.writer, bit)
2245 }
2246
2247 #[inline]
2248 fn write<const BITS: u32, I>(&mut self, value: I) -> io::Result<()>
2249 where
2250 I: Integer,
2251 {
2252 BitWrite::write::<BITS, I>(&mut self.writer, value)
2253 }
2254
2255 #[inline]
2256 fn write_const<const BITS: u32, const VALUE: u32>(&mut self) -> io::Result<()> {
2257 self.writer.write_const::<BITS, VALUE>()
2258 }
2259
2260 #[inline]
2261 fn write_var<I>(&mut self, bits: u32, value: I) -> io::Result<()>
2262 where
2263 I: Integer,
2264 {
2265 self.writer.write_var(bits, value)
2266 }
2267
2268 #[inline]
2269 fn write_unsigned<const BITS: u32, U>(&mut self, value: U) -> io::Result<()>
2270 where
2271 U: UnsignedInteger,
2272 {
2273 BitWrite::write_unsigned::<BITS, U>(&mut self.writer, value)
2274 }
2275
2276 #[inline]
2277 fn write_unsigned_var<U>(&mut self, bits: u32, value: U) -> io::Result<()>
2278 where
2279 U: UnsignedInteger,
2280 {
2281 self.writer.write_unsigned_var(bits, value)
2282 }
2283
2284 #[inline]
2285 fn write_signed<const BITS: u32, S>(&mut self, value: S) -> io::Result<()>
2286 where
2287 S: SignedInteger,
2288 {
2289 BitWrite::write_signed::<BITS, S>(&mut self.writer, value)
2290 }
2291
2292 #[inline(always)]
2293 fn write_signed_var<S>(&mut self, bits: u32, value: S) -> io::Result<()>
2294 where
2295 S: SignedInteger,
2296 {
2297 self.writer.write_signed_var(bits, value)
2298 }
2299
2300 #[inline]
2301 fn write_count<const MAX: u32>(&mut self, count: BitCount<MAX>) -> io::Result<()> {
2302 self.writer.write_count::<MAX>(count)
2303 }
2304
2305 #[inline]
2306 fn write_counted<const MAX: u32, I>(
2307 &mut self,
2308 bits: BitCount<MAX>,
2309 value: I,
2310 ) -> io::Result<()>
2311 where
2312 I: Integer + Sized,
2313 {
2314 self.writer.write_counted::<MAX, I>(bits, value)
2315 }
2316
2317 #[inline]
2318 fn write_unsigned_counted<const BITS: u32, U>(
2319 &mut self,
2320 bits: BitCount<BITS>,
2321 value: U,
2322 ) -> io::Result<()>
2323 where
2324 U: UnsignedInteger,
2325 {
2326 self.writer.write_unsigned_counted::<BITS, U>(bits, value)
2327 }
2328
2329 #[inline]
2330 fn write_signed_counted<const MAX: u32, S>(
2331 &mut self,
2332 bits: impl TryInto<SignedBitCount<MAX>>,
2333 value: S,
2334 ) -> io::Result<()>
2335 where
2336 S: SignedInteger,
2337 {
2338 self.writer.write_signed_counted::<MAX, S>(bits, value)
2339 }
2340
2341 #[inline]
2342 fn write_from<V>(&mut self, value: V) -> io::Result<()>
2343 where
2344 V: Primitive,
2345 {
2346 BitWrite::write_from::<V>(&mut self.writer, value)
2347 }
2348
2349 #[inline]
2350 fn write_as_from<F, V>(&mut self, value: V) -> io::Result<()>
2351 where
2352 F: Endianness,
2353 V: Primitive,
2354 {
2355 BitWrite::write_as_from::<F, V>(&mut self.writer, value)
2356 }
2357
2358 #[inline]
2359 fn pad(&mut self, bits: u32) -> io::Result<()> {
2360 BitWrite::pad(&mut self.writer, bits)
2361 }
2362
2363 #[inline]
2364 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
2365 BitWrite::write_bytes(&mut self.writer, buf)
2366 }
2367
2368 #[inline]
2369 fn write_unary<const STOP_BIT: u8>(&mut self, value: u32) -> io::Result<()> {
2370 self.writer.write_unary::<STOP_BIT>(value)
2371 }
2372
2373 #[inline]
2374 fn build<T: ToBitStream>(&mut self, build: &T) -> Result<(), T::Error> {
2375 BitWrite::build(&mut self.writer, build)
2376 }
2377
2378 #[inline]
2379 fn build_with<'a, T: ToBitStreamWith<'a>>(
2380 &mut self,
2381 build: &T,
2382 context: &T::Context,
2383 ) -> Result<(), T::Error> {
2384 BitWrite::build_with(&mut self.writer, build, context)
2385 }
2386
2387 #[inline]
2388 fn byte_aligned(&self) -> bool {
2389 BitWrite::byte_aligned(&self.writer)
2390 }
2391
2392 #[inline]
2393 fn byte_align(&mut self) -> io::Result<()> {
2394 BitWrite::byte_align(&mut self.writer)
2395 }
2396
2397 #[inline]
2398 fn write_huffman<T>(&mut self, value: T::Symbol) -> io::Result<()>
2399 where
2400 T: crate::huffman::ToBits,
2401 {
2402 BitWrite::write_huffman::<T>(&mut self.writer, value)
2403 }
2404 }
2405
2406 impl<N: PartialOrd + Counter + Copy, E: Endianness> BitRecorder<N, E> {
2407 /// Returns shortest option between ourself and candidate
2408 ///
2409 /// Executes fallible closure on emptied candidate recorder,
2410 /// compares the lengths of ourself and the candidate,
2411 /// and returns the shorter of the two.
2412 ///
2413 /// If the new candidate is shorter, we swap ourself and
2414 /// the candidate so any recorder capacity can be reused.
2415 ///
2416 /// # Example
2417 ///
2418 /// ```
2419 /// use bitstream_io::{BitRecorder, BitWrite, BigEndian};
2420 ///
2421 /// let mut best = BitRecorder::<u8, BigEndian>::new();
2422 /// let mut candidate = BitRecorder::new();
2423 ///
2424 /// // write an 8 bit value to our initial candidate
2425 /// best.write::<8, u8>(0);
2426 /// assert_eq!(best.written(), 8);
2427 ///
2428 /// // try another candidate which writes 4 bits
2429 /// best = best.best(&mut candidate, |w| {
2430 /// w.write::<4, u8>(0)
2431 /// }).unwrap();
2432 ///
2433 /// // which becomes our new best candidate
2434 /// assert_eq!(best.written(), 4);
2435 ///
2436 /// // finally, try a not-so-best candidate
2437 /// // which writes 10 bits
2438 /// best = best.best(&mut candidate, |w| {
2439 /// w.write::<10, u16>(0)
2440 /// }).unwrap();
2441 ///
2442 /// // so our best candidate remains 4 bits
2443 /// assert_eq!(best.written(), 4);
2444 /// ```
2445 pub fn best<F>(
2446 mut self,
2447 candidate: &mut Self,
2448 f: impl FnOnce(&mut Self) -> Result<(), F>,
2449 ) -> Result<Self, F> {
2450 candidate.clear();
2451
2452 f(candidate)?;
2453
2454 if candidate.written() < self.written() {
2455 core::mem::swap(&mut self, candidate);
2456 }
2457
2458 Ok(self)
2459 }
2460 }
2461}
2462
2463#[inline]
2464fn write_byte<W>(mut writer: W, byte: u8) -> io::Result<()>
2465where
2466 W: io::Write,
2467{
2468 writer.write_all(core::slice::from_ref(&byte))
2469}
2470
2471/// For writing aligned bytes to a stream of bytes in a given endianness.
2472///
2473/// This only writes aligned values and maintains no internal state.
2474pub struct ByteWriter<W: io::Write, E: Endianness> {
2475 phantom: PhantomData<E>,
2476 writer: W,
2477}
2478
2479impl<W: io::Write, E: Endianness> ByteWriter<W, E> {
2480 /// Wraps a ByteWriter around something that implements `Write`
2481 pub fn new(writer: W) -> ByteWriter<W, E> {
2482 ByteWriter {
2483 phantom: PhantomData,
2484 writer,
2485 }
2486 }
2487
2488 /// Wraps a BitWriter around something that implements `Write`
2489 /// with the given endianness.
2490 pub fn endian(writer: W, _endian: E) -> ByteWriter<W, E> {
2491 ByteWriter {
2492 phantom: PhantomData,
2493 writer,
2494 }
2495 }
2496
2497 /// Unwraps internal writer and disposes of `ByteWriter`.
2498 /// Any unwritten partial bits are discarded.
2499 #[inline]
2500 pub fn into_writer(self) -> W {
2501 self.writer
2502 }
2503
2504 /// Provides mutable reference to internal writer.
2505 #[inline]
2506 pub fn writer(&mut self) -> &mut W {
2507 &mut self.writer
2508 }
2509
2510 /// Converts `ByteWriter` to `BitWriter` in the same endianness.
2511 #[inline]
2512 pub fn into_bitwriter(self) -> BitWriter<W, E> {
2513 BitWriter::new(self.into_writer())
2514 }
2515
2516 /// Provides temporary `BitWriter` in the same endianness.
2517 ///
2518 /// # Warning
2519 ///
2520 /// Any unwritten bits left over when `BitWriter` is dropped are lost.
2521 #[inline]
2522 pub fn bitwriter(&mut self) -> BitWriter<&mut W, E> {
2523 BitWriter::new(self.writer())
2524 }
2525}
2526
2527/// A trait for anything that can write aligned values to an output stream
2528pub trait ByteWrite {
2529 /// Writes whole numeric value to stream
2530 ///
2531 /// # Errors
2532 ///
2533 /// Passes along any I/O error from the underlying stream.
2534 /// # Examples
2535 /// ```
2536 /// use std::io::Write;
2537 /// use bitstream_io::{BigEndian, ByteWriter, ByteWrite};
2538 /// let mut writer = ByteWriter::endian(Vec::new(), BigEndian);
2539 /// writer.write(0b0000000011111111u16).unwrap();
2540 /// assert_eq!(writer.into_writer(), [0b00000000, 0b11111111]);
2541 /// ```
2542 ///
2543 /// ```
2544 /// use std::io::Write;
2545 /// use bitstream_io::{LittleEndian, ByteWriter, ByteWrite};
2546 /// let mut writer = ByteWriter::endian(Vec::new(), LittleEndian);
2547 /// writer.write(0b0000000011111111u16).unwrap();
2548 /// assert_eq!(writer.into_writer(), [0b11111111, 0b00000000]);
2549 /// ```
2550 fn write<V>(&mut self, value: V) -> io::Result<()>
2551 where
2552 V: Primitive;
2553
2554 /// Writes whole numeric value to stream in a potentially different endianness
2555 ///
2556 /// # Errors
2557 ///
2558 /// Passes along any I/O error from the underlying stream.
2559 ///
2560 /// # Examples
2561 /// ```
2562 /// use std::io::Write;
2563 /// use bitstream_io::{BigEndian, ByteWriter, ByteWrite, LittleEndian};
2564 /// let mut writer = ByteWriter::endian(Vec::new(), BigEndian);
2565 /// writer.write_as::<LittleEndian, u16>(0b0000000011111111).unwrap();
2566 /// assert_eq!(writer.into_writer(), [0b11111111, 0b00000000]);
2567 /// ```
2568 ///
2569 /// ```
2570 /// use std::io::Write;
2571 /// use bitstream_io::{BigEndian, ByteWriter, ByteWrite, LittleEndian};
2572 /// let mut writer = ByteWriter::endian(Vec::new(), LittleEndian);
2573 /// writer.write_as::<BigEndian, u16>(0b0000000011111111).unwrap();
2574 /// assert_eq!(writer.into_writer(), [0b00000000, 0b11111111]);
2575 /// ```
2576 fn write_as<F, V>(&mut self, value: V) -> io::Result<()>
2577 where
2578 F: Endianness,
2579 V: Primitive;
2580
2581 /// Writes the entirety of a byte buffer to the stream.
2582 ///
2583 /// # Errors
2584 ///
2585 /// Passes along any I/O error from the underlying stream.
2586 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()>;
2587
2588 /// Pads the stream by writing 0 over the given number of bytes.
2589 ///
2590 /// # Errors
2591 ///
2592 /// Passes along any I/O error from the underlying stream.
2593 fn pad(&mut self, bytes: u32) -> io::Result<()>;
2594
2595 /// Builds and writes complex type
2596 fn build<T: ToByteStream>(&mut self, build: &T) -> Result<(), T::Error> {
2597 build.to_writer(self)
2598 }
2599
2600 /// Builds and writes complex type with context
2601 fn build_with<'a, T: ToByteStreamWith<'a>>(
2602 &mut self,
2603 build: &T,
2604 context: &T::Context,
2605 ) -> Result<(), T::Error> {
2606 build.to_writer(self, context)
2607 }
2608
2609 /// Builds and writes complex type with owned context
2610 fn build_using<T: ToByteStreamUsing>(
2611 &mut self,
2612 build: &T,
2613 context: T::Context,
2614 ) -> Result<(), T::Error> {
2615 build.to_writer(self, context)
2616 }
2617
2618 /// Returns mutable reference to underlying writer
2619 fn writer_ref(&mut self) -> &mut dyn io::Write;
2620}
2621
2622impl<W: io::Write, E: Endianness> ByteWrite for ByteWriter<W, E> {
2623 #[inline]
2624 fn write<V>(&mut self, value: V) -> io::Result<()>
2625 where
2626 V: Primitive,
2627 {
2628 self.writer.write_all(E::primitive_to_bytes(value).as_ref())
2629 }
2630
2631 #[inline]
2632 fn write_as<F, V>(&mut self, value: V) -> io::Result<()>
2633 where
2634 F: Endianness,
2635 V: Primitive,
2636 {
2637 self.writer.write_all(F::primitive_to_bytes(value).as_ref())
2638 }
2639
2640 #[inline]
2641 fn pad(&mut self, mut bytes: u32) -> io::Result<()> {
2642 let buf = [0u8; 8];
2643
2644 while bytes > 0 {
2645 let to_write = bytes.min(8);
2646 self.write_bytes(&buf[0..to_write as usize])?;
2647 bytes -= to_write;
2648 }
2649 Ok(())
2650 }
2651
2652 #[inline]
2653 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
2654 self.writer.write_all(buf)
2655 }
2656
2657 #[inline]
2658 fn writer_ref(&mut self) -> &mut dyn io::Write {
2659 &mut self.writer
2660 }
2661}
2662
2663/// Implemented by complex types that don't require any additional context
2664/// to build themselves to a writer
2665///
2666/// # Example
2667/// ```
2668/// use std::io::Read;
2669/// use bitstream_io::{BigEndian, BitWrite, BitWriter, ToBitStream};
2670///
2671/// #[derive(Debug, PartialEq, Eq)]
2672/// struct BlockHeader {
2673/// last_block: bool,
2674/// block_type: u8,
2675/// block_size: u32,
2676/// }
2677///
2678/// impl ToBitStream for BlockHeader {
2679/// type Error = std::io::Error;
2680///
2681/// fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> std::io::Result<()> {
2682/// w.write_bit(self.last_block)?;
2683/// w.write::<7, _>(self.block_type)?;
2684/// w.write::<24, _>(self.block_size)
2685/// }
2686/// }
2687///
2688/// let mut data = Vec::new();
2689/// let mut writer = BitWriter::endian(&mut data, BigEndian);
2690/// writer.build(&BlockHeader { last_block: false, block_type: 4, block_size: 122 }).unwrap();
2691/// assert_eq!(data, b"\x04\x00\x00\x7A");
2692/// ```
2693pub trait ToBitStream {
2694 /// Error generated during building, such as `io::Error`
2695 type Error;
2696
2697 /// Generate self to writer
2698 fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error>
2699 where
2700 Self: Sized;
2701
2702 /// Returns length of self in bits, if possible
2703 fn bits<C: Counter>(&self) -> Result<C, Self::Error>
2704 where
2705 Self: Sized,
2706 {
2707 let mut c: BitsWritten<C> = BitsWritten::default();
2708 self.to_writer(&mut c)?;
2709 Ok(c.into_written())
2710 }
2711
2712 /// Returns total length of self, if possible
2713 #[deprecated(since = "4.0.0", note = "use of bits() is preferred")]
2714 #[inline]
2715 fn bits_len<C: Counter, E: Endianness>(&self) -> Result<C, Self::Error>
2716 where
2717 Self: Sized,
2718 {
2719 self.bits()
2720 }
2721}
2722
2723/// Implemented by complex types that require additional context
2724/// to build themselves to a writer
2725pub trait ToBitStreamWith<'a> {
2726 /// Some context to use when writing
2727 type Context: 'a;
2728
2729 /// Error generated during building, such as `io::Error`
2730 type Error;
2731
2732 /// Generate self to writer
2733 fn to_writer<W: BitWrite + ?Sized>(
2734 &self,
2735 w: &mut W,
2736 context: &Self::Context,
2737 ) -> Result<(), Self::Error>
2738 where
2739 Self: Sized;
2740
2741 /// Returns length of self in bits, if possible
2742 fn bits<C: Counter>(&self, context: &Self::Context) -> Result<C, Self::Error>
2743 where
2744 Self: Sized,
2745 {
2746 let mut c: BitsWritten<C> = BitsWritten::default();
2747 self.to_writer(&mut c, context)?;
2748 Ok(c.into_written())
2749 }
2750
2751 /// Returns total length of self, if possible
2752 #[deprecated(since = "4.0.0", note = "use of len() is preferred")]
2753 #[inline]
2754 fn bits_len<C: Counter, E: Endianness>(&self, context: &Self::Context) -> Result<C, Self::Error>
2755 where
2756 Self: Sized,
2757 {
2758 self.bits(context)
2759 }
2760}
2761
2762/// Implemented by complex types that consume additional context
2763/// to build themselves to a writer
2764pub trait ToBitStreamUsing {
2765 /// Some context to consume when writing
2766 type Context;
2767
2768 /// Error generated during building, such as `io::Error`
2769 type Error;
2770
2771 /// Generate self to writer
2772 fn to_writer<W: BitWrite + ?Sized>(
2773 &self,
2774 w: &mut W,
2775 context: Self::Context,
2776 ) -> Result<(), Self::Error>
2777 where
2778 Self: Sized;
2779
2780 /// Returns length of self in bits, if possible
2781 fn bits<C: Counter>(&self, context: Self::Context) -> Result<C, Self::Error>
2782 where
2783 Self: Sized,
2784 {
2785 let mut c: BitsWritten<C> = BitsWritten::default();
2786 self.to_writer(&mut c, context)?;
2787 Ok(c.into_written())
2788 }
2789}
2790
2791/// Implemented by complex types that don't require any additional context
2792/// to build themselves to a writer
2793pub trait ToByteStream {
2794 /// Error generated during building, such as `io::Error`
2795 type Error;
2796
2797 /// Generate self to writer
2798 fn to_writer<W: ByteWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error>
2799 where
2800 Self: Sized;
2801
2802 /// Returns length of self in bytes, if possible
2803 fn bytes<C: Counter>(&self) -> Result<C, Self::Error>
2804 where
2805 Self: Sized,
2806 {
2807 let mut counter = ByteCount::default();
2808 self.to_writer(&mut counter)?;
2809 Ok(counter.writer.count)
2810 }
2811}
2812
2813/// Implemented by complex types that require additional context
2814/// to build themselves to a writer
2815pub trait ToByteStreamWith<'a> {
2816 /// Some context to use when writing
2817 type Context: 'a;
2818
2819 /// Error generated during building, such as `io::Error`
2820 type Error;
2821
2822 /// Generate self to writer
2823 fn to_writer<W: ByteWrite + ?Sized>(
2824 &self,
2825 w: &mut W,
2826 context: &Self::Context,
2827 ) -> Result<(), Self::Error>
2828 where
2829 Self: Sized;
2830
2831 /// Returns length of self in bytes, if possible
2832 fn bytes<C: Counter>(&self, context: &Self::Context) -> Result<C, Self::Error>
2833 where
2834 Self: Sized,
2835 {
2836 let mut counter = ByteCount::default();
2837 self.to_writer(&mut counter, context)?;
2838 Ok(counter.writer.count)
2839 }
2840}
2841
2842/// Implemented by complex types that consume additional context
2843/// to build themselves to a writer
2844pub trait ToByteStreamUsing {
2845 /// Some context to consume when writing
2846 type Context;
2847
2848 /// Error generated during building, such as `io::Error`
2849 type Error;
2850
2851 /// Generate self to writer
2852 fn to_writer<W: ByteWrite + ?Sized>(
2853 &self,
2854 w: &mut W,
2855 context: Self::Context,
2856 ) -> Result<(), Self::Error>
2857 where
2858 Self: Sized;
2859
2860 /// Returns length of self in bytes, if possible
2861 fn bytes<C: Counter>(&self, context: Self::Context) -> Result<C, Self::Error>
2862 where
2863 Self: Sized,
2864 {
2865 let mut counter = ByteCount::default();
2866 self.to_writer(&mut counter, context)?;
2867 Ok(counter.writer.count)
2868 }
2869}
2870
2871#[derive(Default)]
2872struct ByteCounterWriter<C> {
2873 count: C,
2874}
2875
2876impl<C: Counter> io::Write for ByteCounterWriter<C> {
2877 #[inline]
2878 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2879 self.count
2880 .checked_add_assign(buf.len().try_into().map_err(|_| Overflowed)?)?;
2881
2882 Ok(buf.len())
2883 }
2884
2885 #[inline]
2886 fn flush(&mut self) -> io::Result<()> {
2887 // nothing to do
2888 Ok(())
2889 }
2890}
2891
2892#[derive(Default)]
2893struct ByteCount<C> {
2894 writer: ByteCounterWriter<C>,
2895}
2896
2897impl<C: Counter> ByteWrite for ByteCount<C> {
2898 fn write<V: Primitive>(&mut self, _value: V) -> io::Result<()> {
2899 self.writer.count.checked_add_assign(
2900 V::buffer()
2901 .as_ref()
2902 .len()
2903 .try_into()
2904 .map_err(|_| Overflowed)?,
2905 )?;
2906
2907 Ok(())
2908 }
2909
2910 fn write_as<F: Endianness, V: Primitive>(&mut self, _value: V) -> io::Result<()> {
2911 self.writer.count.checked_add_assign(
2912 V::buffer()
2913 .as_ref()
2914 .len()
2915 .try_into()
2916 .map_err(|_| Overflowed)?,
2917 )?;
2918
2919 Ok(())
2920 }
2921
2922 fn write_bytes(&mut self, buf: &[u8]) -> io::Result<()> {
2923 self.writer
2924 .count
2925 .checked_add_assign(buf.len().try_into().map_err(|_| Overflowed)?)?;
2926
2927 Ok(())
2928 }
2929
2930 fn pad(&mut self, bytes: u32) -> io::Result<()> {
2931 self.writer
2932 .count
2933 .checked_add_assign(bytes.try_into().map_err(|_| Overflowed)?)?;
2934
2935 Ok(())
2936 }
2937
2938 fn writer_ref(&mut self) -> &mut dyn io::Write {
2939 &mut self.writer
2940 }
2941}