Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. use Value::*;
  2.  
  3. #[derive(Debug)]
  4. enum Value {
  5. I(i64),
  6. }
  7.  
  8. #[derive(Debug)]
  9. enum Error {
  10. NotEnoughData,
  11. InvalidInteger,
  12. }
  13.  
  14. fn read_int(mut buf: &[u8], size_in_bytes: usize) -> Result<Value, Error> {
  15. let mut acc = 0;
  16.  
  17. for _ in 0..size_in_bytes {
  18. if buf.is_empty() { return Err(Error::NotEnoughData) }
  19. acc <<= 8;
  20. acc |= buf[0] as i64;
  21. buf = &buf[1..];
  22. }
  23.  
  24. Ok(I(acc))
  25. }
  26.  
  27. fn cbor_decode(buf: &[u8]) -> Result<Value, Error> {
  28. match buf[0] {
  29. 0x00 ... 0x17 => Ok(I(buf[0] as i64)),
  30. 0x18 ... 0x1b => read_int(&buf[1..], (buf[0] - 0x17) as usize),
  31. _ => Err(Error::InvalidInteger),
  32. }
  33. }
  34.  
  35. fn main() {
  36. let x = [0x1a, 1, 0, 0];
  37. let y = cbor_decode(&x);
  38. println!("{:?}", y);
  39. }
  40.  
  41. extern crate byteorder;
  42.  
  43. use byteorder::{ByteOrder, BigEndian};
  44.  
  45. fn read_int(buf: &[u8], size_in_bytes: usize) -> Result<Value, Error> {
  46. if buf.len() < size_in_bytes {
  47. Err(Error::NotEnoughData)
  48. } else {
  49. Ok(I(BigEndian::read_int(buf, size_in_bytes)))
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement