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

Implement Parcel for std::ffi::CString #22

Merged
merged 2 commits into from
Jul 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions protocol/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ error_chain! {
foreign_links {
Io(std::io::Error);
FromUtf8(std::string::FromUtf8Error);
FromNulError(std::ffi::NulError);
TryFromIntError(TryFromIntError);
CharTryFromError(CharTryFromError);

Expand Down
59 changes: 59 additions & 0 deletions protocol/src/types/cstring.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::ffi::CString;
use std::io::prelude::{Read, Write};
use {hint, util, Error, Parcel, Settings};

impl Parcel for CString {
const TYPE_NAME: &'static str = "CString";

fn read_field(
read: &mut dyn Read,
settings: &Settings,
_hints: &mut hint::Hints,
) -> Result<Self, Error> {
let mut result = Vec::new();
// this logic is susceptible to DoS attacks by never providing
// a null character and will be fixed by
// https://github.com/dylanmckay/protocol/issues/14
loop {
anarelion marked this conversation as resolved.
Show resolved Hide resolved
let c: u8 = Parcel::read(read, settings)?;
if c == 0x00 {
return Ok(CString::new(result)?);
}
result.push(c);
}
}

fn write_field(
&self,
write: &mut dyn Write,
settings: &Settings,
_hints: &mut hint::Hints,
) -> Result<(), Error> {
util::write_items(self.clone().into_bytes_with_nul().iter(), write, settings)
}
}

#[cfg(test)]
mod test {
use std::ffi::CString;
use std::io::Cursor;
use {Parcel, Settings};

#[test]
fn can_read_cstring() {
let mut data = Cursor::new([0x41, 0x42, 0x43, 0]);
let read_back: CString = Parcel::read(&mut data, &Settings::default()).unwrap();
assert_eq!(read_back, CString::new("ABC").unwrap());
}

#[test]
fn can_write_cstring() {
let mut buffer = Cursor::new(Vec::new());

CString::new("ABC")
.unwrap()
.write(&mut buffer, &Settings::default())
.unwrap();
assert_eq!(buffer.into_inner(), vec![0x41, 0x42, 0x43, 0]);
}
}
1 change: 1 addition & 0 deletions protocol/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod array;
mod char;
/// Definitions for the `std::collections` module.
mod collections;
mod cstring;
mod marker;
mod numerics;
mod option;
Expand Down