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

Disallow serde serialize/deserialize unsigned integer types #72

Merged
merged 3 commits into from
May 30, 2017
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "bson"
version = "0.7.1"
version = "0.8.0"
authors = [
"Y. T. Chung <zonyitoo@gmail.com>",
"Kevin Yeh <kevinyeah@utexas.edu>"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub struct Person {
#[serde(rename = "_id")] // Use MongoDB's special primary key field name when serializing
pub id: String,
pub name: String,
pub age: u32
pub age: i32
}
```

Expand Down
2 changes: 1 addition & 1 deletion src/bson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl Debug for Bson {
&Bson::FloatingPoint(p) => write!(f, "FloatingPoint({:?})", p),
&Bson::String(ref s) => write!(f, "String({:?})", s),
&Bson::Array(ref vec) => write!(f, "Array({:?})", vec),
&Bson::Document(ref doc) => write!(f, "Document({})", doc),
&Bson::Document(ref doc) => write!(f, "Document({:?})", doc),
&Bson::Boolean(b) => write!(f, "Boolean({:?})", b),
&Bson::Null => write!(f, "Null"),
&Bson::RegExp(ref pat, ref opt) => write!(f, "RegExp(/{:?}/{:?})", pat, opt),
Expand Down
3 changes: 3 additions & 0 deletions src/compat/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! Backward compatibility

pub mod u2f;
79 changes: 79 additions & 0 deletions src/compat/u2f.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! Convert unsigned types to/from `Bson::FloatingPoint`

use serde::{Serializer, Deserializer, Deserialize};

/// Converts primitive unsigned types to `f64`
pub trait ToF64 {
/// Converts to `f64` value
fn to_f64(&self) -> f64;
}

impl ToF64 for u8 {
fn to_f64(&self) -> f64 {
*self as f64
}
}

impl ToF64 for u16 {
fn to_f64(&self) -> f64 {
*self as f64
}
}

impl ToF64 for u32 {
fn to_f64(&self) -> f64 {
*self as f64
}
}

impl ToF64 for u64 {
fn to_f64(&self) -> f64 {
*self as f64
}
}

/// Serialize unsigned types to `Bson::FloatingPoint`
pub fn serialize<T, S>(v: &T, s: S) -> Result<S::Ok, S::Error>
where T: ToF64,
S: Serializer
{
s.serialize_f64(v.to_f64())
}

/// Converts from `f64` value
pub trait FromF64 {
/// Converts from `f64` value
fn from_f64(v: f64) -> Self;
}

impl FromF64 for u8 {
fn from_f64(v: f64) -> u8 {
v as u8
}
}

impl FromF64 for u16 {
fn from_f64(v: f64) -> u16 {
v as u16
}
}

impl FromF64 for u32 {
fn from_f64(v: f64) -> u32 {
v as u32
}
}

impl FromF64 for u64 {
fn from_f64(v: f64) -> u64 {
v as u64
}
}

/// Deserialize unsigned types to `Bson::FloatingPoint`
pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
where D: Deserializer<'de>,
T: FromF64
{
f64::deserialize(d).map(T::from_f64)
}
47 changes: 39 additions & 8 deletions src/decoder/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fmt;

use serde::de::{self, Deserialize, Deserializer, Visitor, MapAccess, SeqAccess, VariantAccess,
DeserializeSeed, EnumAccess};
use serde::de::Unexpected;
use serde::de::{Error, Unexpected};

use bson::{Bson, UtcDateTime};
use oid::ObjectId;
Expand Down Expand Up @@ -62,35 +62,66 @@ impl<'de> Visitor<'de> for BsonVisitor {
}

#[inline]
fn visit_bool<E>(self, value: bool) -> Result<Bson, E> {
fn visit_bool<E>(self, value: bool) -> Result<Bson, E>
where E: Error
{
Ok(Bson::Boolean(value))
}

#[inline]
fn visit_i8<E>(self, value: i8) -> Result<Bson, E> {
fn visit_i8<E>(self, value: i8) -> Result<Bson, E>
where E: Error
{
Ok(Bson::I32(value as i32))
}

#[inline]
fn visit_u8<E>(self, value: u8) -> Result<Bson, E>
where E: Error
{
Err(Error::invalid_type(Unexpected::Unsigned(value as u64), &"a signed integer"))
}

#[inline]
fn visit_i16<E>(self, value: i16) -> Result<Bson, E> {
fn visit_i16<E>(self, value: i16) -> Result<Bson, E>
where E: Error
{
Ok(Bson::I32(value as i32))
}

#[inline]
fn visit_u16<E>(self, value: u16) -> Result<Bson, E>
where E: Error
{
Err(Error::invalid_type(Unexpected::Unsigned(value as u64), &"a signed integer"))
}

#[inline]
fn visit_i32<E>(self, value: i32) -> Result<Bson, E> {
fn visit_i32<E>(self, value: i32) -> Result<Bson, E>
where E: Error
{
Ok(Bson::I32(value))
}

#[inline]
fn visit_i64<E>(self, value: i64) -> Result<Bson, E> {
fn visit_u32<E>(self, value: u32) -> Result<Bson, E>
where E: Error
{
Err(Error::invalid_type(Unexpected::Unsigned(value as u64), &"a signed integer"))
}

#[inline]
fn visit_i64<E>(self, value: i64) -> Result<Bson, E>
where E: Error
{
Ok(Bson::I64(value))
}

#[inline]
fn visit_u64<E>(self, value: u64) -> Result<Bson, E> {
Ok(Bson::I64(value as i64))
fn visit_u64<E>(self, value: u64) -> Result<Bson, E>
where E: Error
{
Err(Error::invalid_type(Unexpected::Unsigned(value), &"a signed integer"))
}

#[inline]
Expand Down
3 changes: 3 additions & 0 deletions src/encoder/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub enum EncoderError {
IoError(io::Error),
InvalidMapKeyType(Bson),
Unknown(String),
UnsupportedUnsignedType,
}

impl From<io::Error> for EncoderError {
Expand All @@ -25,6 +26,7 @@ impl fmt::Display for EncoderError {
write!(fmt, "Invalid map key type: {:?}", bson)
}
&EncoderError::Unknown(ref inner) => inner.fmt(fmt),
&EncoderError::UnsupportedUnsignedType => write!(fmt, "BSON does not support unsigned type"),
}
}
}
Expand All @@ -35,6 +37,7 @@ impl error::Error for EncoderError {
&EncoderError::IoError(ref inner) => inner.description(),
&EncoderError::InvalidMapKeyType(_) => "Invalid map key type",
&EncoderError::Unknown(ref inner) => inner,
&EncoderError::UnsupportedUnsignedType => "BSON does not support unsigned type",
}
}
fn cause(&self) -> Option<&error::Error> {
Expand Down
28 changes: 14 additions & 14 deletions src/encoder/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,38 +87,38 @@ impl Serializer for Encoder {
}

#[inline]
fn serialize_i16(self, value: i16) -> EncoderResult<Bson> {
self.serialize_i32(value as i32)
fn serialize_u8(self, _value: u8) -> EncoderResult<Bson> {
Err(EncoderError::UnsupportedUnsignedType)
}

#[inline]
fn serialize_i32(self, value: i32) -> EncoderResult<Bson> {
Ok(Bson::I32(value))
fn serialize_i16(self, value: i16) -> EncoderResult<Bson> {
self.serialize_i32(value as i32)
}

#[inline]
fn serialize_i64(self, value: i64) -> EncoderResult<Bson> {
Ok(Bson::I64(value))
fn serialize_u16(self, _value: u16) -> EncoderResult<Bson> {
Err(EncoderError::UnsupportedUnsignedType)
}

#[inline]
fn serialize_u8(self, value: u8) -> EncoderResult<Bson> {
self.serialize_u64(value as u64)
fn serialize_i32(self, value: i32) -> EncoderResult<Bson> {
Ok(Bson::I32(value))
}

#[inline]
fn serialize_u16(self, value: u16) -> EncoderResult<Bson> {
self.serialize_u64(value as u64)
fn serialize_u32(self, _value: u32) -> EncoderResult<Bson> {
Err(EncoderError::UnsupportedUnsignedType)
}

#[inline]
fn serialize_u32(self, value: u32) -> EncoderResult<Bson> {
self.serialize_u64(value as u64)
fn serialize_i64(self, value: i64) -> EncoderResult<Bson> {
Ok(Bson::I64(value))
}

#[inline]
fn serialize_u64(self, value: u64) -> EncoderResult<Bson> {
Ok(Bson::FloatingPoint(value as f64))
fn serialize_u64(self, _value: u64) -> EncoderResult<Bson> {
Err(EncoderError::UnsupportedUnsignedType)
}

#[inline]
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,4 @@ mod bson;
mod encoder;
mod decoder;
pub mod ordered;
pub mod compat;
17 changes: 17 additions & 0 deletions tests/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,20 @@ fn test_ser_datetime() {
let xfoo: Foo = bson::from_bson(x).unwrap();
assert_eq!(xfoo, foo);
}


#[test]
fn test_compat_u2f() {
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
struct Foo {
#[serde(with = "bson::compat::u2f")]
x: u32
}

let foo = Foo { x: 20 };
let b = bson::to_bson(&foo).unwrap();
assert_eq!(b, Bson::Document(doc! { "x" => (Bson::FloatingPoint(20.0)) }));

let de_foo = bson::from_bson::<Foo>(b).unwrap();
assert_eq!(de_foo, foo);
}