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