@@ 19,6 19,15 @@ impl MessageContent {
MessageContent::Text(text) => [&[0], text.as_bytes()].concat()
}
}
+ pub fn from_bytes(bytes: &[u8]) -> Option<MessageContent> {
+ match bytes.first()? {
+ 0 => {
+ let text = String::from_utf8(bytes[1..].to_vec()).ok()?;
+ Some(MessageContent::Text(text))
+ }
+ _ => None,
+ }
+ }
}
impl Message {
@@ 36,34 45,28 @@ impl Message {
result.extend(self.content.to_bytes());
result
}
- pub fn from_bytes(raw: &[u8]) -> Option<Self> {
- let num_other_recipients = *raw.get(0)?;
- let mut offset = 1;
+ pub fn from_bytes(mut bytes: &[u8]) -> Option<Self> {
+ let num_other_recipients = *bytes.first()?;
+ bytes = &bytes[1..];
let mut other_recipients = Vec::new();
for _ in 0..num_other_recipients {
- let (recipient, len) = SufecAddr::from_bytes(&raw[offset..])?;
- offset += len;
+ let (recipient, len) = SufecAddr::from_bytes(bytes)?;
+ bytes = &bytes[len..];
other_recipients.push(recipient);
}
- let timestamp = u64::from_be_bytes(raw[offset..offset+8].try_into().unwrap());
- offset += 8;
+ let timestamp = u64::from_be_bytes(bytes[..8].try_into().unwrap());
+ bytes = &bytes[8..];
let mut hashes = vec![];
- let num_hashes = raw[offset];
- offset += 1;
+ let num_hashes = *bytes.first()?;
+ bytes = &bytes[1..];
for _ in 0..num_hashes {
- let timestamp = u64::from_be_bytes(raw[offset..offset+8].try_into().unwrap());
- offset += 8;
- let hash = raw[offset..offset+DIGESTBYTES].try_into().unwrap();
+ let timestamp = u64::from_be_bytes(bytes[..8].try_into().unwrap());
+ bytes = &bytes[8..];
+ let hash = bytes[..DIGESTBYTES].try_into().unwrap();
hashes.push((timestamp, Digest(hash)));
- offset += DIGESTBYTES;
+ bytes = &bytes[DIGESTBYTES..];
}
- let content = match raw.get(offset)? {
- 0 => {
- let message = String::from_utf8(raw[offset+1..].to_vec()).ok()?;
- MessageContent::Text(message)
- }
- _ => return None,
- };
+ let content = MessageContent::from_bytes(bytes)?;
Some(Self{other_recipients, timestamp, content, hashes})
}
}