Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Specialization of decoding for Bytes #135

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/message.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::Debug;
use std::usize;

use bytes::{Buf, BufMut, IntoBuf};
use bytes::{Buf, BufMut, Bytes, IntoBuf};

use DecodeError;
use EncodeError;
Expand Down Expand Up @@ -64,13 +64,21 @@ pub trait Message: Debug + Send + Sync {
Self::merge(&mut message, &mut buf.into_buf()).map(|_| message)
}

fn decode_bytes(buf: Bytes) -> Result<Self, DecodeError> where Self: Default {
Self::decode(buf)
}

/// Decodes a length-delimited instance of the message from the buffer.
fn decode_length_delimited<B>(buf: B) -> Result<Self, DecodeError> where B: IntoBuf, Self: Default {
let mut message = Self::default();
message.merge_length_delimited(buf)?;
Ok(message)
}

fn decode_bytes_length_delimited(buf: Bytes) -> Result<Self, DecodeError> where Self: Default {
Self::decode_length_delimited(buf)
}

/// Decodes an instance of the message from a buffer, and merges it into `self`.
///
/// The entire buffer will be consumed.
Expand All @@ -82,12 +90,20 @@ pub trait Message: Debug + Send + Sync {
Ok(())
}

fn merge_bytes(&mut self, buf: Bytes) -> Result<(), DecodeError> where Self: Sized {
self.merge(buf)
}

/// Decodes a length-delimited instance of the message from buffer, and
/// merges it into `self`.
fn merge_length_delimited<B>(&mut self, buf: B) -> Result<(), DecodeError> where B: IntoBuf, Self: Sized {
message::merge(WireType::LengthDelimited, self, &mut buf.into_buf())
}

fn merge_bytes_length_delimited(&mut self, buf: Bytes) -> Result<(), DecodeError> where Self: Sized {
self.merge_length_delimited(buf)
}

/// Clears the message, resetting all fields to their default.
fn clear(&mut self);
}
Expand All @@ -105,4 +121,17 @@ impl <M> Message for Box<M> where M: Message {
fn clear(&mut self) {
(**self).clear()
}

/*
* Doesn't work :-(
fn decode_bytes_length_delimited(buf: Bytes) -> Result<Self, DecodeError> where M: Default {
M::decode_bytes_length_delimited(buf).map(Box::new)
}
*/
fn merge_bytes(&mut self, buf: Bytes) -> Result<(), DecodeError> where Self: Sized {
(**self).merge_bytes(buf)
}
fn merge_bytes_length_delimited(&mut self, buf: Bytes) -> Result<(), DecodeError> where Self: Sized {
(**self).merge_bytes_length_delimited(buf)
}
}