Skip to content

Commit

Permalink
address comment
Browse files Browse the repository at this point in the history
Signed-off-by: Jay Lee <[email protected]>
  • Loading branch information
BusyJay committed Nov 24, 2020
1 parent bdaa6d1 commit 166a842
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ use crate::error::Result;
pub type DeserializeFn<T> = fn(MessageReader) -> Result<T>;
pub type SerializeFn<T> = fn(&T, &mut Vec<u8>) -> Result<()>;

/// According to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md, grpc uses
/// a four bytes to describe the length of a message, so it should not exceed u32::MAX.
const MAX_MESSAGE_SIZE: usize = u32::MAX as usize;

/// Defines how to serialize and deserialize between the specialized type and byte slice.
pub struct Marshaller<T> {
// Use function pointer here to simplify the signature.
Expand All @@ -28,17 +32,17 @@ pub struct Marshaller<T> {
pub mod pb_codec {
use protobuf::{CodedInputStream, Message};

use super::MessageReader;
use super::{MessageReader, MAX_MESSAGE_SIZE};
use crate::error::{Error, Result};

#[inline]
pub fn ser<T: Message>(t: &T, buf: &mut Vec<u8>) -> Result<()> {
t.write_to_vec(buf)?;
if buf.len() <= u32::MAX as usize {
if buf.len() <= MAX_MESSAGE_SIZE as usize {
Ok(())
} else {
Err(Error::Codec(
format!("message is too large: {} > u32::MAX", buf.len()).into(),
format!("message is too large: {} > {}", buf.len(), MAX_MESSAGE_SIZE).into(),
))
}
}
Expand All @@ -56,17 +60,17 @@ pub mod pb_codec {
pub mod pr_codec {
use prost::Message;

use super::MessageReader;
use super::{MessageReader, MAX_MESSAGE_SIZE};
use crate::error::{Error, Result};

#[inline]
pub fn ser<M: Message>(msg: &M, buf: &mut Vec<u8>) -> Result<()> {
msg.encode(buf)?;
if buf.len() <= u32::MAX as usize {
if buf.len() <= MAX_MESSAGE_SIZE as usize {
Ok(())
} else {
Err(Error::Codec(
format!("message is too large: {} > u32::MAX", buf.len()).into(),
format!("message is too large: {} > {}", buf.len(), MAX_MESSAGE_SIZE).into(),
))
}
}
Expand Down

0 comments on commit 166a842

Please sign in to comment.