From 0c2fed49e2a72dfd07f7db7ecbbce6637b2bc470 Mon Sep 17 00:00:00 2001 From: Jon Gjengset Date: Wed, 8 Mar 2017 23:13:28 -0500 Subject: [PATCH] Add Deserialize impl for CStr Fixes #810 --- serde/src/de/impls.rs | 12 ++++++++++++ serde/src/lib.rs | 2 +- test_suite/tests/test_de.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs index 5f5307fd..85bf64c4 100644 --- a/serde/src/de/impls.rs +++ b/serde/src/de/impls.rs @@ -27,6 +27,8 @@ use std::path; use core::str; #[cfg(feature = "std")] use std::ffi::CString; +#[cfg(all(feature = "std", feature="unstable"))] +use std::ffi::CStr; #[cfg(feature = "std")] use std::rc::Rc; @@ -300,6 +302,16 @@ impl Deserialize for String { /////////////////////////////////////////////////////////////////////////////// +#[cfg(all(feature = "std", feature="unstable"))] +impl Deserialize for Box { + fn deserialize(deserializer: D) -> Result + where D: Deserializer + { + let s = try!(CString::deserialize(deserializer)); + Ok(s.into_boxed_c_str()) + } +} + #[cfg(feature = "std")] impl Deserialize for CString { fn deserialize(deserializer: D) -> Result diff --git a/serde/src/lib.rs b/serde/src/lib.rs index 9560ecb6..5c763793 100644 --- a/serde/src/lib.rs +++ b/serde/src/lib.rs @@ -61,7 +61,7 @@ #![doc(html_root_url="https://docs.serde.rs")] #![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(feature = "unstable", feature(inclusive_range, nonzero, specialization, zero_one))] +#![cfg_attr(feature = "unstable", feature(inclusive_range, nonzero, specialization, zero_one, into_boxed_c_str))] #![cfg_attr(feature = "alloc", feature(alloc))] #![cfg_attr(feature = "collections", feature(collections))] #![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))] diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs index fa5943c2..6f9b0bad 100644 --- a/test_suite/tests/test_de.rs +++ b/test_suite/tests/test_de.rs @@ -8,6 +8,9 @@ use std::time::Duration; use std::default::Default; use std::ffi::CString; +#[cfg(feature = "unstable")] +use std::ffi::CStr; + extern crate serde; use serde::Deserialize; @@ -886,6 +889,13 @@ declare_tests! { } } +#[cfg(feature = "unstable")] +#[test] +fn test_cstr() { + assert_de_tokens::>(&CString::new("abc").unwrap().into_boxed_c_str(), + &[Token::Bytes(b"abc")]); +} + #[cfg(feature = "unstable")] #[test] fn test_net_ipaddr() { @@ -895,6 +905,28 @@ fn test_net_ipaddr() { ); } +#[cfg(feature = "unstable")] +#[test] +fn test_cstr_internal_null() { + assert_de_tokens_error::>( + &[ + Token::Bytes(b"a\0c"), + ], + Error::Message("nul byte found in provided data at position: 1".into()) + ); +} + +#[cfg(feature = "unstable")] +#[test] +fn test_cstr_internal_null_end() { + assert_de_tokens_error::>( + &[ + Token::Bytes(b"ac\0"), + ], + Error::Message("nul byte found in provided data at position: 2".into()) + ); +} + declare_error_tests! { test_unknown_field { &[