Guest User

Untitled

a guest
Oct 22nd, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. pub struct ByteBuilder {
  2. bytes: Vec<u8>,
  3. pending: u8,
  4. bit: u8,
  5. }
  6.  
  7. impl ByteBuilder {
  8. pub fn new() -> Self {
  9. Self {
  10. bytes: vec![],
  11. pending: 0,
  12. bit: 0,
  13. }
  14. }
  15.  
  16. pub fn push(&mut self, bit: impl Into<bool>) {
  17. self.pending <<= 1;
  18. self.bit += 1;
  19. self.pending |= u8::from(bit.into());
  20. if self.bit == 8 {
  21. self.bytes.push(std::mem::replace(&mut self.pending, 0));
  22. self.bit = 0;
  23. }
  24. }
  25. }
  26.  
  27. impl From<ByteBuilder> for Vec<u8> {
  28. fn from(b: ByteBuilder) -> Self {
  29. b.bytes
  30. }
  31. }
Add Comment
Please, Sign In to add comment