зеркало из https://github.com/mozilla/gecko-dev.git
Bug 1373381 - Re-vendor third-party libraries. r=jrmuizel
MozReview-Commit-ID: DLHlIDQCypR --HG-- rename : third_party/rust/serde_codegen_internals/LICENSE-APACHE => third_party/rust/serde_derive_internals/LICENSE-APACHE rename : third_party/rust/serde-0.9.9/LICENSE-MIT => third_party/rust/serde_derive_internals/LICENSE-MIT extra : rebase_source : ad913d9923367fc3e022e8ac5ccedfa0491c6dee
This commit is contained in:
Родитель
40bd0b7997
Коммит
1dc39de685
|
@ -1 +0,0 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"12cc0f91b51fedf41ae1670d1624ee1d78a284bdb101645b60a06a12de16c069",".travis.yml":"6b96b2c6bfd7e1acef4b825a2813fc4277859eb9400a16800db8835c25e4087d","Cargo.toml":"e8e47fdafc02dca1094469954c142173859165ac583ff702500d6feef5b7cd3f","README.md":"9f048d969f9f8333cdcdb892744cd0816e4f2922c8817fa5e9e07f9472fe1050","src/app_unit.rs":"da3c29a2fa7fc357f41df76f29a5f6983d878a5050cf07443a20c00fe46094fd","src/lib.rs":"2df7d863c47d8b22f9af66caeafa87e6a206ee713a8aeaa55c5a80a42a92513b"},"package":"c89beb28482985f88b312de4021d748f45b3eecec6cc8dbaf0c2b3c3d1ce6da5"}
|
|
@ -1,2 +0,0 @@
|
|||
target/
|
||||
Cargo.lock
|
|
@ -1,8 +0,0 @@
|
|||
language: rust
|
||||
notifications:
|
||||
webhooks: http://build.servo.org:54856/travis
|
||||
|
||||
rust:
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
|
@ -1,14 +0,0 @@
|
|||
[package]
|
||||
name = "app_units"
|
||||
version = "0.4.1"
|
||||
authors = ["The Servo Project Developers"]
|
||||
description = "Servo app units type (Au)"
|
||||
documentation = "http://doc.servo.org/app_units/"
|
||||
repository = "https://github.com/servo/app_units"
|
||||
license = "MPL-2.0"
|
||||
|
||||
[dependencies]
|
||||
heapsize = "0.3"
|
||||
num-traits = "0.1.32"
|
||||
rustc-serialize = "0.3"
|
||||
serde = "0.9"
|
|
@ -1,3 +0,0 @@
|
|||
# app-units
|
||||
|
||||
[Documentation](http://doc.servo.org/app_units/index.html)
|
|
@ -1,379 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
use heapsize::HeapSizeOf;
|
||||
use num_traits::Zero;
|
||||
use rustc_serialize::{Encodable, Encoder};
|
||||
use serde::de::{Deserialize, Deserializer};
|
||||
use serde::ser::{Serialize, Serializer};
|
||||
use std::default::Default;
|
||||
use std::fmt;
|
||||
use std::i32;
|
||||
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
|
||||
|
||||
/// The number of app units in a pixel.
|
||||
pub const AU_PER_PX: i32 = 60;
|
||||
|
||||
#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)]
|
||||
/// An App Unit, the fundamental unit of length in Servo. Usually
|
||||
/// 1/60th of a pixel (see AU_PER_PX)
|
||||
///
|
||||
/// Please ensure that the values are between MIN_AU and MAX_AU.
|
||||
/// It is safe to construct invalid Au values, but it may lead to
|
||||
/// panics and overflows.
|
||||
pub struct Au(pub i32);
|
||||
|
||||
impl HeapSizeOf for Au {
|
||||
fn heap_size_of_children(&self) -> usize { 0 }
|
||||
}
|
||||
|
||||
impl Deserialize for Au {
|
||||
fn deserialize<D: Deserializer>(deserializer: D) -> Result<Au, D::Error> {
|
||||
Ok(Au(try!(i32::deserialize(deserializer))).clamp())
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Au {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Au {
|
||||
#[inline]
|
||||
fn default() -> Au {
|
||||
Au(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Zero for Au {
|
||||
#[inline]
|
||||
fn zero() -> Au {
|
||||
Au(0)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_zero(&self) -> bool {
|
||||
self.0 == 0
|
||||
}
|
||||
}
|
||||
|
||||
// 1 << 30 lets us add/subtract two Au and check for overflow
|
||||
// after the operation. Gecko uses the same min/max values
|
||||
pub const MAX_AU: Au = Au(1 << 30);
|
||||
pub const MIN_AU: Au = Au(- (1 << 30));
|
||||
|
||||
impl Encodable for Au {
|
||||
fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
|
||||
e.emit_f64(self.to_f64_px())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Au {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}px", self.to_f64_px())
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Au {
|
||||
type Output = Au;
|
||||
|
||||
#[inline]
|
||||
fn add(self, other: Au) -> Au {
|
||||
Au(self.0 + other.0).clamp()
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Au {
|
||||
type Output = Au;
|
||||
|
||||
#[inline]
|
||||
fn sub(self, other: Au) -> Au {
|
||||
Au(self.0 - other.0).clamp()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Mul<i32> for Au {
|
||||
type Output = Au;
|
||||
|
||||
#[inline]
|
||||
fn mul(self, other: i32) -> Au {
|
||||
if let Some(new) = self.0.checked_mul(other) {
|
||||
Au(new).clamp()
|
||||
} else if (self.0 > 0) ^ (other > 0) {
|
||||
MIN_AU
|
||||
} else {
|
||||
MAX_AU
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Div<i32> for Au {
|
||||
type Output = Au;
|
||||
|
||||
#[inline]
|
||||
fn div(self, other: i32) -> Au {
|
||||
Au(self.0 / other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Rem<i32> for Au {
|
||||
type Output = Au;
|
||||
|
||||
#[inline]
|
||||
fn rem(self, other: i32) -> Au {
|
||||
Au(self.0 % other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Neg for Au {
|
||||
type Output = Au;
|
||||
|
||||
#[inline]
|
||||
fn neg(self) -> Au {
|
||||
Au(-self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl AddAssign for Au {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, other: Au) {
|
||||
*self = *self + other;
|
||||
self.clamp_self();
|
||||
}
|
||||
}
|
||||
|
||||
impl SubAssign for Au {
|
||||
#[inline]
|
||||
fn sub_assign(&mut self, other: Au) {
|
||||
*self = *self - other;
|
||||
self.clamp_self();
|
||||
}
|
||||
}
|
||||
|
||||
impl MulAssign<i32> for Au {
|
||||
#[inline]
|
||||
fn mul_assign(&mut self, other: i32) {
|
||||
*self = *self * other;
|
||||
self.clamp_self();
|
||||
}
|
||||
}
|
||||
|
||||
impl DivAssign<i32> for Au {
|
||||
#[inline]
|
||||
fn div_assign(&mut self, other: i32) {
|
||||
*self = *self / other;
|
||||
self.clamp_self();
|
||||
}
|
||||
}
|
||||
|
||||
impl Au {
|
||||
/// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
|
||||
#[inline]
|
||||
pub fn new(value: i32) -> Au {
|
||||
Au(value).clamp()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn clamp(self) -> Self {
|
||||
if self.0 > MAX_AU.0 {
|
||||
MAX_AU
|
||||
} else if self.0 < MIN_AU.0 {
|
||||
MIN_AU
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn clamp_self(&mut self) {
|
||||
*self = self.clamp()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_by(self, factor: f32) -> Au {
|
||||
let new_float = ((self.0 as f32) * factor).round();
|
||||
if new_float > MAX_AU.0 as f32 {
|
||||
MAX_AU
|
||||
} else if new_float < MIN_AU.0 as f32 {
|
||||
MIN_AU
|
||||
} else {
|
||||
Au(new_float as i32)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_px(px: i32) -> Au {
|
||||
Au(px) * AU_PER_PX
|
||||
}
|
||||
|
||||
/// Rounds this app unit down to the pixel towards zero and returns it.
|
||||
#[inline]
|
||||
pub fn to_px(self) -> i32 {
|
||||
self.0 / AU_PER_PX
|
||||
}
|
||||
|
||||
/// Ceil this app unit to the appropriate pixel boundary and return it.
|
||||
#[inline]
|
||||
pub fn ceil_to_px(self) -> i32 {
|
||||
((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_nearest_px(self) -> i32 {
|
||||
((self.0 as f64) / (AU_PER_PX as f64)).round() as i32
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 {
|
||||
((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_f32_px(self) -> f32 {
|
||||
(self.0 as f32) / (AU_PER_PX as f32)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_f64_px(self) -> f64 {
|
||||
(self.0 as f64) / (AU_PER_PX as f64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_f32_px(px: f32) -> Au {
|
||||
let float = (px * AU_PER_PX as f32).round();
|
||||
if float > MAX_AU.0 as f32 {
|
||||
MAX_AU
|
||||
} else if float < MIN_AU.0 as f32 {
|
||||
MIN_AU
|
||||
} else {
|
||||
Au(float as i32)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_f64_px(px: f64) -> Au {
|
||||
let float = (px * AU_PER_PX as f64).round();
|
||||
if float > MAX_AU.0 as f64 {
|
||||
MAX_AU
|
||||
} else if float < MIN_AU.0 as f64 {
|
||||
MIN_AU
|
||||
} else {
|
||||
Au(float as i32)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create() {
|
||||
assert_eq!(Au::zero(), Au(0));
|
||||
assert_eq!(Au::default(), Au(0));
|
||||
assert_eq!(Au::new(7), Au(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operations() {
|
||||
assert_eq!(Au(7) + Au(5), Au(12));
|
||||
assert_eq!(MAX_AU + Au(1), MAX_AU);
|
||||
|
||||
assert_eq!(Au(7) - Au(5), Au(2));
|
||||
assert_eq!(MIN_AU - Au(1), MIN_AU);
|
||||
|
||||
assert_eq!(Au(7) * 5, Au(35));
|
||||
assert_eq!(MAX_AU * -1, MIN_AU);
|
||||
assert_eq!(MIN_AU * -1, MAX_AU);
|
||||
|
||||
assert_eq!(Au(35) / 5, Au(7));
|
||||
assert_eq!(Au(35) % 6, Au(5));
|
||||
|
||||
assert_eq!(-Au(7), Au(-7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturate() {
|
||||
let half = MAX_AU / 2;
|
||||
assert_eq!(half + half + half + half + half, MAX_AU);
|
||||
assert_eq!(-half - half - half - half - half, MIN_AU);
|
||||
assert_eq!(half * -10, MIN_AU);
|
||||
assert_eq!(-half * 10, MIN_AU);
|
||||
assert_eq!(half * 10, MAX_AU);
|
||||
assert_eq!(-half * -10, MAX_AU);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale() {
|
||||
assert_eq!(Au(12).scale_by(1.5), Au(18));
|
||||
assert_eq!(Au(12).scale_by(1.7), Au(20));
|
||||
assert_eq!(Au(12).scale_by(1.8), Au(22));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert() {
|
||||
assert_eq!(Au::from_px(5), Au(300));
|
||||
|
||||
assert_eq!(Au(300).to_px(), 5);
|
||||
assert_eq!(Au(330).to_px(), 5);
|
||||
assert_eq!(Au(350).to_px(), 5);
|
||||
assert_eq!(Au(360).to_px(), 6);
|
||||
|
||||
assert_eq!(Au(300).ceil_to_px(), 5);
|
||||
assert_eq!(Au(310).ceil_to_px(), 6);
|
||||
assert_eq!(Au(330).ceil_to_px(), 6);
|
||||
assert_eq!(Au(350).ceil_to_px(), 6);
|
||||
assert_eq!(Au(360).ceil_to_px(), 6);
|
||||
|
||||
assert_eq!(Au(300).to_nearest_px(), 5);
|
||||
assert_eq!(Au(310).to_nearest_px(), 5);
|
||||
assert_eq!(Au(330).to_nearest_px(), 6);
|
||||
assert_eq!(Au(350).to_nearest_px(), 6);
|
||||
assert_eq!(Au(360).to_nearest_px(), 6);
|
||||
|
||||
assert_eq!(Au(60).to_nearest_pixel(2.), 1.);
|
||||
assert_eq!(Au(70).to_nearest_pixel(2.), 1.);
|
||||
assert_eq!(Au(80).to_nearest_pixel(2.), 1.5);
|
||||
assert_eq!(Au(90).to_nearest_pixel(2.), 1.5);
|
||||
assert_eq!(Au(100).to_nearest_pixel(2.), 1.5);
|
||||
assert_eq!(Au(110).to_nearest_pixel(2.), 2.);
|
||||
assert_eq!(Au(120).to_nearest_pixel(2.), 2.);
|
||||
|
||||
assert_eq!(Au(300).to_f32_px(), 5.);
|
||||
assert_eq!(Au(312).to_f32_px(), 5.2);
|
||||
assert_eq!(Au(330).to_f32_px(), 5.5);
|
||||
assert_eq!(Au(348).to_f32_px(), 5.8);
|
||||
assert_eq!(Au(360).to_f32_px(), 6.);
|
||||
assert_eq!((Au(367).to_f32_px() * 1000.).round(), 6_117.);
|
||||
assert_eq!((Au(368).to_f32_px() * 1000.).round(), 6_133.);
|
||||
|
||||
assert_eq!(Au(300).to_f64_px(), 5.);
|
||||
assert_eq!(Au(312).to_f64_px(), 5.2);
|
||||
assert_eq!(Au(330).to_f64_px(), 5.5);
|
||||
assert_eq!(Au(348).to_f64_px(), 5.8);
|
||||
assert_eq!(Au(360).to_f64_px(), 6.);
|
||||
assert_eq!((Au(367).to_f64_px() * 1000.).round(), 6_117.);
|
||||
assert_eq!((Au(368).to_f64_px() * 1000.).round(), 6_133.);
|
||||
|
||||
assert_eq!(Au::from_f32_px(5.), Au(300));
|
||||
assert_eq!(Au::from_f32_px(5.2), Au(312));
|
||||
assert_eq!(Au::from_f32_px(5.5), Au(330));
|
||||
assert_eq!(Au::from_f32_px(5.8), Au(348));
|
||||
assert_eq!(Au::from_f32_px(6.), Au(360));
|
||||
assert_eq!(Au::from_f32_px(6.12), Au(367));
|
||||
assert_eq!(Au::from_f32_px(6.13), Au(368));
|
||||
|
||||
assert_eq!(Au::from_f64_px(5.), Au(300));
|
||||
assert_eq!(Au::from_f64_px(5.2), Au(312));
|
||||
assert_eq!(Au::from_f64_px(5.5), Au(330));
|
||||
assert_eq!(Au::from_f64_px(5.8), Au(348));
|
||||
assert_eq!(Au::from_f64_px(6.), Au(360));
|
||||
assert_eq!(Au::from_f64_px(6.12), Au(367));
|
||||
assert_eq!(Au::from_f64_px(6.13), Au(368));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heapsize() {
|
||||
use heapsize::HeapSizeOf;
|
||||
fn f<T: HeapSizeOf>(_: T) {}
|
||||
f(Au::new(0));
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
//! An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was
|
||||
//! originally proposed in 2002 as a standard unit of measure in Gecko.
|
||||
//! See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
|
||||
|
||||
extern crate heapsize;
|
||||
extern crate num_traits;
|
||||
extern crate rustc_serialize;
|
||||
extern crate serde;
|
||||
|
||||
mod app_unit;
|
||||
|
||||
pub use app_unit::{Au, MIN_AU, MAX_AU, AU_PER_PX};
|
|
@ -1 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"e084df3ce631ce22082bd63f9e421e7f4d7a2408d6520de532f6a649e4d320dd",".travis.yml":"f705a11b487bf71c41ebd8223cc1f3cbde0dfdfeea96a100af55e06e93397a1b","Cargo.toml":"3268085d1b2f5a6b658d02c98188a631e81c18323dbe1af2cbcccde8664bf2a4","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","changelist.org":"7e1dd0a38f886c111f9a50bc5ecd8ccab0800fcc737c1c211cc5c3361648aa2b","examples/basic.rs":"ef6ab76936c8322b9f89fe8308311339c0bf7b413c5f88b5314b0035d49917a3","logo.png":"ebc5305aae938c1f834cf35302faa8be0f1b7b8c3c3beef5cf6b2f68b9628c35","readme.dev.md":"43bad3bcc13a5c057344d3ba7f64bd2b313f8c133d6afa068108df73e8e8facd","readme.md":"06e09e4e80b048416116640a8352305ceae48f775fd13786c25892cbf55c8fbd","src/lib.rs":"a4dff78a7c5af47c1dc9f240ba7ba3305dd66f638d2d326627093bb326c5fe59","src/refbox.rs":"fe266cec4f9f36942a1a9a9ad094a4bb1003d0c0f3c070cfb6214790d0f21b69","src/serde/mod.rs":"a4aaf85ac92468e246be4533f014b93b8e21059da22342155d03578a81e7f556","src/serde/reader.rs":"21db7aa79660acaa2ac39adfe273a99a27c2a1c39506e2a782f9c7f76500f866","src/serde/writer.rs":"02819f71cda1742188feb66c9ecf58bbd4e35c6d88961763667a3cde72450963","tests/test.rs":"36f7e11cc480ea9f68c4656d55e065f69998346baa8112fcde1f9c1dc4891c02"},"package":"fb0cdeac1c5d567fdb487ae5853c024e4acf1ea85ba6a6552fe084e0805fea5d"}
|
||||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"e084df3ce631ce22082bd63f9e421e7f4d7a2408d6520de532f6a649e4d320dd",".travis.yml":"f705a11b487bf71c41ebd8223cc1f3cbde0dfdfeea96a100af55e06e93397a1b","Cargo.toml":"b3ef32df664d22cfe4526f0022c8789e8976970b9e0982e1dd52f4f811134515","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","changelist.org":"936b58455e1c221539b73b5250302dcd96baa04a5d8536199d3351142addad57","examples/basic.rs":"ef6ab76936c8322b9f89fe8308311339c0bf7b413c5f88b5314b0035d49917a3","logo.png":"ebc5305aae938c1f834cf35302faa8be0f1b7b8c3c3beef5cf6b2f68b9628c35","readme.dev.md":"43bad3bcc13a5c057344d3ba7f64bd2b313f8c133d6afa068108df73e8e8facd","readme.md":"ca48b4a712089d792d449ef6e0e399efaf227dbcfcb141540684a16a2763583b","src/de/mod.rs":"8651e00130bd062e2305dcce8b68d777fff9877688e776b239778e18046dddaf","src/de/read.rs":"5abca51c6f0d93cc144914ed30bf2cfd0074ced09a0de8c3983997aaa471562d","src/internal.rs":"d9448e8467caf4cf24703626dab9e0d9420e98419e323ad7e611e4aeab525e4a","src/lib.rs":"998b85e103f8f5480ffeef43bd8430a66c061011055a053377f37dce32bf9088","src/ser/mod.rs":"0eeb467eeb8189fb935e4996cd45d1f292c401f92b00793907bd428f1bde421d","tests/test.rs":"26598b882a691caa5301a569e56e31567bfba5ffeab6f0ca67ebd95bfae679b0"},"package":"e103c8b299b28a9c6990458b7013dc4a8356a9b854c51b9883241f5866fac36e"}
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "bincode"
|
||||
version = "1.0.0-alpha6"
|
||||
version = "0.8.0"
|
||||
authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Daniel Griffen"]
|
||||
|
||||
repository = "https://github.com/TyOverby/bincode"
|
||||
|
@ -13,9 +13,8 @@ description = "A binary serialization / deserialization strategy that uses Serde
|
|||
[dependencies]
|
||||
byteorder = "1.0.0"
|
||||
num-traits = "0.1.32"
|
||||
|
||||
[dependencies.serde]
|
||||
version = "0.9.*"
|
||||
serde = "1.*.*"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_derive = "0.9.*"
|
||||
serde_bytes = "0.10.*"
|
||||
serde_derive = "1.*.*"
|
||||
|
|
|
@ -22,3 +22,6 @@
|
|||
|
||||
** Changed SizeLimit to be a trait instead of an enum
|
||||
Mostly for performance reasons.
|
||||
|
||||
** Removed RefBox / StrBox / SliceBox
|
||||
Since rustc-serialize support was phased out, you can use `Cow<T>` with serde.
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
[![](http://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode)
|
||||
[![](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT)
|
||||
|
||||
A compact encoder / decoder pair that uses an binary zero-fluff encoding scheme.
|
||||
A compact encoder / decoder pair that uses a binary zero-fluff encoding scheme.
|
||||
The size of the encoded object will be the same or smaller than the size that
|
||||
the object takes up in memory in a running Rust program.
|
||||
|
||||
|
@ -30,7 +30,7 @@ library.
|
|||
extern crate serde_derive;
|
||||
extern crate bincode;
|
||||
|
||||
use bincode::{serialize, deserialize, SizeLimit};
|
||||
use bincode::{serialize, deserialize, Infinite};
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq)]
|
||||
struct Entity {
|
||||
|
@ -44,7 +44,7 @@ struct World(Vec<Entity>);
|
|||
fn main() {
|
||||
let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);
|
||||
|
||||
let encoded: Vec<u8> = serialize(&world, SizeLimit::Infinite).unwrap();
|
||||
let encoded: Vec<u8> = serialize(&world, Infinite).unwrap();
|
||||
|
||||
// 8 bytes for the length of the vector, 4 bytes per float.
|
||||
assert_eq!(encoded.len(), 8 + 4 * 4);
|
||||
|
|
|
@ -1,21 +1,24 @@
|
|||
use std::cmp;
|
||||
use std::io::Read;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use byteorder::{ReadBytesExt, ByteOrder};
|
||||
use serde_crate as serde;
|
||||
use serde_crate::de::value::ValueDeserializer;
|
||||
use serde_crate::de::IntoDeserializer;
|
||||
use serde_crate::de::Error as DeError;
|
||||
use ::SizeLimit;
|
||||
use super::{Result, Error, ErrorKind};
|
||||
use self::read::BincodeRead;
|
||||
|
||||
const BLOCK_SIZE: usize = 65536;
|
||||
pub mod read;
|
||||
|
||||
/// A Deserializer that reads bytes from a buffer.
|
||||
///
|
||||
/// This struct should rarely be used.
|
||||
/// In most cases, prefer the `decode_from` function.
|
||||
///
|
||||
/// The ByteOrder that is chosen will impact the endianness that
|
||||
/// is used to read integers out of the reader.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let d = Deserializer::new(&mut some_reader, SizeLimit::new());
|
||||
/// serde::Deserialize::deserialize(&mut deserializer);
|
||||
|
@ -24,25 +27,19 @@ const BLOCK_SIZE: usize = 65536;
|
|||
pub struct Deserializer<R, S: SizeLimit, E: ByteOrder> {
|
||||
reader: R,
|
||||
size_limit: S,
|
||||
read: u64,
|
||||
_phantom: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<R: Read, E: ByteOrder, S: SizeLimit> Deserializer<R, S, E> {
|
||||
impl<'de, R: BincodeRead<'de>, E: ByteOrder, S: SizeLimit> Deserializer<R, S, E> {
|
||||
/// Creates a new Deserializer with a given `Read`er and a size_limit.
|
||||
pub fn new(r: R, size_limit: S) -> Deserializer<R, S, E> {
|
||||
Deserializer {
|
||||
reader: r,
|
||||
size_limit: size_limit,
|
||||
read: 0,
|
||||
_phantom: PhantomData
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of bytes read from the contained Reader.
|
||||
pub fn bytes_read(&self) -> u64 {
|
||||
self.read
|
||||
}
|
||||
|
||||
fn read_bytes(&mut self, count: u64) -> Result<()> {
|
||||
self.size_limit.add(count)
|
||||
}
|
||||
|
@ -53,22 +50,9 @@ impl<R: Read, E: ByteOrder, S: SizeLimit> Deserializer<R, S, E> {
|
|||
}
|
||||
|
||||
fn read_vec(&mut self) -> Result<Vec<u8>> {
|
||||
let mut len: usize = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
|
||||
let mut result = Vec::new();
|
||||
let mut off = 0;
|
||||
while len > 0 {
|
||||
let reserve = cmp::min(len, BLOCK_SIZE);
|
||||
try!(self.read_bytes(reserve as u64));
|
||||
unsafe {
|
||||
result.reserve(reserve);
|
||||
result.set_len(off + reserve);
|
||||
}
|
||||
try!(self.reader.read_exact(&mut result[off..]));
|
||||
len -= reserve;
|
||||
off += reserve;
|
||||
}
|
||||
Ok(result)
|
||||
let len: usize = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
self.read_bytes(len as u64)?;
|
||||
self.reader.get_byte_buffer(len)
|
||||
}
|
||||
|
||||
fn read_string(&mut self) -> Result<String> {
|
||||
|
@ -84,7 +68,7 @@ macro_rules! impl_nums {
|
|||
($ty:ty, $dser_method:ident, $visitor_method:ident, $reader_method:ident) => {
|
||||
#[inline]
|
||||
fn $dser_method<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
try!(self.read_type::<$ty>());
|
||||
let value = try!(self.reader.$reader_method::<E>());
|
||||
|
@ -93,20 +77,20 @@ macro_rules! impl_nums {
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, R, S, E> serde::Deserializer for &'a mut Deserializer<R, S, E>
|
||||
where R: Read, S: SizeLimit, E: ByteOrder {
|
||||
impl<'de, 'a, R, S, E> serde::Deserializer<'de> for &'a mut Deserializer<R, S, E>
|
||||
where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn deserialize<V>(self, _visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let message = "bincode does not support Deserializer::deserialize";
|
||||
Err(Error::custom(message))
|
||||
}
|
||||
|
||||
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let value: u8 = try!(serde::Deserialize::deserialize(self));
|
||||
match value {
|
||||
|
@ -133,7 +117,7 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
|
||||
#[inline]
|
||||
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
try!(self.read_type::<u8>());
|
||||
visitor.visit_u8(try!(self.reader.read_u8()))
|
||||
|
@ -141,20 +125,20 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
|
||||
#[inline]
|
||||
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
try!(self.read_type::<i8>());
|
||||
visitor.visit_i8(try!(self.reader.read_i8()))
|
||||
}
|
||||
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
use std::str;
|
||||
|
||||
|
@ -182,25 +166,29 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_str(&try!(self.read_string()))
|
||||
let len: usize = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
try!(self.read_bytes(len as u64));
|
||||
self.reader.forward_read_str(len, visitor)
|
||||
}
|
||||
|
||||
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_string(try!(self.read_string()))
|
||||
}
|
||||
|
||||
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_bytes(&try!(self.read_vec()))
|
||||
let len: usize = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
try!(self.read_bytes(len as u64));
|
||||
self.reader.forward_read_bytes(len, visitor)
|
||||
}
|
||||
|
||||
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_byte_buf(try!(self.read_vec()))
|
||||
}
|
||||
|
@ -209,15 +197,15 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
_enum: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
impl<'a, R: 'a, S, E> serde::de::EnumVisitor for &'a mut Deserializer<R, S, E>
|
||||
where R: Read, S: SizeLimit, E: ByteOrder {
|
||||
impl<'de, 'a, R: 'a, S, E> serde::de::EnumAccess<'de> for &'a mut Deserializer<R, S, E>
|
||||
where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
||||
type Error = Error;
|
||||
type Variant = Self;
|
||||
|
||||
fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
|
||||
where V: serde::de::DeserializeSeed,
|
||||
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
|
||||
where V: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
let idx: u32 = try!(serde::de::Deserialize::deserialize(&mut *self));
|
||||
let val: Result<_> = seed.deserialize(idx.into_deserializer());
|
||||
|
@ -227,41 +215,22 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
|
||||
visitor.visit_enum(self)
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
{
|
||||
struct TupleVisitor<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a>(&'a mut Deserializer<R, S, E>);
|
||||
|
||||
impl<'a, 'b: 'a, R: Read + 'b, S: SizeLimit, E: ByteOrder> serde::de::SeqVisitor for TupleVisitor<'a, R, S, E> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
|
||||
where T: serde::de::DeserializeSeed,
|
||||
{
|
||||
let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.0));
|
||||
Ok(Some(value))
|
||||
}
|
||||
}
|
||||
|
||||
visitor.visit_seq(TupleVisitor(self))
|
||||
}
|
||||
|
||||
fn deserialize_seq_fixed_size<V>(self,
|
||||
fn deserialize_tuple<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
struct SeqVisitor<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> {
|
||||
struct Access<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> {
|
||||
deserializer: &'a mut Deserializer<R, S, E>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a, 'b: 'a, R: Read + 'b, S: SizeLimit, E: ByteOrder> serde::de::SeqVisitor for SeqVisitor<'a, R, S, E> {
|
||||
impl<'de, 'a, 'b: 'a, R: BincodeRead<'de>+ 'b, S: SizeLimit, E: ByteOrder> serde::de::SeqAccess<'de> for Access<'a, R, S, E> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
|
||||
where T: serde::de::DeserializeSeed,
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
|
||||
where T: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
if self.len > 0 {
|
||||
self.len -= 1;
|
||||
|
@ -271,13 +240,17 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
Some(self.len)
|
||||
}
|
||||
}
|
||||
|
||||
visitor.visit_seq(SeqVisitor { deserializer: self, len: len })
|
||||
visitor.visit_seq(Access { deserializer: self, len: len })
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let value: u8 = try!(serde::de::Deserialize::deserialize(&mut *self));
|
||||
match value {
|
||||
|
@ -291,26 +264,26 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
|
||||
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let len = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
|
||||
self.deserialize_seq_fixed_size(len, visitor)
|
||||
self.deserialize_tuple(len, visitor)
|
||||
}
|
||||
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
struct MapVisitor<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> {
|
||||
struct Access<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> {
|
||||
deserializer: &'a mut Deserializer<R, S, E>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a, 'b: 'a, R: Read + 'b, S: SizeLimit, E: ByteOrder> serde::de::MapVisitor for MapVisitor<'a, R, S, E> {
|
||||
impl<'de, 'a, 'b: 'a, R: BincodeRead<'de> + 'b, S: SizeLimit, E: ByteOrder> serde::de::MapAccess<'de> for Access<'a, R, S, E> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
|
||||
where K: serde::de::DeserializeSeed,
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
|
||||
where K: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
if self.len > 0 {
|
||||
self.len -= 1;
|
||||
|
@ -321,40 +294,44 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
}
|
||||
|
||||
fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
|
||||
where V: serde::de::DeserializeSeed,
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
|
||||
where V: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
Some(self.len)
|
||||
}
|
||||
}
|
||||
|
||||
let len = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
|
||||
visitor.visit_map(MapVisitor { deserializer: self, len: len })
|
||||
visitor.visit_map(Access { deserializer: self, len: len })
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(self,
|
||||
_name: &str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
self.deserialize_tuple(fields.len(), visitor)
|
||||
}
|
||||
|
||||
fn deserialize_struct_field<V>(self,
|
||||
fn deserialize_identifier<V>(self,
|
||||
_visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let message = "bincode does not support Deserializer::deserialize_struct_field";
|
||||
let message = "bincode does not support Deserializer::deserialize_identifier";
|
||||
Err(Error::custom(message))
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self,
|
||||
_name: &str,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
@ -362,7 +339,7 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
fn deserialize_unit_struct<V>(self,
|
||||
_name: &'static str,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
@ -371,46 +348,46 @@ where R: Read, S: SizeLimit, E: ByteOrder {
|
|||
_name: &'static str,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
self.deserialize_tuple(len, visitor)
|
||||
}
|
||||
|
||||
fn deserialize_ignored_any<V>(self,
|
||||
_visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let message = "bincode does not support Deserializer::deserialize_ignored_any";
|
||||
Err(Error::custom(message))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, R, S, E> serde::de::VariantVisitor for &'a mut Deserializer<R, S, E>
|
||||
where R: Read, S: SizeLimit, E: ByteOrder {
|
||||
impl<'de, 'a, R, S, E> serde::de::VariantAccess<'de> for &'a mut Deserializer<R, S, E>
|
||||
where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_unit(self) -> Result<()> {
|
||||
fn unit_variant(self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value>
|
||||
where T: serde::de::DeserializeSeed,
|
||||
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
|
||||
where T: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
serde::de::DeserializeSeed::deserialize(seed, self)
|
||||
}
|
||||
|
||||
fn visit_tuple<V>(self,
|
||||
fn tuple_variant<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
serde::de::Deserializer::deserialize_tuple(self, len, visitor)
|
||||
}
|
||||
|
||||
fn visit_struct<V>(self,
|
||||
fn struct_variant<V>(self,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor,
|
||||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
serde::de::Deserializer::deserialize_tuple(self, fields.len(), visitor)
|
||||
}
|
|
@ -0,0 +1,151 @@
|
|||
use std::io::{Read as IoRead, Result as IoResult, Error as IoError, ErrorKind as IoErrorKind};
|
||||
use ::Result;
|
||||
use serde_crate as serde;
|
||||
|
||||
/// A byte-oriented reading trait that is specialized for
|
||||
/// slices and generic readers.
|
||||
pub trait BincodeRead<'storage>: IoRead {
|
||||
#[doc(hidden)]
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage>;
|
||||
|
||||
#[doc(hidden)]
|
||||
fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>>;
|
||||
|
||||
#[doc(hidden)]
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage>;
|
||||
}
|
||||
|
||||
/// A BincodeRead implementation for byte slices
|
||||
pub struct SliceReader<'storage> {
|
||||
slice: &'storage [u8]
|
||||
}
|
||||
|
||||
/// A BincodeRead implementation for io::Readers
|
||||
pub struct IoReadReader<R> {
|
||||
reader: R,
|
||||
temp_buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl <'storage> SliceReader<'storage> {
|
||||
/// Constructs a slice reader
|
||||
pub fn new(bytes: &'storage [u8]) -> SliceReader<'storage> {
|
||||
SliceReader {
|
||||
slice: bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl <R> IoReadReader<R> {
|
||||
/// Constructs an IoReadReader
|
||||
pub fn new(r: R) -> IoReadReader<R> {
|
||||
IoReadReader {
|
||||
reader: r,
|
||||
temp_buffer: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl <'storage> IoRead for SliceReader<'storage> {
|
||||
fn read(&mut self, out: & mut [u8]) -> IoResult<usize> {
|
||||
(&mut self.slice).read(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl <R: IoRead> IoRead for IoReadReader<R> {
|
||||
fn read(&mut self, out: & mut [u8]) -> IoResult<usize> {
|
||||
self.reader.read(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl <'storage> SliceReader<'storage> {
|
||||
fn unexpected_eof() -> Box<::ErrorKind> {
|
||||
return Box::new(::ErrorKind::IoError(IoError::new(IoErrorKind::UnexpectedEof, "")));
|
||||
}
|
||||
}
|
||||
|
||||
impl <'storage> BincodeRead<'storage> for SliceReader<'storage> {
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage> {
|
||||
use ::ErrorKind;
|
||||
if length > self.slice.len() {
|
||||
return Err(SliceReader::unexpected_eof());
|
||||
}
|
||||
|
||||
let string = match ::std::str::from_utf8(&self.slice[..length]) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Box::new(ErrorKind::InvalidEncoding {
|
||||
desc: "string was not valid utf8",
|
||||
detail: None,
|
||||
})),
|
||||
};
|
||||
let r = visitor.visit_borrowed_str(string);
|
||||
self.slice = &self.slice[length..];
|
||||
r
|
||||
}
|
||||
|
||||
fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {
|
||||
if length > self.slice.len() {
|
||||
return Err(SliceReader::unexpected_eof());
|
||||
}
|
||||
|
||||
let r = &self.slice[..length];
|
||||
self.slice = &self.slice[length..];
|
||||
Ok(r.to_vec())
|
||||
}
|
||||
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage> {
|
||||
if length > self.slice.len() {
|
||||
return Err(SliceReader::unexpected_eof());
|
||||
}
|
||||
|
||||
let r = visitor.visit_borrowed_bytes(&self.slice[..length]);
|
||||
self.slice = &self.slice[length..];
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
impl <R> IoReadReader<R> where R: IoRead {
|
||||
fn fill_buffer(&mut self, length: usize) -> Result<()> {
|
||||
let current_length = self.temp_buffer.len();
|
||||
if length > current_length{
|
||||
self.temp_buffer.reserve_exact(length - current_length);
|
||||
unsafe { self.temp_buffer.set_len(length); }
|
||||
}
|
||||
|
||||
self.reader.read_exact(&mut self.temp_buffer[..length])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl <R> BincodeRead<'static> for IoReadReader<R> where R: IoRead {
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'static> {
|
||||
self.fill_buffer(length)?;
|
||||
|
||||
let string = match ::std::str::from_utf8(&self.temp_buffer[..length]) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(Box::new(::ErrorKind::InvalidEncoding {
|
||||
desc: "string was not valid utf8",
|
||||
detail: None,
|
||||
})),
|
||||
};
|
||||
|
||||
let r = visitor.visit_str(string);
|
||||
r
|
||||
}
|
||||
|
||||
fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {
|
||||
self.fill_buffer(length)?;
|
||||
Ok(self.temp_buffer[..length].to_vec())
|
||||
}
|
||||
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'static> {
|
||||
self.fill_buffer(length)?;
|
||||
let r = visitor.visit_bytes(&self.temp_buffer[..length]);
|
||||
r
|
||||
}
|
||||
}
|
|
@ -8,21 +8,19 @@ use std::{error, fmt, result};
|
|||
use ::SizeLimit;
|
||||
use byteorder::{ByteOrder};
|
||||
|
||||
pub use self::reader::{
|
||||
pub use super::de::{
|
||||
Deserializer,
|
||||
};
|
||||
|
||||
pub use self::writer::{
|
||||
pub use super::ser::{
|
||||
Serializer,
|
||||
};
|
||||
|
||||
use self::writer::SizeChecker;
|
||||
use super::ser::SizeChecker;
|
||||
|
||||
use serde_crate as serde;
|
||||
|
||||
mod reader;
|
||||
mod writer;
|
||||
|
||||
/// The result of a serialization or deserialization operation.
|
||||
pub type Result<T> = result::Result<T, Error>;
|
||||
|
||||
/// An error that can be produced during (de)serializing.
|
||||
|
@ -31,6 +29,7 @@ pub type Result<T> = result::Result<T, Error>;
|
|||
/// in an invalid state.
|
||||
pub type Error = Box<ErrorKind>;
|
||||
|
||||
/// The kind of error that can be produced during a serialization or deserialization.
|
||||
#[derive(Debug)]
|
||||
pub enum ErrorKind {
|
||||
/// If the error stems from the reader/writer that is being used
|
||||
|
@ -40,14 +39,18 @@ pub enum ErrorKind {
|
|||
/// encoding, this error will be returned. This error is only possible
|
||||
/// if a stream is corrupted. A stream produced from `encode` or `encode_into`
|
||||
/// should **never** produce an InvalidEncoding error.
|
||||
InvalidEncoding{
|
||||
desc: &'static str,
|
||||
InvalidEncoding {
|
||||
#[allow(missing_docs)]
|
||||
desc: &'static str,
|
||||
#[allow(missing_docs)]
|
||||
detail: Option<String>
|
||||
},
|
||||
/// If (de)serializing a message takes more than the provided size limit, this
|
||||
/// error is returned.
|
||||
SizeLimit,
|
||||
/// Bincode can not encode sequences of unknown length (like iterators).
|
||||
SequenceMustHaveLength,
|
||||
/// A custom error message from Serde.
|
||||
Custom(String)
|
||||
}
|
||||
|
||||
|
@ -137,15 +140,15 @@ pub fn serialize_into<W: ?Sized, T: ?Sized, S, E>(writer: &mut W, value: &T, siz
|
|||
pub fn serialize<T: ?Sized, S, E>(value: &T, size_limit: S) -> Result<Vec<u8>>
|
||||
where T: serde::Serialize, S: SizeLimit, E: ByteOrder
|
||||
{
|
||||
// Since we are putting values directly into a vector, we can do size
|
||||
// computation out here and pre-allocate a buffer of *exactly*
|
||||
// the right size.
|
||||
let mut writer = match size_limit.limit() {
|
||||
Some(size_limit) => {
|
||||
let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(ErrorKind::SizeLimit));
|
||||
Vec::with_capacity(actual_size as usize)
|
||||
}
|
||||
None => Vec::new()
|
||||
None => {
|
||||
let size = serialized_size(value) as usize;
|
||||
Vec::with_capacity(size)
|
||||
}
|
||||
};
|
||||
|
||||
try!(serialize_into::<_, _, _, E>(&mut writer, value, super::Infinite));
|
||||
|
@ -194,7 +197,7 @@ pub fn serialized_size<T: ?Sized>(value: &T) -> u64
|
|||
///
|
||||
/// If it can be serialized in `max` or fewer bytes, that number will be returned
|
||||
/// inside `Some`. If it goes over bounds, then None is returned.
|
||||
pub fn serialized_size_bounded<T: ?Sized>(value: &T, max: u64) -> Option<u64>
|
||||
pub fn serialized_size_bounded<T: ?Sized>(value: &T, max: u64) -> Option<u64>
|
||||
where T: serde::Serialize
|
||||
{
|
||||
let mut size_counter = SizeChecker {
|
||||
|
@ -217,8 +220,9 @@ pub fn serialized_size_bounded<T: ?Sized>(value: &T, max: u64) -> Option<u64>
|
|||
/// in is in an invalid state, as the error could be returned during any point
|
||||
/// in the reading.
|
||||
pub fn deserialize_from<R: ?Sized, T, S, E>(reader: &mut R, size_limit: S) -> Result<T>
|
||||
where R: Read, T: serde::Deserialize, S: SizeLimit, E: ByteOrder
|
||||
where R: Read, T: serde::de::DeserializeOwned, S: SizeLimit, E: ByteOrder
|
||||
{
|
||||
let reader = ::de::read::IoReadReader::new(reader);
|
||||
let mut deserializer = Deserializer::<_, S, E>::new(reader, size_limit);
|
||||
serde::Deserialize::deserialize(&mut deserializer)
|
||||
}
|
||||
|
@ -227,9 +231,10 @@ pub fn deserialize_from<R: ?Sized, T, S, E>(reader: &mut R, size_limit: S) -> Re
|
|||
///
|
||||
/// This method does not have a size-limit because if you already have the bytes
|
||||
/// in memory, then you don't gain anything by having a limiter.
|
||||
pub fn deserialize<T, E: ByteOrder>(bytes: &[u8]) -> Result<T>
|
||||
where T: serde::Deserialize,
|
||||
pub fn deserialize<'a, T, E: ByteOrder>(bytes: &'a [u8]) -> Result<T>
|
||||
where T: serde::de::Deserialize<'a>,
|
||||
{
|
||||
let mut reader = bytes;
|
||||
deserialize_from::<_, _, _, E>(&mut reader, super::Infinite)
|
||||
let reader = ::de::read::SliceReader::new(bytes);
|
||||
let mut deserializer = Deserializer::<_, _, E>::new(reader, super::Infinite);
|
||||
serde::Deserialize::deserialize(&mut deserializer)
|
||||
}
|
|
@ -1,3 +1,5 @@
|
|||
#![deny(missing_docs)]
|
||||
|
||||
//! `bincode` is a crate for encoding and decoding using a tiny binary
|
||||
//! serialization strategy.
|
||||
//!
|
||||
|
@ -7,11 +9,11 @@
|
|||
//! and decoding from a `std::io::Buffer`.
|
||||
//!
|
||||
//! ## Modules
|
||||
//! There are two ways to encode and decode structs using `bincode`, either using `rustc_serialize`
|
||||
//! or the `serde` crate. `rustc_serialize` and `serde` are crates and and also the names of their
|
||||
//! corresponding modules inside of `bincode`. Both modules have exactly equivalant functions, and
|
||||
//! and the only difference is whether or not the library user wants to use `rustc_serialize` or
|
||||
//! `serde`.
|
||||
//! Until "default type parameters" lands, we have an extra module called `endian_choice`
|
||||
//! that duplicates all of the core bincode functionality but with the option to choose
|
||||
//! which endianness the integers are encoded using.
|
||||
//!
|
||||
//! The default endianness is little.
|
||||
//!
|
||||
//! ### Using Basic Functions
|
||||
//!
|
||||
|
@ -34,34 +36,36 @@
|
|||
#![crate_type = "rlib"]
|
||||
#![crate_type = "dylib"]
|
||||
|
||||
#![doc(html_logo_url = "./icon.png")]
|
||||
|
||||
extern crate byteorder;
|
||||
extern crate num_traits;
|
||||
extern crate serde as serde_crate;
|
||||
|
||||
pub mod refbox;
|
||||
mod serde;
|
||||
mod ser;
|
||||
mod de;
|
||||
pub mod internal;
|
||||
|
||||
pub mod endian_choice {
|
||||
pub use super::serde::{Deserializer, Serializer, serialize, serialize_into, deserialize, deserialize_from};
|
||||
pub mod read_types {
|
||||
//! The types that the deserializer uses for optimizations
|
||||
pub use ::de::read::{SliceReader, BincodeRead, IoReadReader};
|
||||
}
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
pub use serde::{ErrorKind, Error, Result, serialized_size, serialized_size_bounded};
|
||||
pub use internal::{ErrorKind, Error, Result, serialized_size, serialized_size_bounded};
|
||||
|
||||
pub type Deserializer<W, S> = serde::Deserializer<W, S, byteorder::LittleEndian>;
|
||||
pub type Serializer<W> = serde::Serializer<W, byteorder::LittleEndian>;
|
||||
/// A Deserializer that uses LittleEndian byteorder
|
||||
pub type Deserializer<W, S> = internal::Deserializer<W, S, byteorder::LittleEndian>;
|
||||
/// A Serializer that uses LittleEndian byteorder
|
||||
pub type Serializer<W> = internal::Serializer<W, byteorder::LittleEndian>;
|
||||
|
||||
/// Deserializes a slice of bytes into an object.
|
||||
///
|
||||
/// This method does not have a size-limit because if you already have the bytes
|
||||
/// in memory, then you don't gain anything by having a limiter.
|
||||
pub fn deserialize<T>(bytes: &[u8]) -> serde::Result<T>
|
||||
where T: serde_crate::Deserialize,
|
||||
pub fn deserialize<'a, T>(bytes: &'a [u8]) -> internal::Result<T>
|
||||
where T: serde_crate::de::Deserialize<'a>,
|
||||
{
|
||||
serde::deserialize::<_, byteorder::LittleEndian>(bytes)
|
||||
internal::deserialize::<_, byteorder::LittleEndian>(bytes)
|
||||
}
|
||||
|
||||
/// Deserializes an object directly from a `Buffer`ed Reader.
|
||||
|
@ -73,10 +77,10 @@ pub fn deserialize<T>(bytes: &[u8]) -> serde::Result<T>
|
|||
/// If this returns an `Error`, assume that the buffer that you passed
|
||||
/// in is in an invalid state, as the error could be returned during any point
|
||||
/// in the reading.
|
||||
pub fn deserialize_from<R: ?Sized, T, S>(reader: &mut R, size_limit: S) -> serde::Result<T>
|
||||
where R: Read, T: serde_crate::Deserialize, S: SizeLimit
|
||||
pub fn deserialize_from<R: ?Sized, T, S>(reader: &mut R, size_limit: S) -> internal::Result<T>
|
||||
where R: Read, T: serde_crate::de::DeserializeOwned, S: SizeLimit
|
||||
{
|
||||
serde::deserialize_from::<_, _, _, byteorder::LittleEndian>(reader, size_limit)
|
||||
internal::deserialize_from::<_, _, _, byteorder::LittleEndian>(reader, size_limit)
|
||||
}
|
||||
|
||||
/// Serializes an object directly into a `Writer`.
|
||||
|
@ -87,20 +91,20 @@ pub fn deserialize_from<R: ?Sized, T, S>(reader: &mut R, size_limit: S) -> serde
|
|||
/// If this returns an `Error` (other than SizeLimit), assume that the
|
||||
/// writer is in an invalid state, as writing could bail out in the middle of
|
||||
/// serializing.
|
||||
pub fn serialize_into<W: ?Sized, T: ?Sized, S>(writer: &mut W, value: &T, size_limit: S) -> serde::Result<()>
|
||||
pub fn serialize_into<W: ?Sized, T: ?Sized, S>(writer: &mut W, value: &T, size_limit: S) -> internal::Result<()>
|
||||
where W: Write, T: serde_crate::Serialize, S: SizeLimit
|
||||
{
|
||||
serde::serialize_into::<_, _, _, byteorder::LittleEndian>(writer, value, size_limit)
|
||||
internal::serialize_into::<_, _, _, byteorder::LittleEndian>(writer, value, size_limit)
|
||||
}
|
||||
|
||||
/// Serializes a serializable object into a `Vec` of bytes.
|
||||
///
|
||||
/// If the serialization would take more bytes than allowed by `size_limit`,
|
||||
/// an error is returned.
|
||||
pub fn serialize<T: ?Sized, S>(value: &T, size_limit: S) -> serde::Result<Vec<u8>>
|
||||
pub fn serialize<T: ?Sized, S>(value: &T, size_limit: S) -> internal::Result<Vec<u8>>
|
||||
where T: serde_crate::Serialize, S: SizeLimit
|
||||
{
|
||||
serde::serialize::<_, _, byteorder::LittleEndian>(value, size_limit)
|
||||
internal::serialize::<_, _, byteorder::LittleEndian>(value, size_limit)
|
||||
}
|
||||
|
||||
/// A limit on the amount of bytes that can be read or written.
|
||||
|
@ -122,13 +126,20 @@ pub fn serialize<T: ?Sized, S>(value: &T, size_limit: S) -> serde::Result<Vec<u8
|
|||
/// within that limit. This verification occurs before any bytes are written to
|
||||
/// the Writer, so recovering from an error is easy.
|
||||
pub trait SizeLimit {
|
||||
/// Tells the SizeLimit that a certain number of bytes has been
|
||||
/// read or written. Returns Err if the limit has been exceeded.
|
||||
fn add(&mut self, n: u64) -> Result<()>;
|
||||
/// Returns the hard limit (if one exists)
|
||||
fn limit(&self) -> Option<u64>;
|
||||
}
|
||||
|
||||
/// A SizeLimit that restricts serialized or deserialized messages from
|
||||
/// exceeding a certain byte length.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Bounded(pub u64);
|
||||
|
||||
/// A SizeLimit without a limit!
|
||||
/// Use this if you don't care about the size of encoded or decoded messages.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Infinite;
|
||||
|
||||
|
@ -142,6 +153,7 @@ impl SizeLimit for Bounded {
|
|||
Err(Box::new(ErrorKind::SizeLimit))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&self) -> Option<u64> { Some(self.0) }
|
||||
}
|
||||
|
@ -149,6 +161,7 @@ impl SizeLimit for Bounded {
|
|||
impl SizeLimit for Infinite {
|
||||
#[inline(always)]
|
||||
fn add(&mut self, _: u64) -> Result<()> { Ok (()) }
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&self) -> Option<u64> { None }
|
||||
}
|
||||
|
|
|
@ -1,363 +0,0 @@
|
|||
use std::boxed::Box;
|
||||
use std::ops::Deref;
|
||||
|
||||
use serde_crate as serde;
|
||||
|
||||
/// A struct for encoding nested reference types.
|
||||
///
|
||||
/// Encoding large objects by reference is really handy. For example,
|
||||
/// `encode(&large_hashmap, ...)` encodes the large structure without having to
|
||||
/// own the hashmap. However, it is impossible to serialize a reference if that
|
||||
/// reference is inside of a struct.
|
||||
///
|
||||
/// ```ignore rust
|
||||
/// // Not possible, rustc can not decode the reference.
|
||||
/// #[derive(RustcEncoding, RustcDecoding)]
|
||||
/// struct Message<'a> {
|
||||
/// big_map: &'a HashMap<u32, u32>,
|
||||
/// message_type: String,
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This is because on the decoding side, you can't create the Message struct
|
||||
/// because it needs to have a reference to a HashMap, which is impossible because
|
||||
/// during deserialization, all members need to be owned by the deserialized
|
||||
/// object.
|
||||
///
|
||||
/// This is where RefBox comes in. During serialization, it serializs a reference,
|
||||
/// but during deserialization, it puts that sub-object into a box!
|
||||
///
|
||||
/// ```ignore rust
|
||||
/// // This works!
|
||||
/// #[derive(RustcEncoding, RustcDecoding)]
|
||||
/// struct Message<'a> {
|
||||
/// big_map: RefBox<'a, HashMap<u32, u32>>,
|
||||
/// message_type: String
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Now we can write
|
||||
///
|
||||
/// ```ignore rust
|
||||
/// let my_map = HashMap::new();
|
||||
/// let my_msg = Message {
|
||||
/// big_map: RefBox::new(&my_map),
|
||||
/// message_type: "foo".to_string()
|
||||
/// };
|
||||
///
|
||||
/// let encoded = encode(&my_msg, ...).unwrap();
|
||||
/// let decoded: Message<'static> = decode(&encoded[]).unwrap();
|
||||
/// ```
|
||||
///
|
||||
/// Notice that we managed to encode and decode a struct with a nested reference
|
||||
/// and that the decoded message has the lifetime `'static` which shows us
|
||||
/// that the message owns everything inside it completely.
|
||||
///
|
||||
/// Please don't stick RefBox inside deep data structures. It is much better
|
||||
/// suited in the outermost layer of whatever it is that you are encoding.
|
||||
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
|
||||
pub struct RefBox<'a, T: 'a> {
|
||||
inner: RefBoxInner<'a, T, Box<T>>
|
||||
}
|
||||
|
||||
/// Like a RefBox, but encoding from a `str` and decoedes to a `String`.
|
||||
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
|
||||
pub struct StrBox<'a> {
|
||||
inner: RefBoxInner<'a, str, String>
|
||||
}
|
||||
|
||||
/// Like a RefBox, but encodes from a `[T]` and encodes to a `Vec<T>`.
|
||||
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
|
||||
pub struct SliceBox<'a, T: 'a> {
|
||||
inner: RefBoxInner<'a, [T], Vec<T>>
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
|
||||
enum RefBoxInner<'a, A: 'a + ?Sized, B> {
|
||||
Ref(&'a A),
|
||||
Box(B)
|
||||
}
|
||||
|
||||
impl<'a, T> Clone for RefBoxInner<'a, T, Box<T>> where T: Clone {
|
||||
fn clone(&self) -> RefBoxInner<'a, T, Box<T>> {
|
||||
match *self {
|
||||
RefBoxInner::Ref(reff) => RefBoxInner::Box(Box::new(reff.clone())),
|
||||
RefBoxInner::Box(ref boxed) => RefBoxInner::Box(boxed.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Clone for RefBoxInner<'a, str, String> {
|
||||
fn clone(&self) -> RefBoxInner<'a, str, String> {
|
||||
match *self {
|
||||
RefBoxInner::Ref(reff) => RefBoxInner::Box(String::from(reff)),
|
||||
RefBoxInner::Box(ref boxed) => RefBoxInner::Box(boxed.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Clone for RefBoxInner<'a, [T], Vec<T>> where T: Clone {
|
||||
fn clone(&self) -> RefBoxInner<'a, [T], Vec<T>> {
|
||||
match *self {
|
||||
RefBoxInner::Ref(reff) => RefBoxInner::Box(Vec::from(reff)),
|
||||
RefBoxInner::Box(ref boxed) => RefBoxInner::Box(boxed.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl <'a, T> RefBox<'a, T> {
|
||||
/// Creates a new RefBox that looks at a borrowed value.
|
||||
pub fn new(v: &'a T) -> RefBox<'a, T> {
|
||||
RefBox {
|
||||
inner: RefBoxInner::Ref(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl <T> RefBox<'static, T> {
|
||||
/// Takes the value out of this refbox.
|
||||
///
|
||||
/// Fails if this refbox was not created out of a deserialization.
|
||||
///
|
||||
/// Unless you are doing some really weird things with static references,
|
||||
/// this function will never fail.
|
||||
pub fn take(self) -> Box<T> {
|
||||
match self.inner {
|
||||
RefBoxInner::Box(b) => b,
|
||||
_ => unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to take the value out of this refbox.
|
||||
pub fn try_take(self) -> Result<Box<T>, RefBox<'static, T>> {
|
||||
match self.inner {
|
||||
RefBoxInner::Box(b) => Ok(b),
|
||||
o => Err(RefBox{ inner: o})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> serde::Serialize for RefBox<'a, T>
|
||||
where T: serde::Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: serde::Serializer
|
||||
{
|
||||
serde::Serialize::serialize(&self.inner, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: serde::Deserialize> serde::Deserialize for RefBox<'a, T> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: serde::Deserializer
|
||||
{
|
||||
let inner = try!(serde::Deserialize::deserialize(deserializer));
|
||||
Ok(RefBox{ inner: inner })
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> StrBox<'a> {
|
||||
/// Creates a new StrBox that looks at a borrowed value.
|
||||
pub fn new(s: &'a str) -> StrBox<'a> {
|
||||
StrBox {
|
||||
inner: RefBoxInner::Ref(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a String from a StrBox.
|
||||
pub fn into_string(self) -> String {
|
||||
match self.inner {
|
||||
RefBoxInner::Ref(s) => String::from(s),
|
||||
RefBoxInner::Box(s) => s
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert to an Owned `SliceBox`.
|
||||
pub fn to_owned(self) -> StrBox<'static> {
|
||||
match self.inner {
|
||||
RefBoxInner::Ref(s) => StrBox::boxed(String::from(s)),
|
||||
RefBoxInner::Box(s) => StrBox::boxed(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AsRef<str> for StrBox<'a> {
|
||||
fn as_ref(&self) -> &str {
|
||||
match self.inner {
|
||||
RefBoxInner::Ref(ref s) => s,
|
||||
RefBoxInner::Box(ref s) => s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StrBox<'static> {
|
||||
/// Creates a new StrBox made from an allocated String.
|
||||
pub fn boxed(s: String) -> StrBox<'static> {
|
||||
StrBox { inner: RefBoxInner::Box(s) }
|
||||
}
|
||||
|
||||
/// Takes the value out of this refbox.
|
||||
///
|
||||
/// Fails if this refbox was not created out of a deserialization.
|
||||
///
|
||||
/// Unless you are doing some really weird things with static references,
|
||||
/// this function will never fail.
|
||||
pub fn take(self) -> String {
|
||||
match self.inner {
|
||||
RefBoxInner::Box(b) => b,
|
||||
RefBoxInner::Ref(b) => String::from(b)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to take the value out of this refbox.
|
||||
pub fn try_take(self) -> Result<String, StrBox<'static>> {
|
||||
match self.inner {
|
||||
RefBoxInner::Box(b) => Ok(b),
|
||||
o => Err(StrBox{ inner: o})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<'a> serde::Serialize for StrBox<'a> {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: serde::Serializer
|
||||
{
|
||||
serde::Serialize::serialize(&self.inner, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::Deserialize for StrBox<'static> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: serde::Deserializer
|
||||
{
|
||||
let inner = try!(serde::Deserialize::deserialize(deserializer));
|
||||
Ok(StrBox{ inner: inner })
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// SliceBox
|
||||
//
|
||||
|
||||
impl <'a, T> SliceBox<'a, T> {
|
||||
/// Creates a new RefBox that looks at a borrowed value.
|
||||
pub fn new(v: &'a [T]) -> SliceBox<'a, T> {
|
||||
SliceBox {
|
||||
inner: RefBoxInner::Ref(v)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a `Vec<T>` from a `SliceBox`.
|
||||
pub fn into_vec(self) -> Vec<T> where T: Clone {
|
||||
match self.inner {
|
||||
RefBoxInner::Ref(s) => s.to_vec(),
|
||||
RefBoxInner::Box(s) => s
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert to an Owned `SliceBox`.
|
||||
pub fn to_owned(self) -> SliceBox<'static, T> where T: Clone {
|
||||
match self.inner {
|
||||
RefBoxInner::Ref(s) => SliceBox::boxed(s.to_vec()),
|
||||
RefBoxInner::Box(s) => SliceBox::boxed(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl <T> SliceBox<'static, T> {
|
||||
/// Creates a new SliceBox made from an allocated `Vec<T>`.
|
||||
pub fn boxed(s: Vec<T>) -> SliceBox<'static, T> {
|
||||
SliceBox { inner: RefBoxInner::Box(s) }
|
||||
}
|
||||
|
||||
/// Takes the value out of this refbox.
|
||||
///
|
||||
/// Fails if this refbox was not created out of a deserialization.
|
||||
///
|
||||
/// Unless you are doing some really weird things with static references,
|
||||
/// this function will never fail.
|
||||
pub fn take(self) -> Vec<T> {
|
||||
match self.inner {
|
||||
RefBoxInner::Box(b) => b,
|
||||
_ => unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to take the value out of this refbox.
|
||||
pub fn try_take(self) -> Result<Vec<T>, SliceBox<'static, T>> {
|
||||
match self.inner {
|
||||
RefBoxInner::Box(b) => Ok(b),
|
||||
o => Err(SliceBox{ inner: o})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<'a, T> serde::Serialize for SliceBox<'a, T>
|
||||
where T: serde::Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: serde::Serializer
|
||||
{
|
||||
serde::Serialize::serialize(&self.inner, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: serde::Deserialize> serde::Deserialize for SliceBox<'a, T> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: serde::Deserializer
|
||||
{
|
||||
let inner = try!(serde::Deserialize::deserialize(deserializer));
|
||||
Ok(SliceBox{ inner: inner })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<'a, A: ?Sized, B> serde::Serialize for RefBoxInner<'a, A, B>
|
||||
where A: serde::Serialize,
|
||||
B: serde::Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: serde::Serializer
|
||||
{
|
||||
match self {
|
||||
&RefBoxInner::Ref(ref r) => serde::Serialize::serialize(r, serializer),
|
||||
&RefBoxInner::Box(ref b) => serde::Serialize::serialize(b, serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<'a, A: ?Sized, B> serde::Deserialize for RefBoxInner<'a, A, B>
|
||||
where B: serde::Deserialize,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: serde::Deserializer
|
||||
{
|
||||
let deserialized = try!(serde::Deserialize::deserialize(deserializer));
|
||||
Ok(RefBoxInner::Box(deserialized))
|
||||
}
|
||||
}
|
||||
|
||||
impl <'a, T> Deref for RefBox<'a, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
match &self.inner {
|
||||
&RefBoxInner::Ref(ref t) => t,
|
||||
&RefBoxInner::Box(ref b) => b.deref()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl <'a, T> Deref for SliceBox<'a, T> {
|
||||
type Target = [T];
|
||||
|
||||
fn deref(&self) -> &[T] {
|
||||
match &self.inner {
|
||||
&RefBoxInner::Ref(ref t) => t,
|
||||
&RefBoxInner::Box(ref b) => b.deref()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -7,10 +7,13 @@ use serde_crate as serde;
|
|||
use byteorder::{WriteBytesExt, ByteOrder};
|
||||
|
||||
use super::{Result, Error, ErrorKind};
|
||||
use super::super::SizeLimit;
|
||||
use super::SizeLimit;
|
||||
|
||||
/// An Serializer that encodes values directly into a Writer.
|
||||
///
|
||||
/// The specified byte-order will impact the endianness that is
|
||||
/// used during the encoding.
|
||||
///
|
||||
/// This struct should not be used often.
|
||||
/// For most cases, prefer the `encode_into` function.
|
||||
pub struct Serializer<W, E: ByteOrder> {
|
||||
|
@ -19,20 +22,13 @@ pub struct Serializer<W, E: ByteOrder> {
|
|||
}
|
||||
|
||||
impl<W: Write, E: ByteOrder> Serializer<W, E> {
|
||||
/// Creates a new Serializer with the given `Write`r.
|
||||
pub fn new(w: W) -> Serializer<W, E> {
|
||||
Serializer {
|
||||
writer: w,
|
||||
_phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
fn add_enum_tag(&mut self, tag: usize) -> Result<()> {
|
||||
if tag > u32::MAX as usize {
|
||||
panic!("Variant tag doesn't fit in a u32")
|
||||
}
|
||||
|
||||
serde::Serializer::serialize_u32(self, tag as u32)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E> {
|
||||
|
@ -125,10 +121,6 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
Ok(Compound {ser: self})
|
||||
}
|
||||
|
||||
fn serialize_seq_fixed_size(self, _len: usize) -> Result<Self::SerializeSeq> {
|
||||
Ok(Compound {ser: self})
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
|
||||
Ok(Compound {ser: self})
|
||||
}
|
||||
|
@ -139,11 +131,11 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
|
||||
fn serialize_tuple_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeTupleVariant>
|
||||
{
|
||||
try!(self.add_enum_tag(variant_index));
|
||||
try!(self.serialize_u32(variant_index));
|
||||
Ok(Compound {ser: self})
|
||||
}
|
||||
|
||||
|
@ -159,11 +151,11 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
|
||||
fn serialize_struct_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeStructVariant>
|
||||
{
|
||||
try!(self.add_enum_tag(variant_index));
|
||||
try!(self.serialize_u32(variant_index));
|
||||
Ok(Compound {ser: self})
|
||||
}
|
||||
|
||||
|
@ -177,20 +169,20 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
|
||||
fn serialize_newtype_variant<T: ?Sized>(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize,
|
||||
{
|
||||
try!(self.add_enum_tag(variant_index));
|
||||
try!(self.serialize_u32(variant_index));
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str) -> Result<()> {
|
||||
self.add_enum_tag(variant_index)
|
||||
self.serialize_u32(variant_index)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -213,14 +205,6 @@ impl <S: SizeLimit> SizeChecker<S> {
|
|||
use std::mem::size_of_val;
|
||||
self.add_raw(size_of_val(&t) as u64)
|
||||
}
|
||||
|
||||
fn add_enum_tag(&mut self, tag: usize) -> Result<()> {
|
||||
if tag > u32::MAX as usize {
|
||||
panic!("Variant tag doesn't fit in a u32")
|
||||
}
|
||||
|
||||
self.add_value(tag as u32)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
||||
|
@ -314,10 +298,6 @@ impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
|||
Ok(SizeCompound {ser: self})
|
||||
}
|
||||
|
||||
fn serialize_seq_fixed_size(self, _len: usize) -> Result<Self::SerializeSeq> {
|
||||
Ok(SizeCompound {ser: self})
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
|
||||
Ok(SizeCompound {ser: self})
|
||||
}
|
||||
|
@ -328,11 +308,11 @@ impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
|||
|
||||
fn serialize_tuple_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeTupleVariant>
|
||||
{
|
||||
try!(self.add_enum_tag(variant_index));
|
||||
try!(self.add_value(variant_index));
|
||||
Ok(SizeCompound {ser: self})
|
||||
}
|
||||
|
||||
|
@ -350,11 +330,11 @@ impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
|||
|
||||
fn serialize_struct_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeStructVariant>
|
||||
{
|
||||
try!(self.add_enum_tag(variant_index));
|
||||
try!(self.add_value(variant_index));
|
||||
Ok(SizeCompound {ser: self})
|
||||
}
|
||||
|
||||
|
@ -364,18 +344,18 @@ impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
|||
|
||||
fn serialize_unit_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str) -> Result<()> {
|
||||
self.add_enum_tag(variant_index)
|
||||
self.add_value(variant_index)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<V: serde::Serialize + ?Sized>(self,
|
||||
_name: &'static str,
|
||||
variant_index: usize,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
value: &V) -> Result<()>
|
||||
{
|
||||
try!(self.add_enum_tag(variant_index));
|
||||
try!(self.add_value(variant_index));
|
||||
value.serialize(self)
|
||||
}
|
||||
}
|
||||
|
@ -392,8 +372,8 @@ impl<'a, W, E> serde::ser::SerializeSeq for Compound<'a, W, E>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -411,8 +391,8 @@ impl<'a, W, E> serde::ser::SerializeTuple for Compound<'a, W, E>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -430,8 +410,8 @@ impl<'a, W, E> serde::ser::SerializeTupleStruct for Compound<'a, W, E>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -449,8 +429,8 @@ impl<'a, W, E> serde::ser::SerializeTupleVariant for Compound<'a, W, E>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -468,15 +448,15 @@ impl<'a, W, E> serde::ser::SerializeMap for Compound<'a, W, E>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
|
||||
where K: serde::ser::Serialize
|
||||
fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
|
||||
where K: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
|
||||
where V: serde::ser::Serialize
|
||||
fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
|
||||
where V: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -494,8 +474,8 @@ impl<'a, W, E> serde::ser::SerializeStruct for Compound<'a, W, E>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -513,8 +493,8 @@ impl<'a, W, E> serde::ser::SerializeStructVariant for Compound<'a, W, E>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -536,8 +516,8 @@ impl<'a, S: SizeLimit> serde::ser::SerializeSeq for SizeCompound<'a, S>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -554,8 +534,8 @@ impl<'a, S: SizeLimit> serde::ser::SerializeTuple for SizeCompound<'a, S>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -572,8 +552,8 @@ impl<'a, S: SizeLimit> serde::ser::SerializeTupleStruct for SizeCompound<'a, S>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -590,8 +570,8 @@ impl<'a, S: SizeLimit> serde::ser::SerializeTupleVariant for SizeCompound<'a, S>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -608,15 +588,15 @@ impl<'a, S: SizeLimit + 'a> serde::ser::SerializeMap for SizeCompound<'a, S>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
|
||||
where K: serde::ser::Serialize
|
||||
fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
|
||||
where K: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
|
||||
where V: serde::ser::Serialize
|
||||
fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
|
||||
where V: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -633,8 +613,8 @@ impl<'a, S: SizeLimit> serde::ser::SerializeStruct for SizeCompound<'a, S>
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -651,8 +631,8 @@ impl<'a, S: SizeLimit> serde::ser::SerializeStructVariant for SizeCompound<'a, S
|
|||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
|
@ -3,57 +3,42 @@ extern crate serde_derive;
|
|||
|
||||
extern crate bincode;
|
||||
extern crate serde;
|
||||
extern crate serde_bytes;
|
||||
extern crate byteorder;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Deref;
|
||||
|
||||
use bincode::refbox::{RefBox, StrBox, SliceBox};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use bincode::{Infinite, Bounded};
|
||||
use bincode::{serialized_size, ErrorKind, Result};
|
||||
use bincode::endian_choice::{serialize, deserialize};
|
||||
use bincode::internal::{serialize, deserialize, deserialize_from};
|
||||
|
||||
use bincode::serialize as serialize_little;
|
||||
use bincode::deserialize as deserialize_little;
|
||||
use bincode::deserialize_from as deserialize_from_little;
|
||||
|
||||
fn the_same<V>(element: V)
|
||||
where V: serde::Serialize+serde::Deserialize+PartialEq+Debug+'static
|
||||
where V: serde::Serialize+serde::de::DeserializeOwned+PartialEq+Debug+'static
|
||||
{
|
||||
// Make sure that the bahavior isize correct when wrapping with a RefBox.
|
||||
fn ref_box_correct<V>(v: &V) -> bool
|
||||
where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
|
||||
{
|
||||
let rf = RefBox::new(v);
|
||||
let encoded = serialize_little(&rf, Infinite).unwrap();
|
||||
let decoded: RefBox<'static, V> = deserialize_little(&encoded[..]).unwrap();
|
||||
|
||||
decoded.take().deref() == v
|
||||
}
|
||||
|
||||
let size = serialized_size(&element);
|
||||
|
||||
{
|
||||
let encoded = serialize_little(&element, Infinite);
|
||||
let encoded = encoded.unwrap();
|
||||
let decoded = deserialize_little(&encoded[..]);
|
||||
let decoded = decoded.unwrap();
|
||||
let encoded = serialize_little(&element, Infinite).unwrap();
|
||||
let decoded = deserialize_little(&encoded[..]).unwrap();
|
||||
|
||||
assert_eq!(element, decoded);
|
||||
assert_eq!(size, encoded.len() as u64);
|
||||
assert!(ref_box_correct(&element));
|
||||
}
|
||||
|
||||
{
|
||||
let encoded = serialize::<_, _, byteorder::BigEndian>(&element, Infinite);
|
||||
let encoded = encoded.unwrap();
|
||||
let decoded = deserialize::<_, byteorder::BigEndian>(&encoded[..]);
|
||||
let decoded = decoded.unwrap();
|
||||
let encoded = serialize::<_, _, byteorder::BigEndian>(&element, Infinite).unwrap();
|
||||
let decoded = deserialize::<_, byteorder::BigEndian>(&encoded[..]).unwrap();
|
||||
let decoded_reader = deserialize_from::<_, _, _, byteorder::BigEndian>(&mut &encoded[..], Infinite).unwrap();
|
||||
|
||||
assert_eq!(element, decoded);
|
||||
assert_eq!(element, decoded_reader);
|
||||
assert_eq!(size, encoded.len() as u64);
|
||||
assert!(ref_box_correct(&element));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -304,7 +289,7 @@ fn encode_box() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn test_refbox_serialize() {
|
||||
fn test_cow_serialize() {
|
||||
let large_object = vec![1u32,2,3,4,5,6];
|
||||
let mut large_map = HashMap::new();
|
||||
large_map.insert(1, 2);
|
||||
|
@ -312,28 +297,28 @@ fn test_refbox_serialize() {
|
|||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
enum Message<'a> {
|
||||
M1(RefBox<'a, Vec<u32>>),
|
||||
M2(RefBox<'a, HashMap<u32, u32>>)
|
||||
M1(Cow<'a, Vec<u32>>),
|
||||
M2(Cow<'a, HashMap<u32, u32>>)
|
||||
}
|
||||
|
||||
// Test 1
|
||||
{
|
||||
let serialized = serialize_little(&Message::M1(RefBox::new(&large_object)), Infinite).unwrap();
|
||||
let serialized = serialize_little(&Message::M1(Cow::Borrowed(&large_object)), Infinite).unwrap();
|
||||
let deserialized: Message<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
|
||||
match deserialized {
|
||||
Message::M1(b) => assert!(b.take().deref() == &large_object),
|
||||
Message::M1(b) => assert!(&b.into_owned() == &large_object),
|
||||
_ => assert!(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Test 2
|
||||
{
|
||||
let serialized = serialize_little(&Message::M2(RefBox::new(&large_map)), Infinite).unwrap();
|
||||
let serialized = serialize_little(&Message::M2(Cow::Borrowed(&large_map)), Infinite).unwrap();
|
||||
let deserialized: Message<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
|
||||
match deserialized {
|
||||
Message::M2(b) => assert!(b.take().deref() == &large_map),
|
||||
Message::M2(b) => assert!(&b.into_owned() == &large_map),
|
||||
_ => assert!(false)
|
||||
}
|
||||
}
|
||||
|
@ -342,22 +327,23 @@ fn test_refbox_serialize() {
|
|||
#[test]
|
||||
fn test_strbox_serialize() {
|
||||
let strx: &'static str = "hello world";
|
||||
let serialized = serialize_little(&StrBox::new(strx), Infinite).unwrap();
|
||||
let deserialized: StrBox<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
let stringx: String = deserialized.take();
|
||||
let serialized = serialize_little(&Cow::Borrowed(strx), Infinite).unwrap();
|
||||
let deserialized: Cow<'static, String> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
let stringx: String = deserialized.into_owned();
|
||||
assert!(strx == &stringx[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slicebox_serialize() {
|
||||
let slice = [1u32, 2, 3 ,4, 5];
|
||||
let serialized = serialize_little(&SliceBox::new(&slice), Infinite).unwrap();
|
||||
let deserialized: SliceBox<'static, u32> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
let serialized = serialize_little(&Cow::Borrowed(&slice[..]), Infinite).unwrap();
|
||||
println!("{:?}", serialized);
|
||||
let deserialized: Cow<'static, Vec<u32>> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
{
|
||||
let sb: &[u32] = &deserialized;
|
||||
assert!(slice == sb);
|
||||
}
|
||||
let vecx: Vec<u32> = deserialized.take();
|
||||
let vecx: Vec<u32> = deserialized.into_owned();
|
||||
assert!(slice == &vecx[..]);
|
||||
}
|
||||
|
||||
|
@ -366,18 +352,18 @@ fn test_multi_strings_serialize() {
|
|||
assert!(serialize_little(&("foo", "bar", "baz"), Infinite).is_ok());
|
||||
}
|
||||
|
||||
/*
|
||||
#[test]
|
||||
fn test_oom_protection() {
|
||||
use std::io::Cursor;
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct FakeVec {
|
||||
len: u64,
|
||||
byte: u8
|
||||
}
|
||||
let x = bincode::rustc_serialize::encode(&FakeVec { len: 0xffffffffffffffffu64, byte: 1 }, bincode::SizeLimit::Bounded(10)).unwrap();
|
||||
let y : Result<Vec<u8>, _> = bincode::rustc_serialize::decode_from(&mut Cursor::new(&x[..]), bincode::SizeLimit::Bounded(10));
|
||||
let x = serialize_little(&FakeVec { len: 0xffffffffffffffffu64, byte: 1 }, Bounded(10)).unwrap();
|
||||
let y: Result<Vec<u8>> = deserialize_from_little(&mut Cursor::new(&x[..]), Bounded(10));
|
||||
assert!(y.is_err());
|
||||
}*/
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_buf() {
|
||||
|
@ -390,12 +376,18 @@ fn path_buf() {
|
|||
|
||||
#[test]
|
||||
fn bytes() {
|
||||
use serde::bytes::Bytes;
|
||||
use serde_bytes::Bytes;
|
||||
|
||||
let data = b"abc\0123";
|
||||
let s = serialize_little(&data, Infinite).unwrap();
|
||||
let s = serialize_little(&data[..], Infinite).unwrap();
|
||||
let s2 = serialize_little(&Bytes::new(data), Infinite).unwrap();
|
||||
assert_eq!(s[..], s2[8..]);
|
||||
assert_eq!(s[..], s2[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_bytes() {
|
||||
use serde_bytes::ByteBuf;
|
||||
the_same(ByteBuf::from(vec![1,2,3,4,5]));
|
||||
}
|
||||
|
||||
|
||||
|
@ -406,3 +398,22 @@ fn endian_difference() {
|
|||
let big = serialize::<_, _, byteorder::BigEndian>(&x, Infinite).unwrap();
|
||||
assert_ne!(little, big);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_copy_parse() {
|
||||
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
|
||||
struct Foo<'a> {
|
||||
borrowed_str: &'a str,
|
||||
borrowed_bytes: &'a [u8],
|
||||
}
|
||||
|
||||
let f = Foo {
|
||||
borrowed_str: "hi",
|
||||
borrowed_bytes: &[0, 1, 2, 3],
|
||||
};
|
||||
{
|
||||
let encoded = serialize_little(&f, Infinite).unwrap();
|
||||
let out: Foo = deserialize_little(&encoded[..]).unwrap();
|
||||
assert_eq!(out, f);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"b71b9a6f84b9263b2b89be6ec90dff5920ee68cf9e5768d73ed71957de2d0670","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"21861781fe43e924d0ae78c0f74dbd8bae7e73818a3ef9692f107ca52cdb04cf","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"4a45abeb1e684e30bb361dfa7db59189423348e18d310cbae694b7c8c57cd86a","src/base.rs":"3f3d5d69bd79b146cc3c0402de6260f7531c04e6a44b080f4ec7c8cedebd1337","src/color_space.rs":"7d447e774e85cc33de574637a93c9a8550b681c8d4b94e99f95261ea9740e288","src/context.rs":"7c764ffde2e0ebaecd30ced31ece29f82ddea2f3c8145f4ea59882df38fec0d2","src/data_provider.rs":"899a5762ea472b828e1726e1cefc8d2dbd237772ce171cf6b31a79f144ce8df1","src/display.rs":"906cbcb13f8214308a6afcfb3abdd04e409f48ce62673574d40087486f38b36d","src/event.rs":"7f25a98207f200f10717c2765179ece8ba02600767b7c194c49854e7bfaa470c","src/event_source.rs":"6d1c1378dab8988c46dd3bf20639913716418980b9b490a37a0d5120c60ad580","src/font.rs":"f14340aee0979f6362da671cccf81c49f6e345cd645f07fc75e7074d06e99c70","src/geometry.rs":"9f59dcf55f393a3fa001afe8aea68a85a3c9a06239aeafe6da5d2823ed37b271","src/lib.rs":"efed3638b05e6a806a6fa0c544893afeec931f6c6889bd4a69d8fd2f9838967f","src/private.rs":"87c96ed2002bd567bf02535b4c6e8e3f22827afb2dd92ee17d91cfb45bc6072c"},"package":"ead017dcf77f503dc991f6b52de6084eeea60a94b0a652baa9bf88654a28e83f"}
|
||||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"b71b9a6f84b9263b2b89be6ec90dff5920ee68cf9e5768d73ed71957de2d0670","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"5b53cadf8fadf693d9d96d43d135a9fe0f3a3eea0742971e4cba9400fb4d6981","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"4a45abeb1e684e30bb361dfa7db59189423348e18d310cbae694b7c8c57cd86a","src/base.rs":"3f3d5d69bd79b146cc3c0402de6260f7531c04e6a44b080f4ec7c8cedebd1337","src/color_space.rs":"7d447e774e85cc33de574637a93c9a8550b681c8d4b94e99f95261ea9740e288","src/context.rs":"6ca07886ad2c3c488f440b95cbffc4cefce212625799e9f1bb9f83f2b9985538","src/data_provider.rs":"b20cbff65a960409abfc1e3eb8145db892c6f9f0294805e5425a4186b88d32c3","src/display.rs":"b63f3a6d5971ad216edf8e961dcd201b84b4028d6bc3eebcfc6371300d841629","src/event.rs":"8b188320702836bd1d6fe18db0deb4415755c5a10e2c44afa691fec02f1e3ce2","src/event_source.rs":"6d1c1378dab8988c46dd3bf20639913716418980b9b490a37a0d5120c60ad580","src/font.rs":"a763205dbab72498a60e62ca7e63fc23bcb05cce0bfe5eacb1189a5783f18314","src/geometry.rs":"d452bbfe443d26b80a54ae8dc9eccb68fd03e35f846eba37618ee0c295af122d","src/image.rs":"08a61e703577bcebe5102e3382a777b319b0e9b063dfefb00982094e56525011","src/lib.rs":"62efb6fccbc8a26ea855cb509e649d83b92573941ce7ef4b9a90b2be926a0b91","src/private.rs":"87c96ed2002bd567bf02535b4c6e8e3f22827afb2dd92ee17d91cfb45bc6072c"},"package":"a9f841e9637adec70838c537cae52cb4c751cc6514ad05669b51d107c2021c79"}
|
|
@ -3,7 +3,7 @@ name = "core-graphics"
|
|||
description = "Bindings to Core Graphics for OS X"
|
||||
homepage = "https://github.com/servo/core-graphics-rs"
|
||||
repository = "https://github.com/servo/core-graphics-rs"
|
||||
version = "0.7.0"
|
||||
version = "0.8.1"
|
||||
authors = ["The Servo Project Developers"]
|
||||
license = "MIT / Apache-2.0"
|
||||
|
||||
|
@ -14,4 +14,4 @@ elcapitan = []
|
|||
[dependencies]
|
||||
libc = "0.2"
|
||||
core-foundation = "0.3"
|
||||
serde = "0.9"
|
||||
bitflags = "0.8"
|
||||
|
|
|
@ -10,11 +10,12 @@
|
|||
use base::CGFloat;
|
||||
use color_space::{CGColorSpace, CGColorSpaceRef};
|
||||
use core_foundation::base::{CFRelease, CFRetain, CFTypeID, CFTypeRef, TCFType};
|
||||
use libc::{c_void, size_t};
|
||||
use libc::{c_void, c_int, size_t};
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
use geometry::CGRect;
|
||||
use image::{CGImage, CGImageRef};
|
||||
|
||||
#[repr(C)]
|
||||
pub enum CGTextDrawingMode {
|
||||
|
@ -87,7 +88,8 @@ impl TCFType<CGContextRef> for CGContext {
|
|||
}
|
||||
|
||||
impl CGContext {
|
||||
pub fn create_bitmap_context(width: size_t,
|
||||
pub fn create_bitmap_context(data: Option<*mut c_void>,
|
||||
width: size_t,
|
||||
height: size_t,
|
||||
bits_per_component: size_t,
|
||||
bytes_per_row: size_t,
|
||||
|
@ -95,7 +97,7 @@ impl CGContext {
|
|||
bitmap_info: u32)
|
||||
-> CGContext {
|
||||
unsafe {
|
||||
let result = CGBitmapContextCreate(ptr::null_mut(),
|
||||
let result = CGBitmapContextCreate(data.unwrap_or(ptr::null_mut()),
|
||||
width,
|
||||
height,
|
||||
bits_per_component,
|
||||
|
@ -144,6 +146,12 @@ impl CGContext {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn set_font_smoothing_style(&self, style: i32) {
|
||||
unsafe {
|
||||
CGContextSetFontSmoothingStyle(self.as_concrete_TypeRef(), style as _);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_should_smooth_fonts(&self, should_smooth_fonts: bool) {
|
||||
unsafe {
|
||||
CGContextSetShouldSmoothFonts(self.as_concrete_TypeRef(), should_smooth_fonts)
|
||||
|
@ -197,6 +205,21 @@ impl CGContext {
|
|||
CGContextFillRect(self.as_concrete_TypeRef(), rect)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_image(&self, rect: CGRect, image: &CGImage) {
|
||||
unsafe {
|
||||
CGContextDrawImage(self.as_concrete_TypeRef(), rect, image.as_concrete_TypeRef());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_image(&self) -> Option<CGImage> {
|
||||
let image = unsafe { CGBitmapContextCreateImage(self.as_concrete_TypeRef()) };
|
||||
if image != ptr::null() {
|
||||
Some(unsafe { CGImage::wrap_under_create_rule(image) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
|
@ -213,9 +236,11 @@ extern {
|
|||
fn CGBitmapContextGetWidth(context: CGContextRef) -> size_t;
|
||||
fn CGBitmapContextGetHeight(context: CGContextRef) -> size_t;
|
||||
fn CGBitmapContextGetBytesPerRow(context: CGContextRef) -> size_t;
|
||||
fn CGBitmapContextCreateImage(context: CGContextRef) -> CGImageRef;
|
||||
fn CGContextGetTypeID() -> CFTypeID;
|
||||
fn CGContextSetAllowsFontSmoothing(c: CGContextRef, allowsFontSmoothing: bool);
|
||||
fn CGContextSetShouldSmoothFonts(c: CGContextRef, shouldSmoothFonts: bool);
|
||||
fn CGContextSetFontSmoothingStyle(c: CGContextRef, style: c_int);
|
||||
fn CGContextSetAllowsAntialiasing(c: CGContextRef, allowsAntialiasing: bool);
|
||||
fn CGContextSetShouldAntialias(c: CGContextRef, shouldAntialias: bool);
|
||||
fn CGContextSetAllowsFontSubpixelQuantization(c: CGContextRef,
|
||||
|
@ -234,5 +259,6 @@ extern {
|
|||
alpha: CGFloat);
|
||||
fn CGContextFillRect(context: CGContextRef,
|
||||
rect: CGRect);
|
||||
fn CGContextDrawImage(c: CGContextRef, rect: CGRect, image: CGImageRef);
|
||||
}
|
||||
|
||||
|
|
|
@ -8,22 +8,23 @@
|
|||
// except according to those terms.
|
||||
|
||||
use core_foundation::base::{CFRelease, CFRetain, CFTypeID, CFTypeRef, TCFType};
|
||||
use core_foundation::data::{CFData, CFDataRef};
|
||||
|
||||
use libc::{c_void, size_t};
|
||||
use libc::{c_void, size_t, off_t};
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
|
||||
pub type CGDataProviderGetBytesCallback = *const u8;
|
||||
pub type CGDataProviderReleaseInfoCallback = *const u8;
|
||||
pub type CGDataProviderRewindCallback = *const u8;
|
||||
pub type CGDataProviderSkipBytesCallback = *const u8;
|
||||
pub type CGDataProviderSkipForwardCallback = *const u8;
|
||||
pub type CGDataProviderGetBytesCallback = Option<unsafe extern fn (*mut c_void, *mut c_void, size_t) -> size_t>;
|
||||
pub type CGDataProviderReleaseInfoCallback = Option<unsafe extern fn (*mut c_void)>;
|
||||
pub type CGDataProviderRewindCallback = Option<unsafe extern fn (*mut c_void)>;
|
||||
pub type CGDataProviderSkipBytesCallback = Option<unsafe extern fn (*mut c_void, size_t)>;
|
||||
pub type CGDataProviderSkipForwardCallback = Option<unsafe extern fn (*mut c_void, off_t) -> off_t>;
|
||||
|
||||
pub type CGDataProviderGetBytePointerCallback = *const u8;
|
||||
pub type CGDataProviderGetBytesAtOffsetCallback = *const u8;
|
||||
pub type CGDataProviderReleaseBytePointerCallback = *const u8;
|
||||
pub type CGDataProviderReleaseDataCallback = *const u8;
|
||||
pub type CGDataProviderGetBytesAtPositionCallback = *const u8;
|
||||
pub type CGDataProviderGetBytePointerCallback = Option<unsafe extern fn (*mut c_void) -> *mut c_void>;
|
||||
pub type CGDataProviderGetBytesAtOffsetCallback = Option<unsafe extern fn (*mut c_void, *mut c_void, size_t, size_t)>;
|
||||
pub type CGDataProviderReleaseBytePointerCallback = Option<unsafe extern fn (*mut c_void, *const c_void)>;
|
||||
pub type CGDataProviderReleaseDataCallback = Option<unsafe extern fn (*mut c_void, *const c_void, size_t)>;
|
||||
pub type CGDataProviderGetBytesAtPositionCallback = Option<unsafe extern fn (*mut c_void, *mut c_void, off_t, size_t)>;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct __CGDataProvider;
|
||||
|
@ -82,15 +83,20 @@ impl CGDataProvider {
|
|||
let result = CGDataProviderCreateWithData(ptr::null_mut(),
|
||||
buffer.as_ptr() as *const c_void,
|
||||
buffer.len() as size_t,
|
||||
ptr::null());
|
||||
None);
|
||||
TCFType::wrap_under_create_rule(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a copy of the data from the underlying `CFDataProviderRef`.
|
||||
pub fn copy_data(&self) -> CFData {
|
||||
unsafe { CFData::wrap_under_create_rule(CGDataProviderCopyData(self.obj)) }
|
||||
}
|
||||
}
|
||||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
extern {
|
||||
//fn CGDataProviderCopyData
|
||||
fn CGDataProviderCopyData(provider: CGDataProviderRef) -> CFDataRef;
|
||||
//fn CGDataProviderCreateDirect
|
||||
//fn CGDataProviderCreateSequential
|
||||
//fn CGDataProviderCreateWithCFData
|
||||
|
|
|
@ -15,6 +15,8 @@ use libc;
|
|||
pub use base::{CGError, boolean_t};
|
||||
pub use geometry::{CGRect, CGPoint, CGSize};
|
||||
|
||||
use image::CGImageRef;
|
||||
|
||||
pub type CGDirectDisplayID = libc::uint32_t;
|
||||
pub type CGWindowID = libc::uint32_t;
|
||||
|
||||
|
@ -30,6 +32,14 @@ pub const kCGWindowListOptionOnScreenBelowWindow: CGWindowListOption = 1 << 2;
|
|||
pub const kCGWindowListOptionIncludingWindow: CGWindowListOption = 1 << 3;
|
||||
pub const kCGWindowListExcludeDesktopElements: CGWindowListOption = 1 << 4;
|
||||
|
||||
pub type CGWindowImageOption = libc::uint32_t;
|
||||
|
||||
pub const kCGWindowImageDefault: CGWindowImageOption = 0;
|
||||
pub const kCGWindowImageBoundsIgnoreFraming: CGWindowImageOption = 1 << 0;
|
||||
pub const kCGWindowImageShouldBeOpaque: CGWindowImageOption = 1 << 1;
|
||||
pub const kCGWindowImageOnlyShadows: CGWindowImageOption = 1 << 2;
|
||||
pub const kCGWindowImageBestResolution: CGWindowImageOption = 1 << 3;
|
||||
pub const kCGWindowImageNominalResolution: CGWindowImageOption = 1 << 4;
|
||||
|
||||
pub use core_foundation::dictionary::{ CFDictionary, CFDictionaryRef, CFDictionaryGetValueIfPresent };
|
||||
pub use core_foundation::array::{ CFArray, CFArrayRef };
|
||||
|
@ -38,6 +48,9 @@ pub use core_foundation::base::{ CFIndex, CFRelease, CFTypeRef };
|
|||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
extern {
|
||||
pub static CGRectNull: CGRect;
|
||||
pub static CGRectInfinite: CGRect;
|
||||
|
||||
pub fn CGMainDisplayID() -> CGDirectDisplayID;
|
||||
pub fn CGDisplayIsActive(display: CGDirectDisplayID) -> boolean_t;
|
||||
pub fn CGDisplayIsAlwaysInMirrorSet(display: CGDirectDisplayID) -> boolean_t;
|
||||
|
@ -73,5 +86,9 @@ extern {
|
|||
|
||||
// Window Services Reference
|
||||
pub fn CGWindowListCopyWindowInfo(option: CGWindowListOption, relativeToWindow: CGWindowID ) -> CFArrayRef;
|
||||
pub fn CGWindowListCreateImage(screenBounds: CGRect,
|
||||
listOptions: CGWindowListOption,
|
||||
windowId: CGWindowID,
|
||||
imageOptions: CGWindowImageOption) -> CGImageRef;
|
||||
|
||||
}
|
||||
|
|
|
@ -11,25 +11,27 @@ pub type CGKeyCode = libc::uint16_t;
|
|||
/// Flags for events
|
||||
///
|
||||
/// [Ref](http://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h)
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum CGEventFlags {
|
||||
// Device-independent modifier key bits.
|
||||
AlphaShift = 0x00010000,
|
||||
Shift = 0x00020000,
|
||||
Control = 0x00040000,
|
||||
Alternate = 0x00080000,
|
||||
Command = 0x00100000,
|
||||
bitflags! {
|
||||
pub flags CGEventFlags: u64 {
|
||||
const CGEventFlagNull = 0,
|
||||
|
||||
// Special key identifiers.
|
||||
Help = 0x00400000,
|
||||
SecondaryFn = 0x00800000,
|
||||
// Device-independent modifier key bits.
|
||||
const CGEventFlagAlphaShift = 0x00010000,
|
||||
const CGEventFlagShift = 0x00020000,
|
||||
const CGEventFlagControl = 0x00040000,
|
||||
const CGEventFlagAlternate = 0x00080000,
|
||||
const CGEventFlagCommand = 0x00100000,
|
||||
|
||||
// Identifies key events from numeric keypad area on extended keyboards.
|
||||
NumericPad = 0x00200000,
|
||||
// Special key identifiers.
|
||||
const CGEventFlagHelp = 0x00400000,
|
||||
const CGEventFlagSecondaryFn = 0x00800000,
|
||||
|
||||
// Indicates if mouse/pen movement events are not being coalesced
|
||||
NonCoalesced = 0x00000100,
|
||||
// Identifies key events from numeric keypad area on extended keyboards.
|
||||
const CGEventFlagNumericPad = 0x00200000,
|
||||
|
||||
// Indicates if mouse/pen movement events are not being coalesced
|
||||
const CGEventFlagNonCoalesced = 0x00000100,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constants that specify the different types of input events.
|
||||
|
@ -38,29 +40,29 @@ pub enum CGEventFlags {
|
|||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum CGEventType {
|
||||
Null = 1 << 0,
|
||||
Null = 0,
|
||||
|
||||
// Mouse events.
|
||||
LeftMouseDown = 1 << 1,
|
||||
LeftMouseUp = 1 << 2,
|
||||
RightMouseDown = 1 << 3,
|
||||
RightMouseUp = 1 << 4,
|
||||
MouseMoved = 1 << 5,
|
||||
LeftMouseDragged = 1 << 6,
|
||||
RightMouseDragged = 1 << 7,
|
||||
LeftMouseDown = 1,
|
||||
LeftMouseUp = 2,
|
||||
RightMouseDown = 3,
|
||||
RightMouseUp = 4,
|
||||
MouseMoved = 5,
|
||||
LeftMouseDragged = 6,
|
||||
RightMouseDragged = 7,
|
||||
|
||||
// Keyboard events.
|
||||
KeyDown = 1 << 10,
|
||||
KeyUp = 1 << 11,
|
||||
FlagsChanged = 1 << 12,
|
||||
KeyDown = 10,
|
||||
KeyUp = 11,
|
||||
FlagsChanged = 12,
|
||||
|
||||
// Specialized control devices.
|
||||
ScrollWheel = 1 << 22,
|
||||
TabletPointer = 1 << 23,
|
||||
TabletProximity = 1 << 24,
|
||||
OtherMouseDown = 1 << 25,
|
||||
OtherMouseUp = 1 << 26,
|
||||
OtherMouseDragged = 1 << 27,
|
||||
ScrollWheel = 22,
|
||||
TabletPointer = 23,
|
||||
TabletProximity = 24,
|
||||
OtherMouseDown = 25,
|
||||
OtherMouseUp = 26,
|
||||
OtherMouseDragged = 27,
|
||||
|
||||
// Out of band event types. These are delivered to the event tap callback
|
||||
// to notify it of unusual conditions that disable the event tap.
|
||||
|
@ -222,6 +224,30 @@ impl CGEvent {
|
|||
CGEventGetFlags(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_type(&self, event_type: CGEventType) {
|
||||
unsafe {
|
||||
CGEventSetType(self.as_concrete_TypeRef(), event_type);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_type(&self) -> CGEventType {
|
||||
unsafe {
|
||||
CGEventGetType(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_string_from_utf16_unchecked(&self, buf: &[u16]) {
|
||||
let buflen = buf.len() as libc::c_ulong;
|
||||
unsafe {
|
||||
CGEventKeyboardSetUnicodeString(self.as_concrete_TypeRef(), buflen, buf.as_ptr());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_string(&self, string: &str) {
|
||||
let buf: Vec<u16> = string.encode_utf16().collect();
|
||||
self.set_string_from_utf16_unchecked(&buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
|
@ -282,4 +308,22 @@ extern {
|
|||
/// Return the location of an event in global display coordinates.
|
||||
/// CGPointZero is returned if event is not a valid CGEventRef.
|
||||
fn CGEventGetLocation(event: CGEventRef) -> CGPoint;
|
||||
|
||||
/// Set the event type of an event.
|
||||
fn CGEventSetType(event: CGEventRef, eventType: CGEventType);
|
||||
|
||||
/// Return the event type of an event (left mouse down, for example).
|
||||
fn CGEventGetType(event: CGEventRef) -> CGEventType;
|
||||
|
||||
/// Set the Unicode string associated with a keyboard event.
|
||||
///
|
||||
/// By default, the system translates the virtual key code in a keyboard
|
||||
/// event into a Unicode string based on the keyboard ID in the event
|
||||
/// source. This function allows you to manually override this string.
|
||||
/// Note that application frameworks may ignore the Unicode string in a
|
||||
/// keyboard event and do their own translation based on the virtual
|
||||
/// keycode and perceived event state.
|
||||
fn CGEventKeyboardSetUnicodeString(event: CGEventRef,
|
||||
length: libc::c_ulong,
|
||||
string: *const u16);
|
||||
}
|
||||
|
|
|
@ -12,8 +12,6 @@ use core_foundation::string::{CFString, CFStringRef};
|
|||
use data_provider::{CGDataProvider, CGDataProviderRef};
|
||||
|
||||
use libc;
|
||||
use serde::de::{self, Deserialize, Deserializer};
|
||||
use serde::ser::{Serialize, Serializer};
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
|
||||
|
@ -31,22 +29,6 @@ pub struct CGFont {
|
|||
unsafe impl Send for CGFont {}
|
||||
unsafe impl Sync for CGFont {}
|
||||
|
||||
impl Serialize for CGFont {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
|
||||
let postscript_name = self.postscript_name().to_string();
|
||||
postscript_name.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserialize for CGFont {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer {
|
||||
let postscript_name: String = try!(Deserialize::deserialize(deserializer));
|
||||
CGFont::from_name(&CFString::new(&*postscript_name)).map_err(|_| {
|
||||
de::Error::custom("Couldn't find a font with that PostScript name!")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for CGFont {
|
||||
#[inline]
|
||||
fn clone(&self) -> CGFont {
|
||||
|
|
|
@ -8,6 +8,8 @@
|
|||
// except according to those terms.
|
||||
|
||||
use base::CGFloat;
|
||||
use core_foundation::base::TCFType;
|
||||
use core_foundation::dictionary::CFDictionary;
|
||||
|
||||
pub const CG_ZERO_POINT: CGPoint = CGPoint {
|
||||
x: 0.0,
|
||||
|
@ -70,15 +72,31 @@ impl CGRect {
|
|||
ffi::CGRectInset(*self, size.width, size.height)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_dict_representation(dict: &CFDictionary) -> Option<CGRect> {
|
||||
let mut rect = CGRect::new(&CGPoint::new(0., 0.), &CGSize::new(0., 0.));
|
||||
let result = unsafe {
|
||||
ffi::CGRectMakeWithDictionaryRepresentation(dict.as_concrete_TypeRef(), &mut rect)
|
||||
};
|
||||
if result == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(rect)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod ffi {
|
||||
use base::CGFloat;
|
||||
use base::{CGFloat, boolean_t};
|
||||
use geometry::CGRect;
|
||||
use core_foundation::dictionary::CFDictionaryRef;
|
||||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
extern {
|
||||
pub fn CGRectInset(rect: CGRect, dx: CGFloat, dy: CGFloat) -> CGRect;
|
||||
pub fn CGRectMakeWithDictionaryRepresentation(dict: CFDictionaryRef,
|
||||
rect: *mut CGRect) -> boolean_t;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,161 @@
|
|||
use core_foundation::base::{CFRetain, CFTypeID, CFTypeRef, TCFType};
|
||||
use core_foundation::data::CFData;
|
||||
use color_space::{CGColorSpace, CGColorSpaceRef};
|
||||
use data_provider::{CGDataProvider, CGDataProviderRef};
|
||||
use libc::size_t;
|
||||
use std::ops::Deref;
|
||||
use std::mem;
|
||||
|
||||
#[repr(C)]
|
||||
pub enum CGImageAlphaInfo {
|
||||
CGImageAlphaNone, /* For example, RGB. */
|
||||
CGImageAlphaPremultipliedLast, /* For example, premultiplied RGBA */
|
||||
CGImageAlphaPremultipliedFirst, /* For example, premultiplied ARGB */
|
||||
CGImageAlphaLast, /* For example, non-premultiplied RGBA */
|
||||
CGImageAlphaFirst, /* For example, non-premultiplied ARGB */
|
||||
CGImageAlphaNoneSkipLast, /* For example, RBGX. */
|
||||
CGImageAlphaNoneSkipFirst, /* For example, XRBG. */
|
||||
CGImageAlphaOnly /* No color data, alpha data only */
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub enum CGImageByteOrderInfo {
|
||||
CGImageByteOrderMask = 0x7000,
|
||||
CGImageByteOrder16Little = (1 << 12),
|
||||
CGImageByteOrder32Little = (2 << 12),
|
||||
CGImageByteOrder16Big = (3 << 12),
|
||||
CGImageByteOrder32Big = (4 << 12)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct __CGImage;
|
||||
|
||||
pub type CGImageRef = *const __CGImage;
|
||||
|
||||
pub struct CGImage {
|
||||
obj: CGImageRef,
|
||||
}
|
||||
|
||||
impl Drop for CGImage {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CGImageRelease(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for CGImage {
|
||||
fn clone(&self) -> CGImage {
|
||||
unsafe {
|
||||
TCFType::wrap_under_get_rule(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Replace all this stuff by simply using:
|
||||
// impl_TCFType!(CGImage, CGImageRef, CGImageGetTypeID);
|
||||
impl TCFType<CGImageRef> for CGImage {
|
||||
#[inline]
|
||||
fn as_concrete_TypeRef(&self) -> CGImageRef {
|
||||
self.obj
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn wrap_under_get_rule(reference: CGImageRef) -> CGImage {
|
||||
let reference: CGImageRef = mem::transmute(CFRetain(mem::transmute(reference)));
|
||||
TCFType::wrap_under_create_rule(reference)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn as_CFTypeRef(&self) -> CFTypeRef {
|
||||
unsafe {
|
||||
mem::transmute(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn wrap_under_create_rule(obj: CGImageRef) -> CGImage {
|
||||
CGImage {
|
||||
obj: obj,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn type_id() -> CFTypeID {
|
||||
unsafe {
|
||||
CGImageGetTypeID()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CGImage {
|
||||
pub fn width(&self) -> size_t {
|
||||
unsafe {
|
||||
CGImageGetWidth(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn height(&self) -> size_t {
|
||||
unsafe {
|
||||
CGImageGetHeight(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bits_per_component(&self) -> size_t {
|
||||
unsafe {
|
||||
CGImageGetBitsPerComponent(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bits_per_pixel(&self) -> size_t {
|
||||
unsafe {
|
||||
CGImageGetBitsPerPixel(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bytes_per_row(&self) -> size_t {
|
||||
unsafe {
|
||||
CGImageGetBytesPerRow(self.as_concrete_TypeRef())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn color_space(&self) -> CGColorSpace {
|
||||
unsafe {
|
||||
TCFType::wrap_under_get_rule(CGImageGetColorSpace(self.as_concrete_TypeRef()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the raw image bytes wrapped in `CFData`. Note, the returned `CFData` owns the
|
||||
/// underlying buffer.
|
||||
pub fn data(&self) -> CFData {
|
||||
let data_provider = unsafe {
|
||||
CGDataProvider::wrap_under_get_rule(CGImageGetDataProvider(self.as_concrete_TypeRef()))
|
||||
};
|
||||
data_provider.copy_data()
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for CGImage {
|
||||
type Target = CGImageRef;
|
||||
|
||||
#[inline]
|
||||
fn deref(&self) -> &CGImageRef {
|
||||
&self.obj
|
||||
}
|
||||
}
|
||||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
extern {
|
||||
fn CGImageGetTypeID() -> CFTypeID;
|
||||
fn CGImageGetWidth(image: CGImageRef) -> size_t;
|
||||
fn CGImageGetHeight(image: CGImageRef) -> size_t;
|
||||
fn CGImageGetBitsPerComponent(image: CGImageRef) -> size_t;
|
||||
fn CGImageGetBitsPerPixel(image: CGImageRef) -> size_t;
|
||||
fn CGImageGetBytesPerRow(image: CGImageRef) -> size_t;
|
||||
fn CGImageGetColorSpace(image: CGImageRef) -> CGColorSpaceRef;
|
||||
fn CGImageGetDataProvider(image: CGImageRef) -> CGDataProviderRef;
|
||||
fn CGImageRelease(image: CGImageRef);
|
||||
|
||||
//fn CGImageGetAlphaInfo(image: CGImageRef) -> CGImageAlphaInfo;
|
||||
//fn CGImageCreateCopyWithColorSpace(image: CGImageRef, space: CGColorSpaceRef) -> CGImageRef
|
||||
}
|
|
@ -8,8 +8,11 @@
|
|||
// except according to those terms.
|
||||
|
||||
extern crate libc;
|
||||
#[macro_use]
|
||||
extern crate core_foundation;
|
||||
extern crate serde;
|
||||
|
||||
#[macro_use]
|
||||
extern crate bitflags;
|
||||
|
||||
pub mod base;
|
||||
pub mod color_space;
|
||||
|
@ -17,7 +20,8 @@ pub mod context;
|
|||
pub mod data_provider;
|
||||
pub mod display;
|
||||
pub mod event;
|
||||
pub mod event_source;
|
||||
pub mod event_source;
|
||||
pub mod font;
|
||||
pub mod geometry;
|
||||
pub mod private;
|
||||
pub mod image;
|
||||
|
|
|
@ -1 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"6aad961651169d31d79c0595624d1777b5c4cbb4cf2bed9a126c7e72d29411fd","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"958d9b6c617dff0b709bd26ddcd5ef2989ad3a64e14494c2f94d12b6986f6dae","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"0c82015d302c9937e6376debd961350afeaeb6dde228aac95e3a3115c5813613","src/font.rs":"d9df5c37cb98436dbf8162af9c3449fea1eab41511d326840759d46d514bcada","src/font_collection.rs":"d4ca7f741fd54b4b22b823833dfa1f1ccd78a26cf112119ae992572835e48df6","src/font_descriptor.rs":"cedc4bd303abd4519c7c95201672ce5652f7396cd34383c059f945eefb64623b","src/font_manager.rs":"de5e22620528322d6811d01f03975c53b676ec743297590de5e17a45393df0f1","src/lib.rs":"b1fc720a9ab7ae4f054f0767e05ba5640b2d9fc8c34d05ae04f25b9dd44f6b81"},"package":"0e9719616a10f717628e074744f8c55df7b450f7a34d29c196d14f4498aad05d"}
|
||||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"6aad961651169d31d79c0595624d1777b5c4cbb4cf2bed9a126c7e72d29411fd","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"c29ed6924aff33e32bf93f6e23e953aab825bd55e148069b7f7f01aaba212345","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"0c82015d302c9937e6376debd961350afeaeb6dde228aac95e3a3115c5813613","src/font.rs":"f6ddf0d3d136bd879e343a89df7b7b79ee45a2037b6807ef67eaf074973e5e8e","src/font_collection.rs":"d4ca7f741fd54b4b22b823833dfa1f1ccd78a26cf112119ae992572835e48df6","src/font_descriptor.rs":"42be4c958abef1dc914c2815193862e56a23729fe7df7e1483b1b32330d1b7bb","src/font_manager.rs":"de5e22620528322d6811d01f03975c53b676ec743297590de5e17a45393df0f1","src/lib.rs":"b1fc720a9ab7ae4f054f0767e05ba5640b2d9fc8c34d05ae04f25b9dd44f6b81"},"package":"74ba2a7abdccb94fb6c00822addef48504182b285aa45a30e78286487888fcb4"}
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "core-text"
|
||||
version = "4.0.0"
|
||||
version = "5.0.0"
|
||||
authors = ["The Servo Project Developers"]
|
||||
description = "Bindings to the Core Text framework."
|
||||
license = "MIT/Apache-2.0"
|
||||
|
@ -11,4 +11,4 @@ libc = "0.2"
|
|||
|
||||
[target.x86_64-apple-darwin.dependencies]
|
||||
core-foundation = "0.3"
|
||||
core-graphics = "0.7"
|
||||
core-graphics = "0.8"
|
||||
|
|
|
@ -12,6 +12,7 @@
|
|||
use font_descriptor::{CTFontDescriptor, CTFontDescriptorRef, CTFontOrientation};
|
||||
use font_descriptor::{CTFontSymbolicTraits, CTFontTraits, SymbolicTraitAccessors, TraitAccessors};
|
||||
|
||||
use core_foundation::array::{CFArray, CFArrayRef};
|
||||
use core_foundation::base::{CFIndex, CFOptionFlags, CFTypeID, CFRelease, CFRetain, CFTypeRef, TCFType};
|
||||
use core_foundation::data::{CFData, CFDataRef};
|
||||
use core_foundation::dictionary::CFDictionaryRef;
|
||||
|
@ -378,6 +379,15 @@ pub fn debug_font_traits(font: &CTFont) {
|
|||
// println!("kCTFontSlantTrait: {}", traits.normalized_slant());
|
||||
}
|
||||
|
||||
pub fn cascade_list_for_languages(font: &CTFont, language_pref_list: &CFArray) -> CFArray {
|
||||
unsafe {
|
||||
let font_collection_ref =
|
||||
CTFontCopyDefaultCascadeListForLanguages(font.as_concrete_TypeRef(),
|
||||
language_pref_list.as_concrete_TypeRef());
|
||||
TCFType::wrap_under_create_rule(font_collection_ref)
|
||||
}
|
||||
}
|
||||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
extern {
|
||||
/*
|
||||
|
@ -453,6 +463,8 @@ extern {
|
|||
fn CTFontCopyName(font: CTFontRef, nameKey: CFStringRef) -> CFStringRef;
|
||||
//fn CTFontCopyLocalizedName(font: CTFontRef, nameKey: CFStringRef,
|
||||
// language: *CFStringRef) -> CFStringRef;
|
||||
fn CTFontCopyDefaultCascadeListForLanguages(font: CTFontRef, languagePrefList: CFArrayRef) -> CFArrayRef;
|
||||
|
||||
|
||||
/* Working With Encoding */
|
||||
//fn CTFontCopyCharacterSet
|
||||
|
|
|
@ -271,15 +271,17 @@ impl CTFontDescriptor {
|
|||
value.expect("A font must have a non-null display name.")
|
||||
}
|
||||
|
||||
pub fn font_path(&self) -> String {
|
||||
pub fn font_path(&self) -> Option<String> {
|
||||
unsafe {
|
||||
let value = CTFontDescriptorCopyAttribute(self.obj, kCTFontURLAttribute);
|
||||
assert!(!value.is_null());
|
||||
if (value.is_null()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let value: CFType = TCFType::wrap_under_get_rule(value);
|
||||
assert!(value.instance_of::<CFURLRef,CFURL>());
|
||||
let url: CFURL = TCFType::wrap_under_get_rule(mem::transmute(value.as_CFTypeRef()));
|
||||
format!("{:?}", url)
|
||||
Some(format!("{:?}", url))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -297,7 +299,7 @@ pub fn debug_descriptor(desc: &CTFontDescriptor) {
|
|||
println!("name: {}", desc.font_name());
|
||||
println!("style: {}", desc.style_name());
|
||||
println!("display: {}", desc.display_name());
|
||||
println!("path: {}", desc.font_path());
|
||||
println!("path: {:?}", desc.font_path());
|
||||
desc.show();
|
||||
}
|
||||
|
||||
|
|
|
@ -1 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"172610b244a5ee8a8e2f1f045058b8abf9291d84bb76bf8779d2fd420419c2d6","Cargo.toml":"c0894413ac3abce23bb93d1284031b29dd00ef7d2f5fcb8573208e0c33280538","README.md":"d69d75705e2582721cbfb2d3b4b2af052c71679057a0b2ac53a22c03f1755bba","appveyor.yml":"2c7b2468dc69bef84860b8900024cb6e1a1c52f6fe1232e8ccd83caaf7c231ca","src/bitmap_render_target.rs":"d3b229f85a9804ac52976431657727b410e7d5253283df046e46d98c196f0a3a","src/com_helpers.rs":"fccb4b36379ae3454a88aa32a8e5c09e46ef5f5626266dde1fe5f40a992de39c","src/comptr.rs":"218435689f505769686e07cfc5428852dda90b849a0d48e670f632307f5edc7c","src/font.rs":"9bdf3134c6ad3639eab3da4419c9b43aad2673797f6fdc65841da2c82e1f3af4","src/font_collection.rs":"969fa3abf141dc3504774886f4783fda4a74cd5a198c643f8a77fc1af4e75258","src/font_face.rs":"9506ca579345ab2b6b5615fc75f8f431e2bb0dbd93123d1d2a21a73c851a5427","src/font_family.rs":"403da9f8f9903cbe7f9f79636497b273f9885e200f53af99f9d4e483f11d6889","src/font_file.rs":"60ad02fc25765a2c113175ea372e98a2be0d84aa65fef9246b6a0192e63ff708","src/font_file_loader_impl.rs":"0d304ad99ff1e6874510a1498223329d798ff75b417e3db7e823a695003dfe92","src/gdi_interop.rs":"98922996afc5b8c8304cb65e7c965419003825dfa172a3e11fe69bf3d768551c","src/glyph_run_analysis.rs":"d30d8b41b047815ab5770c730b7a6d09939f2347b4a4257b87bebec08a5794fe","src/helpers.rs":"5d6f164468234ca8806dc1cea117b42dbfae80cc4c9ae965cb0556efdb364682","src/lib.rs":"07dae7e9a6b8e2970917eade968490e2af90110047a0e16f539647269b12f439","src/rendering_params.rs":"be1d1c433f76926c285d8ecdb747c5d9cc6a6c10c1a1890c0760cd99755ed471","src/test.rs":"d77e45f8866abeea070cbbafd4cbde62d875292e8d191310a04c70091978547c","src/types.rs":"784235c15d61fb0d001373575169aa473c92af18dcbc1709a5b2bbaa3a7ceb22"},"package":"74114b6b49d6731835da7a28a3642651451e315f7f9b9d04e907e65a45681796"}
|
||||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"172610b244a5ee8a8e2f1f045058b8abf9291d84bb76bf8779d2fd420419c2d6","Cargo.toml":"48059bb4b7efd1a6c2d659fa909888f2c8b5d34f0bd8027b4aefaae9b8d0586e","Cargo.toml.orig":"d5991dc02e8e88abd04b4df1a45c32b26c94b3b903d3fe32404097c012e74ea9","README.md":"d69d75705e2582721cbfb2d3b4b2af052c71679057a0b2ac53a22c03f1755bba","appveyor.yml":"2c7b2468dc69bef84860b8900024cb6e1a1c52f6fe1232e8ccd83caaf7c231ca","src/bitmap_render_target.rs":"d3b229f85a9804ac52976431657727b410e7d5253283df046e46d98c196f0a3a","src/com_helpers.rs":"fccb4b36379ae3454a88aa32a8e5c09e46ef5f5626266dde1fe5f40a992de39c","src/comptr.rs":"218435689f505769686e07cfc5428852dda90b849a0d48e670f632307f5edc7c","src/font.rs":"9bdf3134c6ad3639eab3da4419c9b43aad2673797f6fdc65841da2c82e1f3af4","src/font_collection.rs":"969fa3abf141dc3504774886f4783fda4a74cd5a198c643f8a77fc1af4e75258","src/font_face.rs":"9506ca579345ab2b6b5615fc75f8f431e2bb0dbd93123d1d2a21a73c851a5427","src/font_family.rs":"403da9f8f9903cbe7f9f79636497b273f9885e200f53af99f9d4e483f11d6889","src/font_file.rs":"60ad02fc25765a2c113175ea372e98a2be0d84aa65fef9246b6a0192e63ff708","src/font_file_loader_impl.rs":"0d304ad99ff1e6874510a1498223329d798ff75b417e3db7e823a695003dfe92","src/gdi_interop.rs":"98922996afc5b8c8304cb65e7c965419003825dfa172a3e11fe69bf3d768551c","src/glyph_run_analysis.rs":"d30d8b41b047815ab5770c730b7a6d09939f2347b4a4257b87bebec08a5794fe","src/helpers.rs":"5d6f164468234ca8806dc1cea117b42dbfae80cc4c9ae965cb0556efdb364682","src/lib.rs":"07dae7e9a6b8e2970917eade968490e2af90110047a0e16f539647269b12f439","src/rendering_params.rs":"be1d1c433f76926c285d8ecdb747c5d9cc6a6c10c1a1890c0760cd99755ed471","src/test.rs":"d77e45f8866abeea070cbbafd4cbde62d875292e8d191310a04c70091978547c","src/types.rs":"784235c15d61fb0d001373575169aa473c92af18dcbc1709a5b2bbaa3a7ceb22"},"package":"36e3b27cd0b8a68e00f07e8d8e1e4f4d8a6b8b873290a734f63bd56d792d23e1"}
|
|
@ -1,19 +1,42 @@
|
|||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g. crates.io) dependencies
|
||||
#
|
||||
# If you believe there's an error in this file please file an
|
||||
# issue against the rust-lang/cargo repository. If you're
|
||||
# editing this file be aware that the upstream Cargo.toml
|
||||
# will likely look very different (and much more reasonable)
|
||||
|
||||
[package]
|
||||
name = "dwrote"
|
||||
description = "Lightweight binding to DirectWrite."
|
||||
repository = "https://github.com/vvuk/dwrote-rs"
|
||||
license = "MPL-2.0"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Vladimir Vukicevic <vladimir@pobox.com>"]
|
||||
description = "Lightweight binding to DirectWrite."
|
||||
license = "MPL-2.0"
|
||||
repository = "https://github.com/servo/dwrote-rs"
|
||||
|
||||
[lib]
|
||||
name = "dwrote"
|
||||
[dependencies.serde_derive]
|
||||
version = "1.0"
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
lazy_static = "0.2"
|
||||
winapi = "0.2"
|
||||
kernel32-sys = "0.2"
|
||||
gdi32-sys = "0.2"
|
||||
serde = "0.9"
|
||||
serde_derive = "0.9"
|
||||
[dependencies.kernel32-sys]
|
||||
version = "0.2"
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1.0"
|
||||
|
||||
[dependencies.winapi]
|
||||
version = "0.2"
|
||||
|
||||
[dependencies.gdi32-sys]
|
||||
version = "0.2"
|
||||
|
||||
[dependencies.lazy_static]
|
||||
version = "0.2"
|
||||
|
||||
[dependencies.libc]
|
||||
version = "0.2"
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
[package]
|
||||
name = "dwrote"
|
||||
description = "Lightweight binding to DirectWrite."
|
||||
repository = "https://github.com/servo/dwrote-rs"
|
||||
license = "MPL-2.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Vladimir Vukicevic <vladimir@pobox.com>"]
|
||||
|
||||
[lib]
|
||||
name = "dwrote"
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
lazy_static = "0.2"
|
||||
winapi = "0.2"
|
||||
kernel32-sys = "0.2"
|
||||
gdi32-sys = "0.2"
|
||||
serde = "1.0"
|
||||
serde_derive = "1.0"
|
|
@ -1 +0,0 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"118514fd9c4958df0d25584cda4917186c46011569f55ef350530c1ad3fbdb48",".travis.yml":"56843ecfd2b71797b648b8e537623e84af3c638ea4b8472ed27c55f097bce3dc","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"596d3bcfc1684713b5c557e84b35b98250bebb3d4715e44741d227ab246a16ab","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"625bec69c76ce5423fdd05cfe46922b2680ec517f97c5854ce34798d1d8a9541","src/approxeq.rs":"6cf810ad389c73a27141a7a67454ed12d4b01c3c16605b9a7414b389bc0615dd","src/length.rs":"d7877ebc7ee2e85df2a1f5b9376011bdeeaa5cd7fa2fbdba0934df7456c0821e","src/lib.rs":"77b97c1d7889f037180b68344471ecf7c46b5412fe7c92504debc422c8739b61","src/macros.rs":"b63dabdb52df84ea170dc1dab5fe8d7a78c054562d1566bab416124708d2d7af","src/num.rs":"749b201289fc6663199160a2f9204e17925fd3053f8ab7779e7bfb377ad06227","src/point.rs":"42c1ee0997598d3482ac4c58f255e31b56a97a3a0aa1871b61f55074eecf1ae2","src/rect.rs":"e18811e3be9dba41976b611d52dbe13c5a27dc7db3e3e779daabeed7670b658f","src/scale_factor.rs":"61f979384316ae8a70e836b0d4b016ec5c26a952776037a65801152af4a247cb","src/side_offsets.rs":"fd95ffc9a74e9e84314875c388e763d0780486eb7f9034423e3a22048361e379","src/size.rs":"d9a6fb1f080a06e1332b2e804f8334e086e6d6f17a4288f35133d80b2e2da765","src/transform2d.rs":"4fe4fef7266b06b7790cd400d990ad02e6e605499a1a33c8e39b5e00364389ba","src/transform3d.rs":"cd8a08dd341fcea4c5b10e00d029424e382f3b0002dd8341f302be7f1c12c4fc","src/trig.rs":"ef290927af252ca90a29ba9f17158b591ed591604e66cb9df045dd47b9cfdca5","src/vector.rs":"c087700ad35c3e18e0f5722573f6a24ed2b0452e044c1f0bbb6466c993c560f1"},"package":"995b21c36b37e0f18ed9ba1714378a337e3ff19a6e5e952ea94b0f3dd4e12fbc"}
|
|
@ -1,2 +0,0 @@
|
|||
Cargo.lock
|
||||
/target/
|
|
@ -1,24 +0,0 @@
|
|||
language: rust
|
||||
rust:
|
||||
- 1.15.1
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
|
||||
notifications:
|
||||
webhooks: http://build.servo.org:54856/travis
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- rust: stable
|
||||
env: FEATURES=""
|
||||
- rust: beta
|
||||
env: FEATURES=""
|
||||
- rust: nightly
|
||||
env: FEATURES=""
|
||||
- rust: nightly
|
||||
env: FEATURES="unstable"
|
||||
|
||||
script:
|
||||
- cargo build --verbose --features "$FEATURES"
|
||||
- cargo test --verbose --features "$FEATURES"
|
|
@ -1,5 +0,0 @@
|
|||
Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
<LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
option. All files in the project carrying such notice may not be
|
||||
copied, modified, or distributed except according to those terms.
|
|
@ -1,23 +0,0 @@
|
|||
[package]
|
||||
name = "euclid"
|
||||
version = "0.14.4"
|
||||
authors = ["The Servo Project Developers"]
|
||||
description = "Geometry primitives"
|
||||
documentation = "https://docs.rs/euclid/"
|
||||
repository = "https://github.com/servo/euclid"
|
||||
keywords = ["matrix", "vector", "linear-algebra", "geometry"]
|
||||
categories = ["science"]
|
||||
license = "MIT / Apache-2.0"
|
||||
|
||||
[features]
|
||||
unstable = []
|
||||
|
||||
[dependencies]
|
||||
heapsize = "0.4"
|
||||
num-traits = {version = "0.1.32", default-features = false}
|
||||
log = "0.3.1"
|
||||
serde = "0.9"
|
||||
|
||||
[dev-dependencies]
|
||||
rand = "0.3.7"
|
||||
serde_test = "0.9"
|
|
@ -1,25 +0,0 @@
|
|||
Copyright (c) 2012-2013 Mozilla Foundation
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
|
@ -1,8 +0,0 @@
|
|||
# euclid
|
||||
|
||||
This is a small library for geometric types with a focus on 2d graphics and
|
||||
layout.
|
||||
|
||||
* [Documentation](https://docs.rs/euclid/)
|
||||
* [Release notes](https://github.com/servo/euclid/releases)
|
||||
* [crates.io](https://crates.io/crates/euclid)
|
|
@ -1,36 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
|
||||
/// Trait for testing approximate equality
|
||||
pub trait ApproxEq<Eps> {
|
||||
fn approx_epsilon() -> Eps;
|
||||
fn approx_eq(&self, other: &Self) -> bool;
|
||||
fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
|
||||
}
|
||||
|
||||
macro_rules! approx_eq {
|
||||
($ty:ty, $eps:expr) => (
|
||||
impl ApproxEq<$ty> for $ty {
|
||||
#[inline]
|
||||
fn approx_epsilon() -> $ty { $eps }
|
||||
#[inline]
|
||||
fn approx_eq(&self, other: &$ty) -> bool {
|
||||
self.approx_eq_eps(other, &$eps)
|
||||
}
|
||||
#[inline]
|
||||
fn approx_eq_eps(&self, other: &$ty, approx_epsilon: &$ty) -> bool {
|
||||
(*self - *other).abs() < *approx_epsilon
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
approx_eq!(f32, 1.0e-6);
|
||||
approx_eq!(f64, 1.0e-6);
|
|
@ -1,461 +0,0 @@
|
|||
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
//! A one-dimensional length, tagged with its units.
|
||||
|
||||
use scale_factor::ScaleFactor;
|
||||
use num::Zero;
|
||||
|
||||
use heapsize::HeapSizeOf;
|
||||
use num_traits::{NumCast, Saturating};
|
||||
use num::One;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::cmp::Ordering;
|
||||
use std::ops::{Add, Sub, Mul, Div, Neg};
|
||||
use std::ops::{AddAssign, SubAssign};
|
||||
use std::marker::PhantomData;
|
||||
use std::fmt;
|
||||
|
||||
/// A one-dimensional distance, with value represented by `T` and unit of measurement `Unit`.
|
||||
///
|
||||
/// `T` can be any numeric type, for example a primitive type like `u64` or `f32`.
|
||||
///
|
||||
/// `Unit` is not used in the representation of a `Length` value. It is used only at compile time
|
||||
/// to ensure that a `Length` stored with one unit is converted explicitly before being used in an
|
||||
/// expression that requires a different unit. It may be a type without values, such as an empty
|
||||
/// enum.
|
||||
///
|
||||
/// You can multiply a `Length` by a `scale_factor::ScaleFactor` to convert it from one unit to
|
||||
/// another. See the `ScaleFactor` docs for an example.
|
||||
// Uncomment the derive, and remove the macro call, once heapsize gets
|
||||
// PhantomData<T> support.
|
||||
#[repr(C)]
|
||||
pub struct Length<T, Unit>(pub T, PhantomData<Unit>);
|
||||
|
||||
impl<T: Clone, Unit> Clone for Length<T, Unit> {
|
||||
fn clone(&self) -> Self {
|
||||
Length(self.0.clone(), PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, Unit> Copy for Length<T, Unit> {}
|
||||
|
||||
impl<Unit, T: HeapSizeOf> HeapSizeOf for Length<T, Unit> {
|
||||
fn heap_size_of_children(&self) -> usize {
|
||||
self.0.heap_size_of_children()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Unit, T> Deserialize for Length<T, Unit> where T: Deserialize {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer {
|
||||
Ok(Length(try!(Deserialize::deserialize(deserializer)), PhantomData))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Unit> Serialize for Length<T, Unit> where T: Serialize {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
|
||||
self.0.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Unit> Length<T, Unit> {
|
||||
pub fn new(x: T) -> Self {
|
||||
Length(x, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Unit, T: Clone> Length<T, Unit> {
|
||||
pub fn get(&self) -> T {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug + Clone, U> fmt::Debug for Length<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.get().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display + Clone, U> fmt::Display for Length<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.get().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
// length + length
|
||||
impl<U, T: Clone + Add<T, Output=T>> Add for Length<T, U> {
|
||||
type Output = Length<T, U>;
|
||||
fn add(self, other: Length<T, U>) -> Length<T, U> {
|
||||
Length::new(self.get() + other.get())
|
||||
}
|
||||
}
|
||||
|
||||
// length += length
|
||||
impl<U, T: Clone + AddAssign<T>> AddAssign for Length<T, U> {
|
||||
fn add_assign(&mut self, other: Length<T, U>) {
|
||||
self.0 += other.get();
|
||||
}
|
||||
}
|
||||
|
||||
// length - length
|
||||
impl<U, T: Clone + Sub<T, Output=T>> Sub<Length<T, U>> for Length<T, U> {
|
||||
type Output = Length<T, U>;
|
||||
fn sub(self, other: Length<T, U>) -> <Self as Sub>::Output {
|
||||
Length::new(self.get() - other.get())
|
||||
}
|
||||
}
|
||||
|
||||
// length -= length
|
||||
impl<U, T: Clone + SubAssign<T>> SubAssign for Length<T, U> {
|
||||
fn sub_assign(&mut self, other: Length<T, U>) {
|
||||
self.0 -= other.get();
|
||||
}
|
||||
}
|
||||
|
||||
// Saturating length + length and length - length.
|
||||
impl<U, T: Clone + Saturating> Saturating for Length<T, U> {
|
||||
fn saturating_add(self, other: Length<T, U>) -> Length<T, U> {
|
||||
Length::new(self.get().saturating_add(other.get()))
|
||||
}
|
||||
|
||||
fn saturating_sub(self, other: Length<T, U>) -> Length<T, U> {
|
||||
Length::new(self.get().saturating_sub(other.get()))
|
||||
}
|
||||
}
|
||||
|
||||
// length / length
|
||||
impl<Src, Dst, T: Clone + Div<T, Output=T>> Div<Length<T, Src>> for Length<T, Dst> {
|
||||
type Output = ScaleFactor<T, Src, Dst>;
|
||||
#[inline]
|
||||
fn div(self, other: Length<T, Src>) -> ScaleFactor<T, Src, Dst> {
|
||||
ScaleFactor::new(self.get() / other.get())
|
||||
}
|
||||
}
|
||||
|
||||
// length * scaleFactor
|
||||
impl<Src, Dst, T: Clone + Mul<T, Output=T>> Mul<ScaleFactor<T, Src, Dst>> for Length<T, Src> {
|
||||
type Output = Length<T, Dst>;
|
||||
#[inline]
|
||||
fn mul(self, scale: ScaleFactor<T, Src, Dst>) -> Length<T, Dst> {
|
||||
Length::new(self.get() * scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
// length / scaleFactor
|
||||
impl<Src, Dst, T: Clone + Div<T, Output=T>> Div<ScaleFactor<T, Src, Dst>> for Length<T, Dst> {
|
||||
type Output = Length<T, Src>;
|
||||
#[inline]
|
||||
fn div(self, scale: ScaleFactor<T, Src, Dst>) -> Length<T, Src> {
|
||||
Length::new(self.get() / scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
// -length
|
||||
impl <U, T:Clone + Neg<Output=T>> Neg for Length<T, U> {
|
||||
type Output = Length<T, U>;
|
||||
#[inline]
|
||||
fn neg(self) -> Length<T, U> {
|
||||
Length::new(-self.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<Unit, T0: NumCast + Clone> Length<T0, Unit> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
pub fn cast<T1: NumCast + Clone>(&self) -> Option<Length<T1, Unit>> {
|
||||
NumCast::from(self.get()).map(Length::new)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Unit, T: Clone + PartialEq> PartialEq for Length<T, Unit> {
|
||||
fn eq(&self, other: &Self) -> bool { self.get().eq(&other.get()) }
|
||||
}
|
||||
|
||||
impl<Unit, T: Clone + PartialOrd> PartialOrd for Length<T, Unit> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
self.get().partial_cmp(&other.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<Unit, T: Clone + Eq> Eq for Length<T, Unit> {}
|
||||
|
||||
impl<Unit, T: Clone + Ord> Ord for Length<T, Unit> {
|
||||
fn cmp(&self, other: &Self) -> Ordering { self.get().cmp(&other.get()) }
|
||||
}
|
||||
|
||||
impl<Unit, T: Zero> Zero for Length<T, Unit> {
|
||||
fn zero() -> Self {
|
||||
Length::new(Zero::zero())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Length<T, U>
|
||||
where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> {
|
||||
/// Linearly interpolate between this length and another length.
|
||||
///
|
||||
/// `t` is expected to be between zero and one.
|
||||
#[inline]
|
||||
pub fn lerp(&self, other: Self, t: T) -> Self {
|
||||
let one_t = T::one() - t;
|
||||
Length::new(one_t * self.get() + t * other.get())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Length;
|
||||
use num::Zero;
|
||||
|
||||
use heapsize::HeapSizeOf;
|
||||
use num_traits::Saturating;
|
||||
use scale_factor::ScaleFactor;
|
||||
use std::f32::INFINITY;
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::Token;
|
||||
use self::serde_test::assert_tokens;
|
||||
|
||||
enum Inch {}
|
||||
enum Mm {}
|
||||
enum Cm {}
|
||||
enum Second {}
|
||||
|
||||
#[test]
|
||||
fn test_clone() {
|
||||
// A cloned Length is a separate length with the state matching the
|
||||
// original Length at the point it was cloned.
|
||||
let mut variable_length: Length<f32, Inch> = Length::new(12.0);
|
||||
|
||||
let one_foot = variable_length.clone();
|
||||
variable_length.0 = 24.0;
|
||||
|
||||
assert_eq!(one_foot.get(), 12.0);
|
||||
assert_eq!(variable_length.get(), 24.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_heapsizeof_builtins() {
|
||||
// Heap size of built-ins is zero by default.
|
||||
let one_foot: Length<f32, Inch> = Length::new(12.0);
|
||||
|
||||
let heap_size_length_f32 = one_foot.heap_size_of_children();
|
||||
|
||||
assert_eq!(heap_size_length_f32, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_heapsizeof_length_vector() {
|
||||
// Heap size of any Length is just the heap size of the length value.
|
||||
for n in 0..5 {
|
||||
let length: Length<Vec<f32>, Inch> = Length::new(Vec::with_capacity(n));
|
||||
|
||||
assert_eq!(length.heap_size_of_children(), length.0.heap_size_of_children());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_length_serde() {
|
||||
let one_cm: Length<f32, Mm> = Length::new(10.0);
|
||||
|
||||
assert_tokens(&one_cm, &[Token::F32(10.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_clones_length_value() {
|
||||
// Calling get returns a clone of the Length's value.
|
||||
// To test this, we need something clone-able - hence a vector.
|
||||
let mut length: Length<Vec<i32>, Inch> = Length::new(vec![1, 2, 3]);
|
||||
|
||||
let value = length.get();
|
||||
length.0.push(4);
|
||||
|
||||
assert_eq!(value, vec![1, 2, 3]);
|
||||
assert_eq!(length.get(), vec![1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fmt_debug() {
|
||||
// Debug and display format the value only.
|
||||
let one_cm: Length<f32, Mm> = Length::new(10.0);
|
||||
|
||||
let result = format!("{:?}", one_cm);
|
||||
|
||||
assert_eq!(result, "10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fmt_display() {
|
||||
// Debug and display format the value only.
|
||||
let one_cm: Length<f32, Mm> = Length::new(10.0);
|
||||
|
||||
let result = format!("{}", one_cm);
|
||||
|
||||
assert_eq!(result, "10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add() {
|
||||
let length1: Length<u8, Mm> = Length::new(250);
|
||||
let length2: Length<u8, Mm> = Length::new(5);
|
||||
|
||||
let result = length1 + length2;
|
||||
|
||||
assert_eq!(result.get(), 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_addassign() {
|
||||
let one_cm: Length<f32, Mm> = Length::new(10.0);
|
||||
let mut measurement: Length<f32, Mm> = Length::new(5.0);
|
||||
|
||||
measurement += one_cm;
|
||||
|
||||
assert_eq!(measurement.get(), 15.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sub() {
|
||||
let length1: Length<u8, Mm> = Length::new(250);
|
||||
let length2: Length<u8, Mm> = Length::new(5);
|
||||
|
||||
let result = length1 - length2;
|
||||
|
||||
assert_eq!(result.get(), 245);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subassign() {
|
||||
let one_cm: Length<f32, Mm> = Length::new(10.0);
|
||||
let mut measurement: Length<f32, Mm> = Length::new(5.0);
|
||||
|
||||
measurement -= one_cm;
|
||||
|
||||
assert_eq!(measurement.get(), -5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_saturating_add() {
|
||||
let length1: Length<u8, Mm> = Length::new(250);
|
||||
let length2: Length<u8, Mm> = Length::new(6);
|
||||
|
||||
let result = length1.saturating_add(length2);
|
||||
|
||||
assert_eq!(result.get(), 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_saturating_sub() {
|
||||
let length1: Length<u8, Mm> = Length::new(5);
|
||||
let length2: Length<u8, Mm> = Length::new(10);
|
||||
|
||||
let result = length1.saturating_sub(length2);
|
||||
|
||||
assert_eq!(result.get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_division_by_length() {
|
||||
// Division results in a ScaleFactor from denominator units
|
||||
// to numerator units.
|
||||
let length: Length<f32, Cm> = Length::new(5.0);
|
||||
let duration: Length<f32, Second> = Length::new(10.0);
|
||||
|
||||
let result = length / duration;
|
||||
|
||||
let expected: ScaleFactor<f32, Second, Cm> = ScaleFactor::new(0.5);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiplication() {
|
||||
let length_mm: Length<f32, Mm> = Length::new(10.0);
|
||||
let cm_per_mm: ScaleFactor<f32, Mm, Cm> = ScaleFactor::new(0.1);
|
||||
|
||||
let result = length_mm * cm_per_mm;
|
||||
|
||||
let expected: Length<f32, Cm> = Length::new(1.0);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_division_by_scalefactor() {
|
||||
let length: Length<f32, Cm> = Length::new(5.0);
|
||||
let cm_per_second: ScaleFactor<f32, Second, Cm> = ScaleFactor::new(10.0);
|
||||
|
||||
let result = length / cm_per_second;
|
||||
|
||||
let expected: Length<f32, Second> = Length::new(0.5);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_negation() {
|
||||
let length: Length<f32, Cm> = Length::new(5.0);
|
||||
|
||||
let result = -length;
|
||||
|
||||
let expected: Length<f32, Cm> = Length::new(-5.0);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cast() {
|
||||
let length_as_i32: Length<i32, Cm> = Length::new(5);
|
||||
|
||||
let result: Length<f32, Cm> = length_as_i32.cast().unwrap();
|
||||
|
||||
let length_as_f32: Length<f32, Cm> = Length::new(5.0);
|
||||
assert_eq!(result, length_as_f32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_equality() {
|
||||
let length_5_point_0: Length<f32, Cm> = Length::new(5.0);
|
||||
let length_5_point_1: Length<f32, Cm> = Length::new(5.1);
|
||||
let length_0_point_1: Length<f32, Cm> = Length::new(0.1);
|
||||
|
||||
assert!(length_5_point_0 == length_5_point_1 - length_0_point_1);
|
||||
assert!(length_5_point_0 != length_5_point_1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_order() {
|
||||
let length_5_point_0: Length<f32, Cm> = Length::new(5.0);
|
||||
let length_5_point_1: Length<f32, Cm> = Length::new(5.1);
|
||||
let length_0_point_1: Length<f32, Cm> = Length::new(0.1);
|
||||
|
||||
assert!(length_5_point_0 < length_5_point_1);
|
||||
assert!(length_5_point_0 <= length_5_point_1);
|
||||
assert!(length_5_point_0 <= length_5_point_1 - length_0_point_1);
|
||||
assert!(length_5_point_1 > length_5_point_0);
|
||||
assert!(length_5_point_1 >= length_5_point_0);
|
||||
assert!(length_5_point_0 >= length_5_point_1 - length_0_point_1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_add() {
|
||||
type LengthCm = Length<f32, Cm>;
|
||||
let length: LengthCm = Length::new(5.0);
|
||||
|
||||
let result = length - LengthCm::zero();
|
||||
|
||||
assert_eq!(result, length);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_division() {
|
||||
type LengthCm = Length<f32, Cm>;
|
||||
let length: LengthCm = Length::new(5.0);
|
||||
let length_zero: LengthCm = Length::zero();
|
||||
|
||||
let result = length / length_zero;
|
||||
|
||||
let expected: ScaleFactor<f32, Cm, Cm> = ScaleFactor::new(INFINITY);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
}
|
|
@ -1,135 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#![cfg_attr(feature = "unstable", feature(asm, repr_simd, test))]
|
||||
|
||||
//! A collection of strongly typed math tools for computer graphics with an inclination
|
||||
//! towards 2d graphics and layout.
|
||||
//!
|
||||
//! All types are generic over the scalar type of their component (`f32`, `i32`, etc.),
|
||||
//! and tagged with a generic Unit parameter which is useful to prevent mixing
|
||||
//! values from different spaces. For example it should not be legal to translate
|
||||
//! a screen-space position by a world-space vector and this can be expressed using
|
||||
//! the generic Unit parameter.
|
||||
//!
|
||||
//! This unit system is not mandatory and all Typed* structures have an alias
|
||||
//! with the default unit: `UnknownUnit`.
|
||||
//! for example ```Point2D<T>``` is equivalent to ```TypedPoint2D<T, UnknownUnit>```.
|
||||
//! Client code typically creates a set of aliases for each type and doesn't need
|
||||
//! to deal with the specifics of typed units further. For example:
|
||||
//!
|
||||
//! All euclid types are marked `#[repr(C)]` in order to facilitate exposing them to
|
||||
//! foreign function interfaces (provided the underlying scalar type is also `repr(C)`).
|
||||
//!
|
||||
//! ```rust
|
||||
//! use euclid::*;
|
||||
//! pub struct ScreenSpace;
|
||||
//! pub type ScreenPoint = TypedPoint2D<f32, ScreenSpace>;
|
||||
//! pub type ScreenSize = TypedSize2D<f32, ScreenSpace>;
|
||||
//! pub struct WorldSpace;
|
||||
//! pub type WorldPoint = TypedPoint3D<f32, WorldSpace>;
|
||||
//! pub type ProjectionMatrix = TypedMatrix4D<f32, WorldSpace, ScreenSpace>;
|
||||
//! // etc...
|
||||
//! ```
|
||||
//!
|
||||
//! Components are accessed in their scalar form by default for convenience, and most
|
||||
//! types additionally implement strongly typed accessors which return typed ```Length``` wrappers.
|
||||
//! For example:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use euclid::*;
|
||||
//! # pub struct WorldSpace;
|
||||
//! # pub type WorldPoint = TypedPoint3D<f32, WorldSpace>;
|
||||
//! let p = WorldPoint::new(0.0, 1.0, 1.0);
|
||||
//! // p.x is an f32.
|
||||
//! println!("p.x = {:?} ", p.x);
|
||||
//! // p.x is a Length<f32, WorldSpace>.
|
||||
//! println!("p.x_typed() = {:?} ", p.x_typed());
|
||||
//! // Length::get returns the scalar value (f32).
|
||||
//! assert_eq!(p.x, p.x_typed().get());
|
||||
//! ```
|
||||
|
||||
extern crate heapsize;
|
||||
|
||||
#[cfg_attr(test, macro_use)]
|
||||
extern crate log;
|
||||
extern crate serde;
|
||||
|
||||
#[cfg(test)]
|
||||
extern crate rand;
|
||||
#[cfg(feature = "unstable")]
|
||||
extern crate test;
|
||||
extern crate num_traits;
|
||||
|
||||
pub use length::Length;
|
||||
pub use scale_factor::ScaleFactor;
|
||||
pub use transform2d::{Transform2D, TypedTransform2D};
|
||||
pub use transform3d::{Transform3D, TypedTransform3D};
|
||||
pub use point::{
|
||||
Point2D, TypedPoint2D, point2,
|
||||
Point3D, TypedPoint3D, point3,
|
||||
};
|
||||
pub use vector::{
|
||||
Vector2D, TypedVector2D, vec2,
|
||||
Vector3D, TypedVector3D, vec3,
|
||||
};
|
||||
|
||||
pub use rect::{Rect, TypedRect, rect};
|
||||
pub use side_offsets::{SideOffsets2D, TypedSideOffsets2D};
|
||||
#[cfg(feature = "unstable")] pub use side_offsets::SideOffsets2DSimdI32;
|
||||
pub use size::{Size2D, TypedSize2D, size2};
|
||||
pub use trig::Trig;
|
||||
|
||||
pub mod approxeq;
|
||||
pub mod num;
|
||||
mod length;
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
mod transform2d;
|
||||
mod transform3d;
|
||||
mod point;
|
||||
mod rect;
|
||||
mod scale_factor;
|
||||
mod side_offsets;
|
||||
mod size;
|
||||
mod trig;
|
||||
mod vector;
|
||||
|
||||
/// The default unit.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct UnknownUnit;
|
||||
|
||||
/// Unit for angles in radians.
|
||||
pub struct Rad;
|
||||
|
||||
/// Unit for angles in degrees.
|
||||
pub struct Deg;
|
||||
|
||||
/// A value in radians.
|
||||
pub type Radians<T> = Length<T, Rad>;
|
||||
|
||||
/// A value in Degrees.
|
||||
pub type Degrees<T> = Length<T, Deg>;
|
||||
|
||||
/// Temporary alias to facilitate the transition to the new naming scheme
|
||||
#[deprecated]
|
||||
pub type Matrix2D<T> = Transform2D<T>;
|
||||
|
||||
/// Temporary alias to facilitate the transition to the new naming scheme
|
||||
#[deprecated]
|
||||
pub type TypedMatrix2D<T, Src, Dst> = TypedTransform2D<T, Src, Dst>;
|
||||
|
||||
/// Temporary alias to facilitate the transition to the new naming scheme
|
||||
#[deprecated]
|
||||
pub type Matrix4D<T> = Transform3D<T>;
|
||||
|
||||
/// Temporary alias to facilitate the transition to the new naming scheme
|
||||
#[deprecated]
|
||||
pub type TypedMatrix4D<T, Src, Dst> = TypedTransform3D<T, Src, Dst>;
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
macro_rules! define_matrix {
|
||||
(
|
||||
$(#[$attr:meta])*
|
||||
pub struct $name:ident<T, $($phantom:ident),+> {
|
||||
$(pub $field:ident: T,)+
|
||||
}
|
||||
) => (
|
||||
#[repr(C)]
|
||||
$(#[$attr])*
|
||||
pub struct $name<T, $($phantom),+> {
|
||||
$(pub $field: T,)+
|
||||
_unit: PhantomData<($($phantom),+)>
|
||||
}
|
||||
|
||||
impl<T: Clone, $($phantom),+> Clone for $name<T, $($phantom),+> {
|
||||
fn clone(&self) -> Self {
|
||||
$name {
|
||||
$($field: self.$field.clone(),)+
|
||||
_unit: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, $($phantom),+> Copy for $name<T, $($phantom),+> {}
|
||||
|
||||
impl<T, $($phantom),+> ::heapsize::HeapSizeOf for $name<T, $($phantom),+>
|
||||
where T: ::heapsize::HeapSizeOf
|
||||
{
|
||||
fn heap_size_of_children(&self) -> usize {
|
||||
$(self.$field.heap_size_of_children() +)+ 0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, $($phantom),+> ::serde::Deserialize for $name<T, $($phantom),+>
|
||||
where T: ::serde::Deserialize
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: ::serde::Deserializer
|
||||
{
|
||||
let ($($field,)+) =
|
||||
try!(::serde::Deserialize::deserialize(deserializer));
|
||||
Ok($name {
|
||||
$($field: $field,)+
|
||||
_unit: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, $($phantom),+> ::serde::Serialize for $name<T, $($phantom),+>
|
||||
where T: ::serde::Serialize
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: ::serde::Serializer
|
||||
{
|
||||
($(&self.$field,)+).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, $($phantom),+> ::std::cmp::Eq for $name<T, $($phantom),+>
|
||||
where T: ::std::cmp::Eq {}
|
||||
|
||||
impl<T, $($phantom),+> ::std::cmp::PartialEq for $name<T, $($phantom),+>
|
||||
where T: ::std::cmp::PartialEq
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
true $(&& self.$field == other.$field)+
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, $($phantom),+> ::std::hash::Hash for $name<T, $($phantom),+>
|
||||
where T: ::std::hash::Hash
|
||||
{
|
||||
fn hash<H: ::std::hash::Hasher>(&self, h: &mut H) {
|
||||
$(self.$field.hash(h);)+
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
|
@ -1,77 +0,0 @@
|
|||
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
//! A one-dimensional length, tagged with its units.
|
||||
|
||||
use num_traits;
|
||||
|
||||
|
||||
pub trait Zero {
|
||||
fn zero() -> Self;
|
||||
}
|
||||
|
||||
impl<T: num_traits::Zero> Zero for T {
|
||||
fn zero() -> T { num_traits::Zero::zero() }
|
||||
}
|
||||
|
||||
pub trait One {
|
||||
fn one() -> Self;
|
||||
}
|
||||
|
||||
impl<T: num_traits::One> One for T {
|
||||
fn one() -> T { num_traits::One::one() }
|
||||
}
|
||||
|
||||
|
||||
pub trait Round : Copy { fn round(self) -> Self; }
|
||||
pub trait Floor : Copy { fn floor(self) -> Self; }
|
||||
pub trait Ceil : Copy { fn ceil(self) -> Self; }
|
||||
|
||||
macro_rules! num_int {
|
||||
($ty:ty) => (
|
||||
impl Round for $ty {
|
||||
#[inline]
|
||||
fn round(self) -> $ty { self }
|
||||
}
|
||||
impl Floor for $ty {
|
||||
#[inline]
|
||||
fn floor(self) -> $ty { self }
|
||||
}
|
||||
impl Ceil for $ty {
|
||||
#[inline]
|
||||
fn ceil(self) -> $ty { self }
|
||||
}
|
||||
)
|
||||
}
|
||||
macro_rules! num_float {
|
||||
($ty:ty) => (
|
||||
impl Round for $ty {
|
||||
#[inline]
|
||||
fn round(self) -> $ty { self.round() }
|
||||
}
|
||||
impl Floor for $ty {
|
||||
#[inline]
|
||||
fn floor(self) -> $ty { self.floor() }
|
||||
}
|
||||
impl Ceil for $ty {
|
||||
#[inline]
|
||||
fn ceil(self) -> $ty { self.ceil() }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
num_int!(i16);
|
||||
num_int!(u16);
|
||||
num_int!(i32);
|
||||
num_int!(u32);
|
||||
num_int!(i64);
|
||||
num_int!(u64);
|
||||
num_int!(isize);
|
||||
num_int!(usize);
|
||||
num_float!(f32);
|
||||
num_float!(f64);
|
|
@ -1,796 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use super::UnknownUnit;
|
||||
use approxeq::ApproxEq;
|
||||
use length::Length;
|
||||
use scale_factor::ScaleFactor;
|
||||
use size::TypedSize2D;
|
||||
use num::*;
|
||||
use num_traits::{Float, NumCast};
|
||||
use vector::{TypedVector2D, TypedVector3D, vec2, vec3};
|
||||
use std::fmt;
|
||||
use std::ops::{Add, Mul, Sub, Div, AddAssign, SubAssign, MulAssign, DivAssign};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
define_matrix! {
|
||||
/// A 2d Point tagged with a unit.
|
||||
pub struct TypedPoint2D<T, U> {
|
||||
pub x: T,
|
||||
pub y: T,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default 2d point type with no unit.
|
||||
///
|
||||
/// `Point2D` provides the same methods as `TypedPoint2D`.
|
||||
pub type Point2D<T> = TypedPoint2D<T, UnknownUnit>;
|
||||
|
||||
impl<T: Copy + Zero, U> TypedPoint2D<T, U> {
|
||||
/// Constructor, setting all components to zero.
|
||||
#[inline]
|
||||
pub fn origin() -> Self {
|
||||
point2(Zero::zero(), Zero::zero())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn zero() -> Self {
|
||||
Self::origin()
|
||||
}
|
||||
|
||||
/// Convert into a 3d point.
|
||||
#[inline]
|
||||
pub fn to_3d(&self) -> TypedPoint3D<T, U> {
|
||||
point3(self.x, self.y, Zero::zero())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for TypedPoint2D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "({:?},{:?})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display, U> fmt::Display for TypedPoint2D<T, U> {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "({},{})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> TypedPoint2D<T, U> {
|
||||
/// Constructor taking scalar values directly.
|
||||
#[inline]
|
||||
pub fn new(x: T, y: T) -> Self {
|
||||
TypedPoint2D { x: x, y: y, _unit: PhantomData }
|
||||
}
|
||||
|
||||
/// Constructor taking properly typed Lengths instead of scalar values.
|
||||
#[inline]
|
||||
pub fn from_lengths(x: Length<T, U>, y: Length<T, U>) -> Self {
|
||||
point2(x.0, y.0)
|
||||
}
|
||||
|
||||
/// Create a 3d point from this one, using the specified z value.
|
||||
#[inline]
|
||||
pub fn extend(&self, z: T) -> TypedPoint3D<T, U> {
|
||||
point3(self.x, self.y, z)
|
||||
}
|
||||
|
||||
/// Cast this point into a vector.
|
||||
///
|
||||
/// Equivalent to substracting the origin to this point.
|
||||
#[inline]
|
||||
pub fn to_vector(&self) -> TypedVector2D<T, U> {
|
||||
vec2(self.x, self.y)
|
||||
}
|
||||
|
||||
/// Returns self.x as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn x_typed(&self) -> Length<T, U> { Length::new(self.x) }
|
||||
|
||||
/// Returns self.y as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn y_typed(&self) -> Length<T, U> { Length::new(self.y) }
|
||||
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
#[inline]
|
||||
pub fn to_untyped(&self) -> Point2D<T> {
|
||||
point2(self.x, self.y)
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
#[inline]
|
||||
pub fn from_untyped(p: &Point2D<T>) -> Self {
|
||||
point2(p.x, p.y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_array(&self) -> [T; 2] {
|
||||
[self.x, self.y]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> TypedPoint2D<T, U> {
|
||||
#[inline]
|
||||
pub fn add_size(&self, other: &TypedSize2D<T, U>) -> Self {
|
||||
point2(self.x + other.width, self.y + other.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> Add<TypedSize2D<T, U>> for TypedPoint2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn add(self, other: TypedSize2D<T, U>) -> Self {
|
||||
point2(self.x + other.width, self.y + other.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> AddAssign<TypedVector2D<T, U>> for TypedPoint2D<T, U> {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, other: TypedVector2D<T, U>) {
|
||||
*self = *self + other
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> SubAssign<TypedVector2D<T, U>> for TypedPoint2D<T, U> {
|
||||
#[inline]
|
||||
fn sub_assign(&mut self, other: TypedVector2D<T, U>) {
|
||||
*self = *self - other
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> Add<TypedVector2D<T, U>> for TypedPoint2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn add(self, other: TypedVector2D<T, U>) -> Self {
|
||||
point2(self.x + other.x, self.y + other.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedPoint2D<T, U> {
|
||||
type Output = TypedVector2D<T, U>;
|
||||
#[inline]
|
||||
fn sub(self, other: Self) -> TypedVector2D<T, U> {
|
||||
vec2(self.x - other.x, self.y - other.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> Sub<TypedVector2D<T, U>> for TypedPoint2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn sub(self, other: TypedVector2D<T, U>) -> Self {
|
||||
point2(self.x - other.x, self.y - other.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Float, U> TypedPoint2D<T, U> {
|
||||
#[inline]
|
||||
pub fn min(self, other: Self) -> Self {
|
||||
point2(self.x.min(other.x), self.y.min(other.y))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max(self, other: Self) -> Self {
|
||||
point2(self.x.max(other.x), self.y.max(other.y))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedPoint2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn mul(self, scale: T) -> Self {
|
||||
point2(self.x * scale, self.y * scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> MulAssign<T> for TypedPoint2D<T, U> {
|
||||
#[inline]
|
||||
fn mul_assign(&mut self, scale: T) {
|
||||
*self = *self * scale
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedPoint2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn div(self, scale: T) -> Self {
|
||||
point2(self.x / scale, self.y / scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> DivAssign<T> for TypedPoint2D<T, U> {
|
||||
#[inline]
|
||||
fn div_assign(&mut self, scale: T) {
|
||||
*self = *self / scale
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U1, U2> Mul<ScaleFactor<T, U1, U2>> for TypedPoint2D<T, U1> {
|
||||
type Output = TypedPoint2D<T, U2>;
|
||||
#[inline]
|
||||
fn mul(self, scale: ScaleFactor<T, U1, U2>) -> TypedPoint2D<T, U2> {
|
||||
point2(self.x * scale.get(), self.y * scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U1, U2> Div<ScaleFactor<T, U1, U2>> for TypedPoint2D<T, U2> {
|
||||
type Output = TypedPoint2D<T, U1>;
|
||||
#[inline]
|
||||
fn div(self, scale: ScaleFactor<T, U1, U2>) -> TypedPoint2D<T, U1> {
|
||||
point2(self.x / scale.get(), self.y / scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Round, U> TypedPoint2D<T, U> {
|
||||
/// Rounds each component to the nearest integer value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
/// For example `{ -0.1, -0.8 }.round() == { 0.0, -1.0 }`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn round(&self) -> Self {
|
||||
point2(self.x.round(), self.y.round())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Ceil, U> TypedPoint2D<T, U> {
|
||||
/// Rounds each component to the smallest integer equal or greater than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
/// For example `{ -0.1, -0.8 }.ceil() == { 0.0, 0.0 }`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn ceil(&self) -> Self {
|
||||
point2(self.x.ceil(), self.y.ceil())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Floor, U> TypedPoint2D<T, U> {
|
||||
/// Rounds each component to the biggest integer equal or lower than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
/// For example `{ -0.1, -0.8 }.floor() == { -1.0, -1.0 }`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn floor(&self) -> Self {
|
||||
point2(self.x.floor(), self.y.floor())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: NumCast + Copy, U> TypedPoint2D<T, U> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
///
|
||||
/// When casting from floating point to integer coordinates, the decimals are truncated
|
||||
/// as one would expect from a simple cast, but this behavior does not always make sense
|
||||
/// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
|
||||
#[inline]
|
||||
pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedPoint2D<NewT, U>> {
|
||||
match (NumCast::from(self.x), NumCast::from(self.y)) {
|
||||
(Some(x), Some(y)) => Some(point2(x, y)),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience functions for common casts
|
||||
|
||||
/// Cast into an `f32` point.
|
||||
#[inline]
|
||||
pub fn to_f32(&self) -> TypedPoint2D<f32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `usize` point, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point points, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_usize(&self) -> TypedPoint2D<usize, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an i32 point, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point points, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i32(&self) -> TypedPoint2D<i32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an i64 point, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point points, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i64(&self) -> TypedPoint2D<i64, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedPoint2D<T, U>
|
||||
where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> {
|
||||
/// Linearly interpolate between this point and another point.
|
||||
///
|
||||
/// `t` is expected to be between zero and one.
|
||||
#[inline]
|
||||
pub fn lerp(&self, other: Self, t: T) -> Self {
|
||||
let one_t = T::one() - t;
|
||||
point2(
|
||||
one_t * self.x + t * other.x,
|
||||
one_t * self.y + t * other.y,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy+ApproxEq<T>, U> ApproxEq<TypedPoint2D<T, U>> for TypedPoint2D<T, U> {
|
||||
#[inline]
|
||||
fn approx_epsilon() -> Self {
|
||||
point2(T::approx_epsilon(), T::approx_epsilon())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq(&self, other: &Self) -> bool {
|
||||
self.x.approx_eq(&other.x) && self.y.approx_eq(&other.y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
|
||||
self.x.approx_eq_eps(&other.x, &eps.x) && self.y.approx_eq_eps(&other.y, &eps.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> Into<[T; 2]> for TypedPoint2D<T, U> {
|
||||
fn into(self) -> [T; 2] {
|
||||
self.to_array()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> From<[T; 2]> for TypedPoint2D<T, U> {
|
||||
fn from(array: [T; 2]) -> Self {
|
||||
point2(array[0], array[1])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
define_matrix! {
|
||||
/// A 3d Point tagged with a unit.
|
||||
pub struct TypedPoint3D<T, U> {
|
||||
pub x: T,
|
||||
pub y: T,
|
||||
pub z: T,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default 3d point type with no unit.
|
||||
///
|
||||
/// `Point3D` provides the same methods as `TypedPoint3D`.
|
||||
pub type Point3D<T> = TypedPoint3D<T, UnknownUnit>;
|
||||
|
||||
impl<T: Copy + Zero, U> TypedPoint3D<T, U> {
|
||||
/// Constructor, setting all copmonents to zero.
|
||||
#[inline]
|
||||
pub fn origin() -> Self {
|
||||
point3(Zero::zero(), Zero::zero(), Zero::zero())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + One, U> TypedPoint3D<T, U> {
|
||||
#[inline]
|
||||
pub fn to_array_4d(&self) -> [T; 4] {
|
||||
[self.x, self.y, self.z, One::one()]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedPoint3D<T, U>
|
||||
where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> {
|
||||
/// Linearly interpolate between this point and another point.
|
||||
///
|
||||
/// `t` is expected to be between zero and one.
|
||||
#[inline]
|
||||
pub fn lerp(&self, other: Self, t: T) -> Self {
|
||||
let one_t = T::one() - t;
|
||||
point3(
|
||||
one_t * self.x + t * other.x,
|
||||
one_t * self.y + t * other.y,
|
||||
one_t * self.z + t * other.z,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for TypedPoint3D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "({:?},{:?},{:?})", self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display, U> fmt::Display for TypedPoint3D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "({},{},{})", self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> TypedPoint3D<T, U> {
|
||||
/// Constructor taking scalar values directly.
|
||||
#[inline]
|
||||
pub fn new(x: T, y: T, z: T) -> Self {
|
||||
TypedPoint3D { x: x, y: y, z: z, _unit: PhantomData }
|
||||
}
|
||||
|
||||
/// Constructor taking properly typed Lengths instead of scalar values.
|
||||
#[inline]
|
||||
pub fn from_lengths(x: Length<T, U>, y: Length<T, U>, z: Length<T, U>) -> Self {
|
||||
point3(x.0, y.0, z.0)
|
||||
}
|
||||
|
||||
/// Cast this point into a vector.
|
||||
///
|
||||
/// Equivalent to substracting the origin to this point.
|
||||
#[inline]
|
||||
pub fn to_vector(&self) -> TypedVector3D<T, U> {
|
||||
vec3(self.x, self.y, self.z)
|
||||
}
|
||||
|
||||
/// Returns self.x as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn x_typed(&self) -> Length<T, U> { Length::new(self.x) }
|
||||
|
||||
/// Returns self.y as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn y_typed(&self) -> Length<T, U> { Length::new(self.y) }
|
||||
|
||||
/// Returns self.z as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn z_typed(&self) -> Length<T, U> { Length::new(self.z) }
|
||||
|
||||
#[inline]
|
||||
pub fn to_array(&self) -> [T; 3] { [self.x, self.y, self.z] }
|
||||
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
#[inline]
|
||||
pub fn to_untyped(&self) -> Point3D<T> {
|
||||
point3(self.x, self.y, self.z)
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
#[inline]
|
||||
pub fn from_untyped(p: &Point3D<T>) -> Self {
|
||||
point3(p.x, p.y, p.z)
|
||||
}
|
||||
|
||||
/// Convert into a 2d point.
|
||||
#[inline]
|
||||
pub fn to_2d(&self) -> TypedPoint2D<T, U> {
|
||||
point2(self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> AddAssign<TypedVector3D<T, U>> for TypedPoint3D<T, U> {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, other: TypedVector3D<T, U>) {
|
||||
*self = *self + other
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> SubAssign<TypedVector3D<T, U>> for TypedPoint3D<T, U> {
|
||||
#[inline]
|
||||
fn sub_assign(&mut self, other: TypedVector3D<T, U>) {
|
||||
*self = *self - other
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> Add<TypedVector3D<T, U>> for TypedPoint3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn add(self, other: TypedVector3D<T, U>) -> Self {
|
||||
point3(self.x + other.x, self.y + other.y, self.z + other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedPoint3D<T, U> {
|
||||
type Output = TypedVector3D<T, U>;
|
||||
#[inline]
|
||||
fn sub(self, other: Self) -> TypedVector3D<T, U> {
|
||||
vec3(self.x - other.x, self.y - other.y, self.z - other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> Sub<TypedVector3D<T, U>> for TypedPoint3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn sub(self, other: TypedVector3D<T, U>) -> Self {
|
||||
point3(self.x - other.x, self.y - other.y, self.z - other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedPoint3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn mul(self, scale: T) -> Self {
|
||||
point3(self.x * scale, self.y * scale, self.z * scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedPoint3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn div(self, scale: T) -> Self {
|
||||
point3(self.x / scale, self.y / scale, self.z / scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Float, U> TypedPoint3D<T, U> {
|
||||
#[inline]
|
||||
pub fn min(self, other: Self) -> Self {
|
||||
point3(self.x.min(other.x), self.y.min(other.y), self.z.min(other.z))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max(self, other: Self) -> Self {
|
||||
point3(self.x.max(other.x), self.y.max(other.y), self.z.max(other.z))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Round, U> TypedPoint3D<T, U> {
|
||||
/// Rounds each component to the nearest integer value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn round(&self) -> Self {
|
||||
point3(self.x.round(), self.y.round(), self.z.round())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Ceil, U> TypedPoint3D<T, U> {
|
||||
/// Rounds each component to the smallest integer equal or greater than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn ceil(&self) -> Self {
|
||||
point3(self.x.ceil(), self.y.ceil(), self.z.ceil())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Floor, U> TypedPoint3D<T, U> {
|
||||
/// Rounds each component to the biggest integer equal or lower than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn floor(&self) -> Self {
|
||||
point3(self.x.floor(), self.y.floor(), self.z.floor())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: NumCast + Copy, U> TypedPoint3D<T, U> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
///
|
||||
/// When casting from floating point to integer coordinates, the decimals are truncated
|
||||
/// as one would expect from a simple cast, but this behavior does not always make sense
|
||||
/// geometrically. Consider using round(), ceil or floor() before casting.
|
||||
#[inline]
|
||||
pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedPoint3D<NewT, U>> {
|
||||
match (NumCast::from(self.x),
|
||||
NumCast::from(self.y),
|
||||
NumCast::from(self.z)) {
|
||||
(Some(x), Some(y), Some(z)) => Some(point3(x, y, z)),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience functions for common casts
|
||||
|
||||
/// Cast into an `f32` point.
|
||||
#[inline]
|
||||
pub fn to_f32(&self) -> TypedPoint3D<f32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `usize` point, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point points, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_usize(&self) -> TypedPoint3D<usize, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i32` point, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point points, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i32(&self) -> TypedPoint3D<i32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i64` point, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point points, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i64(&self) -> TypedPoint3D<i64, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy+ApproxEq<T>, U> ApproxEq<TypedPoint3D<T, U>> for TypedPoint3D<T, U> {
|
||||
#[inline]
|
||||
fn approx_epsilon() -> Self {
|
||||
point3(T::approx_epsilon(), T::approx_epsilon(), T::approx_epsilon())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq(&self, other: &Self) -> bool {
|
||||
self.x.approx_eq(&other.x)
|
||||
&& self.y.approx_eq(&other.y)
|
||||
&& self.z.approx_eq(&other.z)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
|
||||
self.x.approx_eq_eps(&other.x, &eps.x)
|
||||
&& self.y.approx_eq_eps(&other.y, &eps.y)
|
||||
&& self.z.approx_eq_eps(&other.z, &eps.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> Into<[T; 3]> for TypedPoint3D<T, U> {
|
||||
fn into(self) -> [T; 3] {
|
||||
self.to_array()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> From<[T; 3]> for TypedPoint3D<T, U> {
|
||||
fn from(array: [T; 3]) -> Self {
|
||||
point3(array[0], array[1], array[2])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn point2<T: Copy, U>(x: T, y: T) -> TypedPoint2D<T, U> {
|
||||
TypedPoint2D::new(x, y)
|
||||
}
|
||||
|
||||
pub fn point3<T: Copy, U>(x: T, y: T, z: T) -> TypedPoint3D<T, U> {
|
||||
TypedPoint3D::new(x, y, z)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod point2d {
|
||||
use super::Point2D;
|
||||
|
||||
#[test]
|
||||
pub fn test_scalar_mul() {
|
||||
let p1: Point2D<f32> = Point2D::new(3.0, 5.0);
|
||||
|
||||
let result = p1 * 5.0;
|
||||
|
||||
assert_eq!(result, Point2D::new(15.0, 25.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_min() {
|
||||
let p1 = Point2D::new(1.0, 3.0);
|
||||
let p2 = Point2D::new(2.0, 2.0);
|
||||
|
||||
let result = p1.min(p2);
|
||||
|
||||
assert_eq!(result, Point2D::new(1.0, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_max() {
|
||||
let p1 = Point2D::new(1.0, 3.0);
|
||||
let p2 = Point2D::new(2.0, 2.0);
|
||||
|
||||
let result = p1.max(p2);
|
||||
|
||||
assert_eq!(result, Point2D::new(2.0, 3.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod typedpoint2d {
|
||||
use super::TypedPoint2D;
|
||||
use scale_factor::ScaleFactor;
|
||||
use vector::vec2;
|
||||
|
||||
pub enum Mm {}
|
||||
pub enum Cm {}
|
||||
|
||||
pub type Point2DMm<T> = TypedPoint2D<T, Mm>;
|
||||
pub type Point2DCm<T> = TypedPoint2D<T, Cm>;
|
||||
|
||||
#[test]
|
||||
pub fn test_add() {
|
||||
let p1 = Point2DMm::new(1.0, 2.0);
|
||||
let p2 = vec2(3.0, 4.0);
|
||||
|
||||
let result = p1 + p2;
|
||||
|
||||
assert_eq!(result, Point2DMm::new(4.0, 6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_add_assign() {
|
||||
let mut p1 = Point2DMm::new(1.0, 2.0);
|
||||
p1 += vec2(3.0, 4.0);
|
||||
|
||||
assert_eq!(p1, Point2DMm::new(4.0, 6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_scalar_mul() {
|
||||
let p1 = Point2DMm::new(1.0, 2.0);
|
||||
let cm_per_mm: ScaleFactor<f32, Mm, Cm> = ScaleFactor::new(0.1);
|
||||
|
||||
let result = p1 * cm_per_mm;
|
||||
|
||||
assert_eq!(result, Point2DCm::new(0.1, 0.2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_conv_vector() {
|
||||
use {Point2D, point2};
|
||||
|
||||
for i in 0..100 {
|
||||
// We don't care about these values as long as they are not the same.
|
||||
let x = i as f32 *0.012345;
|
||||
let y = i as f32 *0.987654;
|
||||
let p: Point2D<f32> = point2(x, y);
|
||||
assert_eq!(p.to_vector().to_point(), p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod point3d {
|
||||
use super::Point3D;
|
||||
|
||||
#[test]
|
||||
pub fn test_min() {
|
||||
let p1 = Point3D::new(1.0, 3.0, 5.0);
|
||||
let p2 = Point3D::new(2.0, 2.0, -1.0);
|
||||
|
||||
let result = p1.min(p2);
|
||||
|
||||
assert_eq!(result, Point3D::new(1.0, 2.0, -1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_max() {
|
||||
let p1 = Point3D::new(1.0, 3.0, 5.0);
|
||||
let p2 = Point3D::new(2.0, 2.0, -1.0);
|
||||
|
||||
let result = p1.max(p2);
|
||||
|
||||
assert_eq!(result, Point3D::new(2.0, 3.0, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_conv_vector() {
|
||||
use point3;
|
||||
for i in 0..100 {
|
||||
// We don't care about these values as long as they are not the same.
|
||||
let x = i as f32 *0.012345;
|
||||
let y = i as f32 *0.987654;
|
||||
let z = x * y;
|
||||
let p: Point3D<f32> = point3(x, y, z);
|
||||
assert_eq!(p.to_vector().to_point(), p);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,699 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use super::UnknownUnit;
|
||||
use length::Length;
|
||||
use scale_factor::ScaleFactor;
|
||||
use num::*;
|
||||
use point::TypedPoint2D;
|
||||
use vector::TypedVector2D;
|
||||
use size::TypedSize2D;
|
||||
|
||||
use heapsize::HeapSizeOf;
|
||||
use num_traits::NumCast;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::cmp::PartialOrd;
|
||||
use std::fmt;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::ops::{Add, Sub, Mul, Div};
|
||||
|
||||
/// A 2d Rectangle optionally tagged with a unit.
|
||||
pub struct TypedRect<T, U = UnknownUnit> {
|
||||
pub origin: TypedPoint2D<T, U>,
|
||||
pub size: TypedSize2D<T, U>,
|
||||
}
|
||||
|
||||
/// The default rectangle type with no unit.
|
||||
pub type Rect<T> = TypedRect<T, UnknownUnit>;
|
||||
|
||||
impl<T: HeapSizeOf, U> HeapSizeOf for TypedRect<T, U> {
|
||||
fn heap_size_of_children(&self) -> usize {
|
||||
self.origin.heap_size_of_children() + self.size.heap_size_of_children()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Deserialize, U> Deserialize for TypedRect<T, U> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
let (origin, size) = try!(Deserialize::deserialize(deserializer));
|
||||
Ok(TypedRect::new(origin, size))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Serialize, U> Serialize for TypedRect<T, U> {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(&self.origin, &self.size).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Hash, U> Hash for TypedRect<T, U>
|
||||
{
|
||||
fn hash<H: Hasher>(&self, h: &mut H) {
|
||||
self.origin.hash(h);
|
||||
self.size.hash(h);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> Copy for TypedRect<T, U> {}
|
||||
|
||||
impl<T: Copy, U> Clone for TypedRect<T, U> {
|
||||
fn clone(&self) -> Self { *self }
|
||||
}
|
||||
|
||||
impl<T: PartialEq, U> PartialEq<TypedRect<T, U>> for TypedRect<T, U> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.origin.eq(&other.origin) && self.size.eq(&other.size)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Eq, U> Eq for TypedRect<T, U> {}
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for TypedRect<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "TypedRect({:?} at {:?})", self.size, self.origin)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display, U> fmt::Display for TypedRect<T, U> {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "Rect({} at {})", self.size, self.origin)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedRect<T, U> {
|
||||
/// Constructor.
|
||||
pub fn new(origin: TypedPoint2D<T, U>, size: TypedSize2D<T, U>) -> Self {
|
||||
TypedRect {
|
||||
origin: origin,
|
||||
size: size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedRect<T, U>
|
||||
where T: Copy + Clone + Zero + PartialOrd + PartialEq + Add<T, Output=T> + Sub<T, Output=T> {
|
||||
#[inline]
|
||||
pub fn intersects(&self, other: &Self) -> bool {
|
||||
self.origin.x < other.origin.x + other.size.width &&
|
||||
other.origin.x < self.origin.x + self.size.width &&
|
||||
self.origin.y < other.origin.y + other.size.height &&
|
||||
other.origin.y < self.origin.y + self.size.height
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max_x(&self) -> T {
|
||||
self.origin.x + self.size.width
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn min_x(&self) -> T {
|
||||
self.origin.x
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max_y(&self) -> T {
|
||||
self.origin.y + self.size.height
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn min_y(&self) -> T {
|
||||
self.origin.y
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max_x_typed(&self) -> Length<T, U> {
|
||||
Length::new(self.max_x())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn min_x_typed(&self) -> Length<T, U> {
|
||||
Length::new(self.min_x())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max_y_typed(&self) -> Length<T, U> {
|
||||
Length::new(self.max_y())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn min_y_typed(&self) -> Length<T, U> {
|
||||
Length::new(self.min_y())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn intersection(&self, other: &Self) -> Option<Self> {
|
||||
if !self.intersects(other) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let upper_left = TypedPoint2D::new(max(self.min_x(), other.min_x()),
|
||||
max(self.min_y(), other.min_y()));
|
||||
let lower_right_x = min(self.max_x(), other.max_x());
|
||||
let lower_right_y = min(self.max_y(), other.max_y());
|
||||
|
||||
Some(TypedRect::new(upper_left, TypedSize2D::new(lower_right_x - upper_left.x,
|
||||
lower_right_y - upper_left.y)))
|
||||
}
|
||||
|
||||
/// Returns the same rectangle, translated by a vector.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn translate(&self, by: &TypedVector2D<T, U>) -> Self {
|
||||
Self::new(self.origin + *by, self.size)
|
||||
}
|
||||
|
||||
/// Returns true if this rectangle contains the point. Points are considered
|
||||
/// in the rectangle if they are on the left or top edge, but outside if they
|
||||
/// are on the right or bottom edge.
|
||||
#[inline]
|
||||
pub fn contains(&self, other: &TypedPoint2D<T, U>) -> bool {
|
||||
self.origin.x <= other.x && other.x < self.origin.x + self.size.width &&
|
||||
self.origin.y <= other.y && other.y < self.origin.y + self.size.height
|
||||
}
|
||||
|
||||
/// Returns true if this rectangle contains the interior of rect. Always
|
||||
/// returns true if rect is empty, and always returns false if rect is
|
||||
/// nonempty but this rectangle is empty.
|
||||
#[inline]
|
||||
pub fn contains_rect(&self, rect: &Self) -> bool {
|
||||
rect.is_empty() ||
|
||||
(self.min_x() <= rect.min_x() && rect.max_x() <= self.max_x() &&
|
||||
self.min_y() <= rect.min_y() && rect.max_y() <= self.max_y())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn inflate(&self, width: T, height: T) -> Self {
|
||||
TypedRect::new(
|
||||
TypedPoint2D::new(self.origin.x - width, self.origin.y - height),
|
||||
TypedSize2D::new(self.size.width + width + width, self.size.height + height + height),
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn inflate_typed(&self, width: Length<T, U>, height: Length<T, U>) -> Self {
|
||||
self.inflate(width.get(), height.get())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn top_right(&self) -> TypedPoint2D<T, U> {
|
||||
TypedPoint2D::new(self.max_x(), self.origin.y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn bottom_left(&self) -> TypedPoint2D<T, U> {
|
||||
TypedPoint2D::new(self.origin.x, self.max_y())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn bottom_right(&self) -> TypedPoint2D<T, U> {
|
||||
TypedPoint2D::new(self.max_x(), self.max_y())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn translate_by_size(&self, size: &TypedSize2D<T, U>) -> Self {
|
||||
self.translate(&size.to_vector())
|
||||
}
|
||||
|
||||
/// Returns the smallest rectangle containing the four points.
|
||||
pub fn from_points(points: &[TypedPoint2D<T, U>]) -> Self {
|
||||
if points.len() == 0 {
|
||||
return TypedRect::zero();
|
||||
}
|
||||
let (mut min_x, mut min_y) = (points[0].x, points[0].y);
|
||||
let (mut max_x, mut max_y) = (min_x, min_y);
|
||||
for point in &points[1..] {
|
||||
if point.x < min_x {
|
||||
min_x = point.x
|
||||
}
|
||||
if point.x > max_x {
|
||||
max_x = point.x
|
||||
}
|
||||
if point.y < min_y {
|
||||
min_y = point.y
|
||||
}
|
||||
if point.y > max_y {
|
||||
max_y = point.y
|
||||
}
|
||||
}
|
||||
TypedRect::new(TypedPoint2D::new(min_x, min_y),
|
||||
TypedSize2D::new(max_x - min_x, max_y - min_y))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedRect<T, U>
|
||||
where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> {
|
||||
/// Linearly interpolate between this rectangle and another rectange.
|
||||
///
|
||||
/// `t` is expected to be between zero and one.
|
||||
#[inline]
|
||||
pub fn lerp(&self, other: Self, t: T) -> Self {
|
||||
Self::new(
|
||||
self.origin.lerp(other.origin, t),
|
||||
self.size.lerp(other.size, t),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedRect<T, U>
|
||||
where T: Copy + Clone + PartialOrd + Add<T, Output=T> + Sub<T, Output=T> + Zero {
|
||||
#[inline]
|
||||
pub fn union(&self, other: &Self) -> Self {
|
||||
if self.size == Zero::zero() {
|
||||
return *other;
|
||||
}
|
||||
if other.size == Zero::zero() {
|
||||
return *self;
|
||||
}
|
||||
|
||||
let upper_left = TypedPoint2D::new(min(self.min_x(), other.min_x()),
|
||||
min(self.min_y(), other.min_y()));
|
||||
|
||||
let lower_right_x = max(self.max_x(), other.max_x());
|
||||
let lower_right_y = max(self.max_y(), other.max_y());
|
||||
|
||||
TypedRect::new(
|
||||
upper_left,
|
||||
TypedSize2D::new(lower_right_x - upper_left.x, lower_right_y - upper_left.y)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedRect<T, U> {
|
||||
#[inline]
|
||||
pub fn scale<Scale: Copy>(&self, x: Scale, y: Scale) -> Self
|
||||
where T: Copy + Clone + Mul<Scale, Output=T> {
|
||||
TypedRect::new(
|
||||
TypedPoint2D::new(self.origin.x * x, self.origin.y * y),
|
||||
TypedSize2D::new(self.size.width * x, self.size.height * y)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + PartialEq + Zero, U> TypedRect<T, U> {
|
||||
/// Constructor, setting all sides to zero.
|
||||
pub fn zero() -> Self {
|
||||
TypedRect::new(
|
||||
TypedPoint2D::origin(),
|
||||
TypedSize2D::zero(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns true if the size is zero, regardless of the origin's value.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size.width == Zero::zero() || self.size.height == Zero::zero()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn min<T: Clone + PartialOrd>(x: T, y: T) -> T {
|
||||
if x <= y { x } else { y }
|
||||
}
|
||||
|
||||
pub fn max<T: Clone + PartialOrd>(x: T, y: T) -> T {
|
||||
if x >= y { x } else { y }
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedRect<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn mul(self, scale: T) -> Self {
|
||||
TypedRect::new(self.origin * scale, self.size * scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedRect<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn div(self, scale: T) -> Self {
|
||||
TypedRect::new(self.origin / scale, self.size / scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U1, U2> Mul<ScaleFactor<T, U1, U2>> for TypedRect<T, U1> {
|
||||
type Output = TypedRect<T, U2>;
|
||||
#[inline]
|
||||
fn mul(self, scale: ScaleFactor<T, U1, U2>) -> TypedRect<T, U2> {
|
||||
TypedRect::new(self.origin * scale, self.size * scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U1, U2> Div<ScaleFactor<T, U1, U2>> for TypedRect<T, U2> {
|
||||
type Output = TypedRect<T, U1>;
|
||||
#[inline]
|
||||
fn div(self, scale: ScaleFactor<T, U1, U2>) -> TypedRect<T, U1> {
|
||||
TypedRect::new(self.origin / scale, self.size / scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, Unit> TypedRect<T, Unit> {
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
pub fn to_untyped(&self) -> Rect<T> {
|
||||
TypedRect::new(self.origin.to_untyped(), self.size.to_untyped())
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
pub fn from_untyped(r: &Rect<T>) -> TypedRect<T, Unit> {
|
||||
TypedRect::new(TypedPoint2D::from_untyped(&r.origin), TypedSize2D::from_untyped(&r.size))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T0: NumCast + Copy, Unit> TypedRect<T0, Unit> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
///
|
||||
/// When casting from floating point to integer coordinates, the decimals are truncated
|
||||
/// as one would expect from a simple cast, but this behavior does not always make sense
|
||||
/// geometrically. Consider using round(), round_in or round_out() before casting.
|
||||
pub fn cast<T1: NumCast + Copy>(&self) -> Option<TypedRect<T1, Unit>> {
|
||||
match (self.origin.cast(), self.size.cast()) {
|
||||
(Some(origin), Some(size)) => Some(TypedRect::new(origin, size)),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Floor + Ceil + Round + Add<T, Output=T> + Sub<T, Output=T>, U> TypedRect<T, U> {
|
||||
/// Return a rectangle with edges rounded to integer coordinates, such that
|
||||
/// the returned rectangle has the same set of pixel centers as the original
|
||||
/// one.
|
||||
/// Edges at offset 0.5 round up.
|
||||
/// Suitable for most places where integral device coordinates
|
||||
/// are needed, but note that any translation should be applied first to
|
||||
/// avoid pixel rounding errors.
|
||||
/// Note that this is *not* rounding to nearest integer if the values are negative.
|
||||
/// They are always rounding as floor(n + 0.5).
|
||||
#[must_use]
|
||||
pub fn round(&self) -> Self {
|
||||
let origin = self.origin.round();
|
||||
let size = self.origin.add_size(&self.size).round() - origin;
|
||||
TypedRect::new(origin, TypedSize2D::new(size.x, size.y))
|
||||
}
|
||||
|
||||
/// Return a rectangle with edges rounded to integer coordinates, such that
|
||||
/// the original rectangle contains the resulting rectangle.
|
||||
#[must_use]
|
||||
pub fn round_in(&self) -> Self {
|
||||
let origin = self.origin.ceil();
|
||||
let size = self.origin.add_size(&self.size).floor() - origin;
|
||||
TypedRect::new(origin, TypedSize2D::new(size.x, size.y))
|
||||
}
|
||||
|
||||
/// Return a rectangle with edges rounded to integer coordinates, such that
|
||||
/// the original rectangle is contained in the resulting rectangle.
|
||||
#[must_use]
|
||||
pub fn round_out(&self) -> Self {
|
||||
let origin = self.origin.floor();
|
||||
let size = self.origin.add_size(&self.size).ceil() - origin;
|
||||
TypedRect::new(origin, TypedSize2D::new(size.x, size.y))
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience functions for common casts
|
||||
impl<T: NumCast + Copy, Unit> TypedRect<T, Unit> {
|
||||
/// Cast into an `f32` rectangle.
|
||||
pub fn to_f32(&self) -> TypedRect<f32, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `usize` rectangle, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point rectangles, it is worth considering whether
|
||||
/// to `round()`, `round_in()` or `round_out()` before the cast in order to
|
||||
/// obtain the desired conversion behavior.
|
||||
pub fn to_usize(&self) -> TypedRect<usize, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i32` rectangle, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point rectangles, it is worth considering whether
|
||||
/// to `round()`, `round_in()` or `round_out()` before the cast in order to
|
||||
/// obtain the desired conversion behavior.
|
||||
pub fn to_i32(&self) -> TypedRect<i32, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i64` rectangle, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point rectangles, it is worth considering whether
|
||||
/// to `round()`, `round_in()` or `round_out()` before the cast in order to
|
||||
/// obtain the desired conversion behavior.
|
||||
pub fn to_i64(&self) -> TypedRect<i64, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// Shorthand for `TypedRect::new(TypedPoint2D::new(x, y), TypedSize2D::new(w, h))`.
|
||||
pub fn rect<T: Copy, U>(x: T, y: T, w: T, h: T) -> TypedRect<T, U> {
|
||||
TypedRect::new(TypedPoint2D::new(x, y), TypedSize2D::new(w, h))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use point::Point2D;
|
||||
use vector::vec2;
|
||||
use size::Size2D;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_min_max() {
|
||||
assert!(min(0u32, 1u32) == 0u32);
|
||||
assert!(min(-1.0f32, 0.0f32) == -1.0f32);
|
||||
|
||||
assert!(max(0u32, 1u32) == 1u32);
|
||||
assert!(max(-1.0f32, 0.0f32) == 0.0f32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_translate() {
|
||||
let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
|
||||
let pp = p.translate(&vec2(10,15));
|
||||
|
||||
assert!(pp.size.width == 50);
|
||||
assert!(pp.size.height == 40);
|
||||
assert!(pp.origin.x == 10);
|
||||
assert!(pp.origin.y == 15);
|
||||
|
||||
|
||||
let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
|
||||
let rr = r.translate(&vec2(0,-10));
|
||||
|
||||
assert!(rr.size.width == 50);
|
||||
assert!(rr.size.height == 40);
|
||||
assert!(rr.origin.x == -10);
|
||||
assert!(rr.origin.y == -15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_translate_by_size() {
|
||||
let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
|
||||
let pp = p.translate_by_size(&Size2D::new(10,15));
|
||||
|
||||
assert!(pp.size.width == 50);
|
||||
assert!(pp.size.height == 40);
|
||||
assert!(pp.origin.x == 10);
|
||||
assert!(pp.origin.y == 15);
|
||||
|
||||
|
||||
let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
|
||||
let rr = r.translate_by_size(&Size2D::new(0,-10));
|
||||
|
||||
assert!(rr.size.width == 50);
|
||||
assert!(rr.size.height == 40);
|
||||
assert!(rr.origin.x == -10);
|
||||
assert!(rr.origin.y == -15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_union() {
|
||||
let p = Rect::new(Point2D::new(0, 0), Size2D::new(50, 40));
|
||||
let q = Rect::new(Point2D::new(20,20), Size2D::new(5, 5));
|
||||
let r = Rect::new(Point2D::new(-15, -30), Size2D::new(200, 15));
|
||||
let s = Rect::new(Point2D::new(20, -15), Size2D::new(250, 200));
|
||||
|
||||
let pq = p.union(&q);
|
||||
assert!(pq.origin == Point2D::new(0, 0));
|
||||
assert!(pq.size == Size2D::new(50, 40));
|
||||
|
||||
let pr = p.union(&r);
|
||||
assert!(pr.origin == Point2D::new(-15, -30));
|
||||
assert!(pr.size == Size2D::new(200, 70));
|
||||
|
||||
let ps = p.union(&s);
|
||||
assert!(ps.origin == Point2D::new(0, -15));
|
||||
assert!(ps.size == Size2D::new(270, 200));
|
||||
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_intersection() {
|
||||
let p = Rect::new(Point2D::new(0, 0), Size2D::new(10, 20));
|
||||
let q = Rect::new(Point2D::new(5, 15), Size2D::new(10, 10));
|
||||
let r = Rect::new(Point2D::new(-5, -5), Size2D::new(8, 8));
|
||||
|
||||
let pq = p.intersection(&q);
|
||||
assert!(pq.is_some());
|
||||
let pq = pq.unwrap();
|
||||
assert!(pq.origin == Point2D::new(5, 15));
|
||||
assert!(pq.size == Size2D::new(5, 5));
|
||||
|
||||
let pr = p.intersection(&r);
|
||||
assert!(pr.is_some());
|
||||
let pr = pr.unwrap();
|
||||
assert!(pr.origin == Point2D::new(0, 0));
|
||||
assert!(pr.size == Size2D::new(3, 3));
|
||||
|
||||
let qr = q.intersection(&r);
|
||||
assert!(qr.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_contains() {
|
||||
let r = Rect::new(Point2D::new(-20, 15), Size2D::new(100, 200));
|
||||
|
||||
assert!(r.contains(&Point2D::new(0, 50)));
|
||||
assert!(r.contains(&Point2D::new(-10, 200)));
|
||||
|
||||
// The `contains` method is inclusive of the top/left edges, but not the
|
||||
// bottom/right edges.
|
||||
assert!(r.contains(&Point2D::new(-20, 15)));
|
||||
assert!(!r.contains(&Point2D::new(80, 15)));
|
||||
assert!(!r.contains(&Point2D::new(80, 215)));
|
||||
assert!(!r.contains(&Point2D::new(-20, 215)));
|
||||
|
||||
// Points beyond the top-left corner.
|
||||
assert!(!r.contains(&Point2D::new(-25, 15)));
|
||||
assert!(!r.contains(&Point2D::new(-15, 10)));
|
||||
|
||||
// Points beyond the top-right corner.
|
||||
assert!(!r.contains(&Point2D::new(85, 20)));
|
||||
assert!(!r.contains(&Point2D::new(75, 10)));
|
||||
|
||||
// Points beyond the bottom-right corner.
|
||||
assert!(!r.contains(&Point2D::new(85, 210)));
|
||||
assert!(!r.contains(&Point2D::new(75, 220)));
|
||||
|
||||
// Points beyond the bottom-left corner.
|
||||
assert!(!r.contains(&Point2D::new(-25, 210)));
|
||||
assert!(!r.contains(&Point2D::new(-15, 220)));
|
||||
|
||||
let r = Rect::new(Point2D::new(-20.0, 15.0), Size2D::new(100.0, 200.0));
|
||||
assert!(r.contains_rect(&r));
|
||||
assert!(!r.contains_rect(&r.translate(&vec2( 0.1, 0.0))));
|
||||
assert!(!r.contains_rect(&r.translate(&vec2(-0.1, 0.0))));
|
||||
assert!(!r.contains_rect(&r.translate(&vec2( 0.0, 0.1))));
|
||||
assert!(!r.contains_rect(&r.translate(&vec2( 0.0, -0.1))));
|
||||
// Empty rectangles are always considered as contained in other rectangles,
|
||||
// even if their origin is not.
|
||||
let p = Point2D::new(1.0, 1.0);
|
||||
assert!(!r.contains(&p));
|
||||
assert!(r.contains_rect(&Rect::new(p, Size2D::zero())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scale() {
|
||||
let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
|
||||
let pp = p.scale(10, 15);
|
||||
|
||||
assert!(pp.size.width == 500);
|
||||
assert!(pp.size.height == 600);
|
||||
assert!(pp.origin.x == 0);
|
||||
assert!(pp.origin.y == 0);
|
||||
|
||||
let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
|
||||
let rr = r.scale(1, 20);
|
||||
|
||||
assert!(rr.size.width == 50);
|
||||
assert!(rr.size.height == 800);
|
||||
assert!(rr.origin.x == -10);
|
||||
assert!(rr.origin.y == -100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inflate() {
|
||||
let p = Rect::new(Point2D::new(0, 0), Size2D::new(10, 10));
|
||||
let pp = p.inflate(10, 20);
|
||||
|
||||
assert!(pp.size.width == 30);
|
||||
assert!(pp.size.height == 50);
|
||||
assert!(pp.origin.x == -10);
|
||||
assert!(pp.origin.y == -20);
|
||||
|
||||
let r = Rect::new(Point2D::new(0, 0), Size2D::new(10, 20));
|
||||
let rr = r.inflate(-2, -5);
|
||||
|
||||
assert!(rr.size.width == 6);
|
||||
assert!(rr.size.height == 10);
|
||||
assert!(rr.origin.x == 2);
|
||||
assert!(rr.origin.y == 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_min_max_x_y() {
|
||||
let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
|
||||
assert!(p.max_y() == 40);
|
||||
assert!(p.min_y() == 0);
|
||||
assert!(p.max_x() == 50);
|
||||
assert!(p.min_x() == 0);
|
||||
|
||||
let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40));
|
||||
assert!(r.max_y() == 35);
|
||||
assert!(r.min_y() == -5);
|
||||
assert!(r.max_x() == 40);
|
||||
assert!(r.min_x() == -10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_empty() {
|
||||
assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(0u32, 0u32)).is_empty());
|
||||
assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(10u32, 0u32)).is_empty());
|
||||
assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(0u32, 10u32)).is_empty());
|
||||
assert!(!Rect::new(Point2D::new(0u32, 0u32), Size2D::new(1u32, 1u32)).is_empty());
|
||||
assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(0u32, 0u32)).is_empty());
|
||||
assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(10u32, 0u32)).is_empty());
|
||||
assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(0u32, 10u32)).is_empty());
|
||||
assert!(!Rect::new(Point2D::new(10u32, 10u32), Size2D::new(1u32, 1u32)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_round() {
|
||||
let mut x = -2.0;
|
||||
let mut y = -2.0;
|
||||
let mut w = -2.0;
|
||||
let mut h = -2.0;
|
||||
while x < 2.0 {
|
||||
while y < 2.0 {
|
||||
while w < 2.0 {
|
||||
while h < 2.0 {
|
||||
let rect = Rect::new(Point2D::new(x, y), Size2D::new(w, h));
|
||||
|
||||
assert!(rect.contains_rect(&rect.round_in()));
|
||||
assert!(rect.round_in().inflate(1.0, 1.0).contains_rect(&rect));
|
||||
|
||||
assert!(rect.round_out().contains_rect(&rect));
|
||||
assert!(rect.inflate(1.0, 1.0).contains_rect(&rect.round_out()));
|
||||
|
||||
assert!(rect.inflate(1.0, 1.0).contains_rect(&rect.round()));
|
||||
assert!(rect.round().inflate(1.0, 1.0).contains_rect(&rect));
|
||||
|
||||
h += 0.1;
|
||||
}
|
||||
w += 0.1;
|
||||
}
|
||||
y += 0.1;
|
||||
}
|
||||
x += 0.1
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,171 +0,0 @@
|
|||
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
//! A type-checked scaling factor between units.
|
||||
|
||||
use num::One;
|
||||
|
||||
use heapsize::HeapSizeOf;
|
||||
use num_traits::NumCast;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt;
|
||||
use std::ops::{Add, Mul, Sub, Div};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
/// A scaling factor between two different units of measurement.
|
||||
///
|
||||
/// This is effectively a type-safe float, intended to be used in combination with other types like
|
||||
/// `length::Length` to enforce conversion between systems of measurement at compile time.
|
||||
///
|
||||
/// `Src` and `Dst` represent the units before and after multiplying a value by a `ScaleFactor`. They
|
||||
/// may be types without values, such as empty enums. For example:
|
||||
///
|
||||
/// ```rust
|
||||
/// use euclid::ScaleFactor;
|
||||
/// use euclid::Length;
|
||||
/// enum Mm {};
|
||||
/// enum Inch {};
|
||||
///
|
||||
/// let mm_per_inch: ScaleFactor<f32, Inch, Mm> = ScaleFactor::new(25.4);
|
||||
///
|
||||
/// let one_foot: Length<f32, Inch> = Length::new(12.0);
|
||||
/// let one_foot_in_mm: Length<f32, Mm> = one_foot * mm_per_inch;
|
||||
/// ```
|
||||
#[repr(C)]
|
||||
pub struct ScaleFactor<T, Src, Dst>(pub T, PhantomData<(Src, Dst)>);
|
||||
|
||||
impl<T: HeapSizeOf, Src, Dst> HeapSizeOf for ScaleFactor<T, Src, Dst> {
|
||||
fn heap_size_of_children(&self) -> usize {
|
||||
self.0.heap_size_of_children()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Src, Dst> Deserialize for ScaleFactor<T, Src, Dst> where T: Deserialize {
|
||||
fn deserialize<D>(deserializer: D) -> Result<ScaleFactor<T, Src, Dst>, D::Error>
|
||||
where D: Deserializer {
|
||||
Ok(ScaleFactor(try!(Deserialize::deserialize(deserializer)), PhantomData))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Src, Dst> Serialize for ScaleFactor<T, Src, Dst> where T: Serialize {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
|
||||
self.0.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Src, Dst> ScaleFactor<T, Src, Dst> {
|
||||
pub fn new(x: T) -> ScaleFactor<T, Src, Dst> {
|
||||
ScaleFactor(x, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone, Src, Dst> ScaleFactor<T, Src, Dst> {
|
||||
pub fn get(&self) -> T {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone + One + Div<T, Output=T>, Src, Dst> ScaleFactor<T, Src, Dst> {
|
||||
/// The inverse ScaleFactor (1.0 / self).
|
||||
pub fn inv(&self) -> ScaleFactor<T, Dst, Src> {
|
||||
let one: T = One::one();
|
||||
ScaleFactor::new(one / self.get())
|
||||
}
|
||||
}
|
||||
|
||||
// scale0 * scale1
|
||||
impl<T: Clone + Mul<T, Output=T>, A, B, C>
|
||||
Mul<ScaleFactor<T, B, C>> for ScaleFactor<T, A, B> {
|
||||
type Output = ScaleFactor<T, A, C>;
|
||||
#[inline]
|
||||
fn mul(self, other: ScaleFactor<T, B, C>) -> ScaleFactor<T, A, C> {
|
||||
ScaleFactor::new(self.get() * other.get())
|
||||
}
|
||||
}
|
||||
|
||||
// scale0 + scale1
|
||||
impl<T: Clone + Add<T, Output=T>, Src, Dst> Add for ScaleFactor<T, Src, Dst> {
|
||||
type Output = ScaleFactor<T, Src, Dst>;
|
||||
#[inline]
|
||||
fn add(self, other: ScaleFactor<T, Src, Dst>) -> ScaleFactor<T, Src, Dst> {
|
||||
ScaleFactor::new(self.get() + other.get())
|
||||
}
|
||||
}
|
||||
|
||||
// scale0 - scale1
|
||||
impl<T: Clone + Sub<T, Output=T>, Src, Dst> Sub for ScaleFactor<T, Src, Dst> {
|
||||
type Output = ScaleFactor<T, Src, Dst>;
|
||||
#[inline]
|
||||
fn sub(self, other: ScaleFactor<T, Src, Dst>) -> ScaleFactor<T, Src, Dst> {
|
||||
ScaleFactor::new(self.get() - other.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: NumCast + Clone, Src, Dst0> ScaleFactor<T, Src, Dst0> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
pub fn cast<T1: NumCast + Clone>(&self) -> Option<ScaleFactor<T1, Src, Dst0>> {
|
||||
NumCast::from(self.get()).map(ScaleFactor::new)
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: Switch to `derive(PartialEq, Clone)` after this Rust issue is fixed:
|
||||
// https://github.com/mozilla/rust/issues/7671
|
||||
|
||||
impl<T: PartialEq, Src, Dst> PartialEq for ScaleFactor<T, Src, Dst> {
|
||||
fn eq(&self, other: &ScaleFactor<T, Src, Dst>) -> bool {
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone, Src, Dst> Clone for ScaleFactor<T, Src, Dst> {
|
||||
fn clone(&self) -> ScaleFactor<T, Src, Dst> {
|
||||
ScaleFactor::new(self.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, Src, Dst> Copy for ScaleFactor<T, Src, Dst> {}
|
||||
|
||||
impl<T: fmt::Debug, Src, Dst> fmt::Debug for ScaleFactor<T, Src, Dst> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display, Src, Dst> fmt::Display for ScaleFactor<T, Src, Dst> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ScaleFactor;
|
||||
|
||||
enum Inch {}
|
||||
enum Cm {}
|
||||
enum Mm {}
|
||||
|
||||
#[test]
|
||||
fn test_scale_factor() {
|
||||
let mm_per_inch: ScaleFactor<f32, Inch, Mm> = ScaleFactor::new(25.4);
|
||||
let cm_per_mm: ScaleFactor<f32, Mm, Cm> = ScaleFactor::new(0.1);
|
||||
|
||||
let mm_per_cm: ScaleFactor<f32, Cm, Mm> = cm_per_mm.inv();
|
||||
assert_eq!(mm_per_cm.get(), 10.0);
|
||||
|
||||
let cm_per_inch: ScaleFactor<f32, Inch, Cm> = mm_per_inch * cm_per_mm;
|
||||
assert_eq!(cm_per_inch, ScaleFactor::new(2.54));
|
||||
|
||||
let a: ScaleFactor<isize, Inch, Inch> = ScaleFactor::new(2);
|
||||
let b: ScaleFactor<isize, Inch, Inch> = ScaleFactor::new(3);
|
||||
assert!(a != b);
|
||||
assert_eq!(a, a.clone());
|
||||
assert_eq!(a.clone() + b.clone(), ScaleFactor::new(5));
|
||||
assert_eq!(a - b, ScaleFactor::new(-1));
|
||||
}
|
||||
}
|
|
@ -1,283 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
//! A group of side offsets, which correspond to top/left/bottom/right for borders, padding,
|
||||
//! and margins in CSS.
|
||||
|
||||
use super::UnknownUnit;
|
||||
use length::Length;
|
||||
use num::Zero;
|
||||
use std::fmt;
|
||||
use std::ops::Add;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
use heapsize::HeapSizeOf;
|
||||
|
||||
/// A group of side offsets, which correspond to top/left/bottom/right for borders, padding,
|
||||
/// and margins in CSS, optionally tagged with a unit.
|
||||
define_matrix! {
|
||||
pub struct TypedSideOffsets2D<T, U> {
|
||||
pub top: T,
|
||||
pub right: T,
|
||||
pub bottom: T,
|
||||
pub left: T,
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for TypedSideOffsets2D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "({:?},{:?},{:?},{:?})",
|
||||
self.top, self.right, self.bottom, self.left)
|
||||
}
|
||||
}
|
||||
|
||||
/// The default side offset type with no unit.
|
||||
pub type SideOffsets2D<T> = TypedSideOffsets2D<T, UnknownUnit>;
|
||||
|
||||
impl<T: Copy, U> TypedSideOffsets2D<T, U> {
|
||||
/// Constructor taking a scalar for each side.
|
||||
pub fn new(top: T, right: T, bottom: T, left: T) -> Self {
|
||||
TypedSideOffsets2D {
|
||||
top: top,
|
||||
right: right,
|
||||
bottom: bottom,
|
||||
left: left,
|
||||
_unit: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructor taking a typed Length for each side.
|
||||
pub fn from_lengths(top: Length<T, U>,
|
||||
right: Length<T, U>,
|
||||
bottom: Length<T, U>,
|
||||
left: Length<T, U>) -> Self {
|
||||
TypedSideOffsets2D::new(top.0, right.0, bottom.0, left.0)
|
||||
}
|
||||
|
||||
/// Access self.top as a typed Length instead of a scalar value.
|
||||
pub fn top_typed(&self) -> Length<T, U> { Length::new(self.top) }
|
||||
|
||||
/// Access self.right as a typed Length instead of a scalar value.
|
||||
pub fn right_typed(&self) -> Length<T, U> { Length::new(self.right) }
|
||||
|
||||
/// Access self.bottom as a typed Length instead of a scalar value.
|
||||
pub fn bottom_typed(&self) -> Length<T, U> { Length::new(self.bottom) }
|
||||
|
||||
/// Access self.left as a typed Length instead of a scalar value.
|
||||
pub fn left_typed(&self) -> Length<T, U> { Length::new(self.left) }
|
||||
|
||||
/// Constructor setting the same value to all sides, taking a scalar value directly.
|
||||
pub fn new_all_same(all: T) -> Self {
|
||||
TypedSideOffsets2D::new(all, all, all, all)
|
||||
}
|
||||
|
||||
/// Constructor setting the same value to all sides, taking a typed Length.
|
||||
pub fn from_length_all_same(all: Length<T, U>) -> Self {
|
||||
TypedSideOffsets2D::new_all_same(all.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedSideOffsets2D<T, U> where T: Add<T, Output=T> + Copy {
|
||||
pub fn horizontal(&self) -> T {
|
||||
self.left + self.right
|
||||
}
|
||||
|
||||
pub fn vertical(&self) -> T {
|
||||
self.top + self.bottom
|
||||
}
|
||||
|
||||
pub fn horizontal_typed(&self) -> Length<T, U> {
|
||||
Length::new(self.horizontal())
|
||||
}
|
||||
|
||||
pub fn vertical_typed(&self) -> Length<T, U> {
|
||||
Length::new(self.vertical())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Add for TypedSideOffsets2D<T, U> where T : Copy + Add<T, Output=T> {
|
||||
type Output = Self;
|
||||
fn add(self, other: Self) -> Self {
|
||||
TypedSideOffsets2D::new(
|
||||
self.top + other.top,
|
||||
self.right + other.right,
|
||||
self.bottom + other.bottom,
|
||||
self.left + other.left,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Zero, U> TypedSideOffsets2D<T, U> {
|
||||
/// Constructor, setting all sides to zero.
|
||||
pub fn zero() -> Self {
|
||||
TypedSideOffsets2D::new(
|
||||
Zero::zero(),
|
||||
Zero::zero(),
|
||||
Zero::zero(),
|
||||
Zero::zero(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A SIMD enabled version of TypedSideOffsets2D specialized for i32.
|
||||
#[cfg(feature = "unstable")]
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
#[repr(simd)]
|
||||
pub struct SideOffsets2DSimdI32 {
|
||||
pub top: i32,
|
||||
pub bottom: i32,
|
||||
pub right: i32,
|
||||
pub left: i32,
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl HeapSizeOf for SideOffsets2DSimdI32 {
|
||||
fn heap_size_of_children(&self) -> usize { 0 }
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl SideOffsets2DSimdI32 {
|
||||
#[inline]
|
||||
pub fn new(top: i32, right: i32, bottom: i32, left: i32) -> SideOffsets2DSimdI32 {
|
||||
SideOffsets2DSimdI32 {
|
||||
top: top,
|
||||
bottom: bottom,
|
||||
right: right,
|
||||
left: left,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl SideOffsets2DSimdI32 {
|
||||
#[inline]
|
||||
pub fn new_all_same(all: i32) -> SideOffsets2DSimdI32 {
|
||||
SideOffsets2DSimdI32::new(all.clone(), all.clone(), all.clone(), all.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl SideOffsets2DSimdI32 {
|
||||
#[inline]
|
||||
pub fn horizontal(&self) -> i32 {
|
||||
self.left + self.right
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn vertical(&self) -> i32 {
|
||||
self.top + self.bottom
|
||||
}
|
||||
}
|
||||
|
||||
/*impl Add for SideOffsets2DSimdI32 {
|
||||
type Output = SideOffsets2DSimdI32;
|
||||
#[inline]
|
||||
fn add(self, other: SideOffsets2DSimdI32) -> SideOffsets2DSimdI32 {
|
||||
self + other // Use SIMD addition
|
||||
}
|
||||
}*/
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl SideOffsets2DSimdI32 {
|
||||
#[inline]
|
||||
pub fn zero() -> SideOffsets2DSimdI32 {
|
||||
SideOffsets2DSimdI32 {
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
left: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
#[inline]
|
||||
pub fn is_zero(&self) -> bool {
|
||||
self.top == 0 && self.right == 0 && self.bottom == 0 && self.left == 0
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[inline]
|
||||
pub fn is_zero(&self) -> bool {
|
||||
let is_zero: bool;
|
||||
unsafe {
|
||||
asm! {
|
||||
"ptest $1, $1
|
||||
setz $0"
|
||||
: "=r"(is_zero)
|
||||
: "x"(*self)
|
||||
:
|
||||
: "intel"
|
||||
};
|
||||
}
|
||||
is_zero
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SideOffsets2DSimdI32;
|
||||
|
||||
#[test]
|
||||
fn test_is_zero() {
|
||||
assert!(SideOffsets2DSimdI32::new_all_same(0).is_zero());
|
||||
assert!(!SideOffsets2DSimdI32::new_all_same(1).is_zero());
|
||||
assert!(!SideOffsets2DSimdI32::new(1, 0, 0, 0).is_zero());
|
||||
assert!(!SideOffsets2DSimdI32::new(0, 1, 0, 0).is_zero());
|
||||
assert!(!SideOffsets2DSimdI32::new(0, 0, 1, 0).is_zero());
|
||||
assert!(!SideOffsets2DSimdI32::new(0, 0, 0, 1).is_zero());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg(bench)]
|
||||
mod bench {
|
||||
use test::BenchHarness;
|
||||
use std::num::Zero;
|
||||
use rand::{XorShiftRng, Rng};
|
||||
use super::SideOffsets2DSimdI32;
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[bench]
|
||||
fn bench_naive_is_zero(bh: &mut BenchHarness) {
|
||||
fn is_zero(x: &SideOffsets2DSimdI32) -> bool {
|
||||
x.top.is_zero() && x.right.is_zero() && x.bottom.is_zero() && x.left.is_zero()
|
||||
}
|
||||
let mut rng = XorShiftRng::new().unwrap();
|
||||
bh.iter(|| is_zero(&rng.gen::<SideOffsets2DSimdI32>()))
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_is_zero(bh: &mut BenchHarness) {
|
||||
let mut rng = XorShiftRng::new().unwrap();
|
||||
bh.iter(|| rng.gen::<SideOffsets2DSimdI32>().is_zero())
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_naive_add(bh: &mut BenchHarness) {
|
||||
fn add(x: &SideOffsets2DSimdI32, y: &SideOffsets2DSimdI32) -> SideOffsets2DSimdI32 {
|
||||
SideOffsets2DSimdI32 {
|
||||
top: x.top + y.top,
|
||||
right: x.right + y.right,
|
||||
bottom: x.bottom + y.bottom,
|
||||
left: x.left + y.left,
|
||||
}
|
||||
}
|
||||
let mut rng = XorShiftRng::new().unwrap();
|
||||
bh.iter(|| add(&rng.gen::<SideOffsets2DSimdI32>(), &rng.gen::<SideOffsets2DSimdI32>()))
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_add(bh: &mut BenchHarness) {
|
||||
let mut rng = XorShiftRng::new().unwrap();
|
||||
bh.iter(|| rng.gen::<SideOffsets2DSimdI32>() + rng.gen::<SideOffsets2DSimdI32>())
|
||||
}
|
||||
}
|
|
@ -1,294 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use super::UnknownUnit;
|
||||
use length::Length;
|
||||
use scale_factor::ScaleFactor;
|
||||
use vector::{TypedVector2D, vec2};
|
||||
use num::*;
|
||||
|
||||
use num_traits::NumCast;
|
||||
use std::fmt;
|
||||
use std::ops::{Add, Div, Mul, Sub};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
/// A 2d size tagged with a unit.
|
||||
define_matrix! {
|
||||
pub struct TypedSize2D<T, U> {
|
||||
pub width: T,
|
||||
pub height: T,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default 2d size type with no unit.
|
||||
///
|
||||
/// `Size2D` provides the same methods as `TypedSize2D`.
|
||||
pub type Size2D<T> = TypedSize2D<T, UnknownUnit>;
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for TypedSize2D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{:?}×{:?}", self.width, self.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display, U> fmt::Display for TypedSize2D<T, U> {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "({}x{})", self.width, self.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedSize2D<T, U> {
|
||||
/// Constructor taking scalar values.
|
||||
pub fn new(width: T, height: T) -> Self {
|
||||
TypedSize2D {
|
||||
width: width,
|
||||
height: height,
|
||||
_unit: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone, U> TypedSize2D<T, U> {
|
||||
/// Constructor taking scalar strongly typed lengths.
|
||||
pub fn from_lengths(width: Length<T, U>, height: Length<T, U>) -> Self {
|
||||
TypedSize2D::new(width.get(), height.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Round, U> TypedSize2D<T, U> {
|
||||
/// Rounds each component to the nearest integer value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
pub fn round(&self) -> Self {
|
||||
TypedSize2D::new(self.width.round(), self.height.round())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Ceil, U> TypedSize2D<T, U> {
|
||||
/// Rounds each component to the smallest integer equal or greater than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
pub fn ceil(&self) -> Self {
|
||||
TypedSize2D::new(self.width.ceil(), self.height.ceil())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Floor, U> TypedSize2D<T, U> {
|
||||
/// Rounds each component to the biggest integer equal or lower than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
pub fn floor(&self) -> Self {
|
||||
TypedSize2D::new(self.width.floor(), self.height.floor())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> Add for TypedSize2D<T, U> {
|
||||
type Output = Self;
|
||||
fn add(self, other: Self) -> Self {
|
||||
TypedSize2D::new(self.width + other.width, self.height + other.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedSize2D<T, U> {
|
||||
type Output = Self;
|
||||
fn sub(self, other: Self) -> Self {
|
||||
TypedSize2D::new(self.width - other.width, self.height - other.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Clone + Mul<T, Output=U>, U> TypedSize2D<T, U> {
|
||||
pub fn area(&self) -> U { self.width * self.height }
|
||||
}
|
||||
|
||||
impl<T, U> TypedSize2D<T, U>
|
||||
where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> {
|
||||
/// Linearly interpolate between this size and another size.
|
||||
///
|
||||
/// `t` is expected to be between zero and one.
|
||||
#[inline]
|
||||
pub fn lerp(&self, other: Self, t: T) -> Self {
|
||||
let one_t = T::one() - t;
|
||||
size2(
|
||||
one_t * self.width + t * other.width,
|
||||
one_t * self.height + t * other.height,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Zero, U> TypedSize2D<T, U> {
|
||||
pub fn zero() -> Self {
|
||||
TypedSize2D::new(
|
||||
Zero::zero(),
|
||||
Zero::zero(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Zero, U> Zero for TypedSize2D<T, U> {
|
||||
fn zero() -> Self {
|
||||
TypedSize2D::new(
|
||||
Zero::zero(),
|
||||
Zero::zero(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedSize2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn mul(self, scale: T) -> Self {
|
||||
TypedSize2D::new(self.width * scale, self.height * scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedSize2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn div(self, scale: T) -> Self {
|
||||
TypedSize2D::new(self.width / scale, self.height / scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U1, U2> Mul<ScaleFactor<T, U1, U2>> for TypedSize2D<T, U1> {
|
||||
type Output = TypedSize2D<T, U2>;
|
||||
#[inline]
|
||||
fn mul(self, scale: ScaleFactor<T, U1, U2>) -> TypedSize2D<T, U2> {
|
||||
TypedSize2D::new(self.width * scale.get(), self.height * scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U1, U2> Div<ScaleFactor<T, U1, U2>> for TypedSize2D<T, U2> {
|
||||
type Output = TypedSize2D<T, U1>;
|
||||
#[inline]
|
||||
fn div(self, scale: ScaleFactor<T, U1, U2>) -> TypedSize2D<T, U1> {
|
||||
TypedSize2D::new(self.width / scale.get(), self.height / scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> TypedSize2D<T, U> {
|
||||
/// Returns self.width as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn width_typed(&self) -> Length<T, U> { Length::new(self.width) }
|
||||
|
||||
/// Returns self.height as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn height_typed(&self) -> Length<T, U> { Length::new(self.height) }
|
||||
|
||||
#[inline]
|
||||
pub fn to_array(&self) -> [T; 2] { [self.width, self.height] }
|
||||
|
||||
#[inline]
|
||||
pub fn to_vector(&self) -> TypedVector2D<T, U> { vec2(self.width, self.height) }
|
||||
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
pub fn to_untyped(&self) -> Size2D<T> {
|
||||
TypedSize2D::new(self.width, self.height)
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
pub fn from_untyped(p: &Size2D<T>) -> Self {
|
||||
TypedSize2D::new(p.width, p.height)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: NumCast + Copy, Unit> TypedSize2D<T, Unit> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
///
|
||||
/// When casting from floating point to integer coordinates, the decimals are truncated
|
||||
/// as one would expect from a simple cast, but this behavior does not always make sense
|
||||
/// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
|
||||
pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedSize2D<NewT, Unit>> {
|
||||
match (NumCast::from(self.width), NumCast::from(self.height)) {
|
||||
(Some(w), Some(h)) => Some(TypedSize2D::new(w, h)),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience functions for common casts
|
||||
|
||||
/// Cast into an `f32` size.
|
||||
pub fn to_f32(&self) -> TypedSize2D<f32, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `uint` size, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point sizes, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
pub fn to_usize(&self) -> TypedSize2D<usize, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i32` size, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point sizes, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
pub fn to_i32(&self) -> TypedSize2D<i32, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i64` size, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating point sizes, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
pub fn to_i64(&self) -> TypedSize2D<i64, Unit> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// Shorthand for `TypedSize2D::new(w, h)`.
|
||||
pub fn size2<T, U>(w: T, h: T) -> TypedSize2D<T, U> {
|
||||
TypedSize2D::new(w, h)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod size2d {
|
||||
use super::Size2D;
|
||||
|
||||
#[test]
|
||||
pub fn test_add() {
|
||||
let p1 = Size2D::new(1.0, 2.0);
|
||||
let p2 = Size2D::new(3.0, 4.0);
|
||||
assert_eq!(p1 + p2, Size2D::new(4.0, 6.0));
|
||||
|
||||
let p1 = Size2D::new(1.0, 2.0);
|
||||
let p2 = Size2D::new(0.0, 0.0);
|
||||
assert_eq!(p1 + p2, Size2D::new(1.0, 2.0));
|
||||
|
||||
let p1 = Size2D::new(1.0, 2.0);
|
||||
let p2 = Size2D::new(-3.0, -4.0);
|
||||
assert_eq!(p1 + p2, Size2D::new(-2.0, -2.0));
|
||||
|
||||
let p1 = Size2D::new(0.0, 0.0);
|
||||
let p2 = Size2D::new(0.0, 0.0);
|
||||
assert_eq!(p1 + p2, Size2D::new(0.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_sub() {
|
||||
let p1 = Size2D::new(1.0, 2.0);
|
||||
let p2 = Size2D::new(3.0, 4.0);
|
||||
assert_eq!(p1 - p2, Size2D::new(-2.0, -2.0));
|
||||
|
||||
let p1 = Size2D::new(1.0, 2.0);
|
||||
let p2 = Size2D::new(0.0, 0.0);
|
||||
assert_eq!(p1 - p2, Size2D::new(1.0, 2.0));
|
||||
|
||||
let p1 = Size2D::new(1.0, 2.0);
|
||||
let p2 = Size2D::new(-3.0, -4.0);
|
||||
assert_eq!(p1 - p2, Size2D::new(4.0, 6.0));
|
||||
|
||||
let p1 = Size2D::new(0.0, 0.0);
|
||||
let p2 = Size2D::new(0.0, 0.0);
|
||||
assert_eq!(p1 - p2, Size2D::new(0.0, 0.0));
|
||||
}
|
||||
}
|
|
@ -1,488 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use super::{UnknownUnit, Radians};
|
||||
use num::{One, Zero};
|
||||
use point::TypedPoint2D;
|
||||
use vector::{TypedVector2D, vec2};
|
||||
use rect::TypedRect;
|
||||
use std::ops::{Add, Mul, Div, Sub};
|
||||
use std::marker::PhantomData;
|
||||
use approxeq::ApproxEq;
|
||||
use trig::Trig;
|
||||
use std::fmt;
|
||||
|
||||
define_matrix! {
|
||||
/// A 2d transform stored as a 2 by 3 matrix in row-major order in memory.
|
||||
///
|
||||
/// Transforms can be parametrized over the source and destination units, to describe a
|
||||
/// transformation from a space to another.
|
||||
/// For example, `TypedTransform2D<f32, WordSpace, ScreenSpace>::transform_point4d`
|
||||
/// takes a `TypedPoint2D<f32, WordSpace>` and returns a `TypedPoint2D<f32, ScreenSpace>`.
|
||||
///
|
||||
/// Transforms expose a set of convenience methods for pre- and post-transformations.
|
||||
/// A pre-transformation corresponds to adding an operation that is applied before
|
||||
/// the rest of the transformation, while a post-transformation adds an operation
|
||||
/// that is applied after.
|
||||
pub struct TypedTransform2D<T, Src, Dst> {
|
||||
pub m11: T, pub m12: T,
|
||||
pub m21: T, pub m22: T,
|
||||
pub m31: T, pub m32: T,
|
||||
}
|
||||
}
|
||||
|
||||
/// The default 2d transform type with no units.
|
||||
pub type Transform2D<T> = TypedTransform2D<T, UnknownUnit, UnknownUnit>;
|
||||
|
||||
impl<T: Copy, Src, Dst> TypedTransform2D<T, Src, Dst> {
|
||||
/// Create a transform specifying its matrix elements in row-major order.
|
||||
pub fn row_major(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> Self {
|
||||
TypedTransform2D {
|
||||
m11: m11, m12: m12,
|
||||
m21: m21, m22: m22,
|
||||
m31: m31, m32: m32,
|
||||
_unit: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a transform specifying its matrix elements in column-major order.
|
||||
pub fn column_major(m11: T, m21: T, m31: T, m12: T, m22: T, m32: T) -> Self {
|
||||
TypedTransform2D {
|
||||
m11: m11, m12: m12,
|
||||
m21: m21, m22: m22,
|
||||
m31: m31, m32: m32,
|
||||
_unit: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an array containing this transform's terms in row-major order (the order
|
||||
/// in which the transform is actually laid out in memory).
|
||||
pub fn to_row_major_array(&self) -> [T; 6] {
|
||||
[
|
||||
self.m11, self.m12,
|
||||
self.m21, self.m22,
|
||||
self.m31, self.m32
|
||||
]
|
||||
}
|
||||
|
||||
/// Returns an array containing this transform's terms in column-major order.
|
||||
pub fn to_column_major_array(&self) -> [T; 6] {
|
||||
[
|
||||
self.m11, self.m21, self.m31,
|
||||
self.m12, self.m22, self.m32
|
||||
]
|
||||
}
|
||||
|
||||
/// Returns an array containing this transform's 3 rows in (in row-major order)
|
||||
/// as arrays.
|
||||
///
|
||||
/// This is a convenience method to interface with other libraries like glium.
|
||||
pub fn to_row_arrays(&self) -> [[T; 2]; 3] {
|
||||
[
|
||||
[self.m11, self.m12],
|
||||
[self.m21, self.m22],
|
||||
[self.m31, self.m32],
|
||||
]
|
||||
}
|
||||
|
||||
/// Creates a transform from an array of 6 elements in row-major order.
|
||||
pub fn from_row_major_array(array: [T; 6]) -> Self {
|
||||
Self::row_major(
|
||||
array[0], array[1],
|
||||
array[2], array[3],
|
||||
array[4], array[5],
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a transform from 3 rows of 2 elements (row-major order).
|
||||
pub fn from_row_arrays(array: [[T; 2]; 3]) -> Self {
|
||||
Self::row_major(
|
||||
array[0][0], array[0][1],
|
||||
array[1][0], array[1][1],
|
||||
array[2][0], array[2][1],
|
||||
)
|
||||
}
|
||||
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
pub fn to_untyped(&self) -> Transform2D<T> {
|
||||
Transform2D::row_major(
|
||||
self.m11, self.m12,
|
||||
self.m21, self.m22,
|
||||
self.m31, self.m32
|
||||
)
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
pub fn from_untyped(p: &Transform2D<T>) -> Self {
|
||||
TypedTransform2D::row_major(
|
||||
p.m11, p.m12,
|
||||
p.m21, p.m22,
|
||||
p.m31, p.m32
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Src, Dst> TypedTransform2D<T, Src, Dst>
|
||||
where T: Copy +
|
||||
PartialEq +
|
||||
One + Zero {
|
||||
pub fn identity() -> Self {
|
||||
let (_0, _1) = (Zero::zero(), One::one());
|
||||
TypedTransform2D::row_major(
|
||||
_1, _0,
|
||||
_0, _1,
|
||||
_0, _0
|
||||
)
|
||||
}
|
||||
|
||||
// Intentional not public, because it checks for exact equivalence
|
||||
// while most consumers will probably want some sort of approximate
|
||||
// equivalence to deal with floating-point errors.
|
||||
fn is_identity(&self) -> bool {
|
||||
*self == TypedTransform2D::identity()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Src, Dst> TypedTransform2D<T, Src, Dst>
|
||||
where T: Copy + Clone +
|
||||
Add<T, Output=T> +
|
||||
Mul<T, Output=T> +
|
||||
Div<T, Output=T> +
|
||||
Sub<T, Output=T> +
|
||||
Trig +
|
||||
PartialOrd +
|
||||
One + Zero {
|
||||
|
||||
/// Returns the multiplication of the two matrices such that mat's transformation
|
||||
/// applies after self's transformation.
|
||||
#[must_use]
|
||||
pub fn post_mul<NewDst>(&self, mat: &TypedTransform2D<T, Dst, NewDst>) -> TypedTransform2D<T, Src, NewDst> {
|
||||
TypedTransform2D::row_major(
|
||||
self.m11 * mat.m11 + self.m12 * mat.m21,
|
||||
self.m11 * mat.m12 + self.m12 * mat.m22,
|
||||
self.m21 * mat.m11 + self.m22 * mat.m21,
|
||||
self.m21 * mat.m12 + self.m22 * mat.m22,
|
||||
self.m31 * mat.m11 + self.m32 * mat.m21 + mat.m31,
|
||||
self.m31 * mat.m12 + self.m32 * mat.m22 + mat.m32,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the multiplication of the two matrices such that mat's transformation
|
||||
/// applies before self's transformation.
|
||||
#[must_use]
|
||||
pub fn pre_mul<NewSrc>(&self, mat: &TypedTransform2D<T, NewSrc, Src>) -> TypedTransform2D<T, NewSrc, Dst> {
|
||||
mat.post_mul(self)
|
||||
}
|
||||
|
||||
/// Returns a translation transform.
|
||||
pub fn create_translation(x: T, y: T) -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
TypedTransform2D::row_major(
|
||||
_1, _0,
|
||||
_0, _1,
|
||||
x, y
|
||||
)
|
||||
}
|
||||
|
||||
/// Applies a translation after self's transformation and returns the resulting transform.
|
||||
#[must_use]
|
||||
pub fn post_translate(&self, v: TypedVector2D<T, Dst>) -> Self {
|
||||
self.post_mul(&TypedTransform2D::create_translation(v.x, v.y))
|
||||
}
|
||||
|
||||
/// Applies a translation before self's transformation and returns the resulting transform.
|
||||
#[must_use]
|
||||
pub fn pre_translate(&self, v: TypedVector2D<T, Src>) -> Self {
|
||||
self.pre_mul(&TypedTransform2D::create_translation(v.x, v.y))
|
||||
}
|
||||
|
||||
/// Returns a scale transform.
|
||||
pub fn create_scale(x: T, y: T) -> Self {
|
||||
let _0 = Zero::zero();
|
||||
TypedTransform2D::row_major(
|
||||
x, _0,
|
||||
_0, y,
|
||||
_0, _0
|
||||
)
|
||||
}
|
||||
|
||||
/// Applies a scale after self's transformation and returns the resulting transform.
|
||||
#[must_use]
|
||||
pub fn post_scale(&self, x: T, y: T) -> Self {
|
||||
self.post_mul(&TypedTransform2D::create_scale(x, y))
|
||||
}
|
||||
|
||||
/// Applies a scale before self's transformation and returns the resulting transform.
|
||||
#[must_use]
|
||||
pub fn pre_scale(&self, x: T, y: T) -> Self {
|
||||
TypedTransform2D::row_major(
|
||||
self.m11 * x, self.m12,
|
||||
self.m21, self.m22 * y,
|
||||
self.m31, self.m32
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a rotation transform.
|
||||
pub fn create_rotation(theta: Radians<T>) -> Self {
|
||||
let _0 = Zero::zero();
|
||||
let cos = theta.get().cos();
|
||||
let sin = theta.get().sin();
|
||||
TypedTransform2D::row_major(
|
||||
cos, _0 - sin,
|
||||
sin, cos,
|
||||
_0, _0
|
||||
)
|
||||
}
|
||||
|
||||
/// Applies a rotation after self's transformation and returns the resulting transform.
|
||||
#[must_use]
|
||||
pub fn post_rotate(&self, theta: Radians<T>) -> Self {
|
||||
self.post_mul(&TypedTransform2D::create_rotation(theta))
|
||||
}
|
||||
|
||||
/// Applies a rotation after self's transformation and returns the resulting transform.
|
||||
#[must_use]
|
||||
pub fn pre_rotate(&self, theta: Radians<T>) -> Self {
|
||||
self.pre_mul(&TypedTransform2D::create_rotation(theta))
|
||||
}
|
||||
|
||||
/// Returns the given point transformed by this transform.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn transform_point(&self, point: &TypedPoint2D<T, Src>) -> TypedPoint2D<T, Dst> {
|
||||
TypedPoint2D::new(point.x * self.m11 + point.y * self.m21 + self.m31,
|
||||
point.x * self.m12 + point.y * self.m22 + self.m32)
|
||||
}
|
||||
|
||||
/// Returns the given vector transformed by this matrix.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn transform_vector(&self, vec: &TypedVector2D<T, Src>) -> TypedVector2D<T, Dst> {
|
||||
vec2(vec.x * self.m11 + vec.y * self.m21,
|
||||
vec.x * self.m12 + vec.y * self.m22)
|
||||
}
|
||||
|
||||
/// Returns a rectangle that encompasses the result of transforming the given rectangle by this
|
||||
/// transform.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn transform_rect(&self, rect: &TypedRect<T, Src>) -> TypedRect<T, Dst> {
|
||||
TypedRect::from_points(&[
|
||||
self.transform_point(&rect.origin),
|
||||
self.transform_point(&rect.top_right()),
|
||||
self.transform_point(&rect.bottom_left()),
|
||||
self.transform_point(&rect.bottom_right()),
|
||||
])
|
||||
}
|
||||
|
||||
/// Computes and returns the determinant of this transform.
|
||||
pub fn determinant(&self) -> T {
|
||||
self.m11 * self.m22 - self.m12 * self.m21
|
||||
}
|
||||
|
||||
/// Returns the inverse transform if possible.
|
||||
#[must_use]
|
||||
pub fn inverse(&self) -> Option<TypedTransform2D<T, Dst, Src>> {
|
||||
let det = self.determinant();
|
||||
|
||||
let _0: T = Zero::zero();
|
||||
let _1: T = One::one();
|
||||
|
||||
if det == _0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let inv_det = _1 / det;
|
||||
Some(TypedTransform2D::row_major(
|
||||
inv_det * self.m22,
|
||||
inv_det * (_0 - self.m12),
|
||||
inv_det * (_0 - self.m21),
|
||||
inv_det * self.m11,
|
||||
inv_det * (self.m21 * self.m32 - self.m22 * self.m31),
|
||||
inv_det * (self.m31 * self.m12 - self.m11 * self.m32),
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns the same transform with a different destination unit.
|
||||
#[inline]
|
||||
pub fn with_destination<NewDst>(&self) -> TypedTransform2D<T, Src, NewDst> {
|
||||
TypedTransform2D::row_major(
|
||||
self.m11, self.m12,
|
||||
self.m21, self.m22,
|
||||
self.m31, self.m32,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the same transform with a different source unit.
|
||||
#[inline]
|
||||
pub fn with_source<NewSrc>(&self) -> TypedTransform2D<T, NewSrc, Dst> {
|
||||
TypedTransform2D::row_major(
|
||||
self.m11, self.m12,
|
||||
self.m21, self.m22,
|
||||
self.m31, self.m32,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ApproxEq<T>, Src, Dst> TypedTransform2D<T, Src, Dst> {
|
||||
pub fn approx_eq(&self, other: &Self) -> bool {
|
||||
self.m11.approx_eq(&other.m11) && self.m12.approx_eq(&other.m12) &&
|
||||
self.m21.approx_eq(&other.m21) && self.m22.approx_eq(&other.m22) &&
|
||||
self.m31.approx_eq(&other.m31) && self.m32.approx_eq(&other.m32)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + fmt::Debug, Src, Dst> fmt::Debug for TypedTransform2D<T, Src, Dst>
|
||||
where T: Copy + fmt::Debug +
|
||||
PartialEq +
|
||||
One + Zero {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
if self.is_identity() {
|
||||
write!(f, "[I]")
|
||||
} else {
|
||||
self.to_row_major_array().fmt(f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use approxeq::ApproxEq;
|
||||
use point::Point2D;
|
||||
use Radians;
|
||||
|
||||
use std::f32::consts::FRAC_PI_2;
|
||||
|
||||
type Mat = Transform2D<f32>;
|
||||
|
||||
fn rad(v: f32) -> Radians<f32> { Radians::new(v) }
|
||||
|
||||
#[test]
|
||||
pub fn test_translation() {
|
||||
let t1 = Mat::create_translation(1.0, 2.0);
|
||||
let t2 = Mat::identity().pre_translate(vec2(1.0, 2.0));
|
||||
let t3 = Mat::identity().post_translate(vec2(1.0, 2.0));
|
||||
assert_eq!(t1, t2);
|
||||
assert_eq!(t1, t3);
|
||||
|
||||
assert_eq!(t1.transform_point(&Point2D::new(1.0, 1.0)), Point2D::new(2.0, 3.0));
|
||||
|
||||
assert_eq!(t1.post_mul(&t1), Mat::create_translation(2.0, 4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_rotation() {
|
||||
let r1 = Mat::create_rotation(rad(FRAC_PI_2));
|
||||
let r2 = Mat::identity().pre_rotate(rad(FRAC_PI_2));
|
||||
let r3 = Mat::identity().post_rotate(rad(FRAC_PI_2));
|
||||
assert_eq!(r1, r2);
|
||||
assert_eq!(r1, r3);
|
||||
|
||||
assert!(r1.transform_point(&Point2D::new(1.0, 2.0)).approx_eq(&Point2D::new(2.0, -1.0)));
|
||||
|
||||
assert!(r1.post_mul(&r1).approx_eq(&Mat::create_rotation(rad(FRAC_PI_2*2.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_scale() {
|
||||
let s1 = Mat::create_scale(2.0, 3.0);
|
||||
let s2 = Mat::identity().pre_scale(2.0, 3.0);
|
||||
let s3 = Mat::identity().post_scale(2.0, 3.0);
|
||||
assert_eq!(s1, s2);
|
||||
assert_eq!(s1, s3);
|
||||
|
||||
assert!(s1.transform_point(&Point2D::new(2.0, 2.0)).approx_eq(&Point2D::new(4.0, 6.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_column_major() {
|
||||
assert_eq!(
|
||||
Mat::row_major(
|
||||
1.0, 2.0,
|
||||
3.0, 4.0,
|
||||
5.0, 6.0
|
||||
),
|
||||
Mat::column_major(
|
||||
1.0, 3.0, 5.0,
|
||||
2.0, 4.0, 6.0,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_simple() {
|
||||
let m1 = Mat::identity();
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.approx_eq(&m2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_scale() {
|
||||
let m1 = Mat::create_scale(1.5, 0.3);
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.pre_mul(&m2).approx_eq(&Mat::identity()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_translate() {
|
||||
let m1 = Mat::create_translation(-132.0, 0.3);
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.pre_mul(&m2).approx_eq(&Mat::identity()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inverse_none() {
|
||||
assert!(Mat::create_scale(2.0, 0.0).inverse().is_none());
|
||||
assert!(Mat::create_scale(2.0, 2.0).inverse().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_pre_post() {
|
||||
let m1 = Transform2D::identity().post_scale(1.0, 2.0).post_translate(vec2(1.0, 2.0));
|
||||
let m2 = Transform2D::identity().pre_translate(vec2(1.0, 2.0)).pre_scale(1.0, 2.0);
|
||||
assert!(m1.approx_eq(&m2));
|
||||
|
||||
let r = Mat::create_rotation(rad(FRAC_PI_2));
|
||||
let t = Mat::create_translation(2.0, 3.0);
|
||||
|
||||
let a = Point2D::new(1.0, 1.0);
|
||||
|
||||
assert!(r.post_mul(&t).transform_point(&a).approx_eq(&Point2D::new(3.0, 2.0)));
|
||||
assert!(t.post_mul(&r).transform_point(&a).approx_eq(&Point2D::new(4.0, -3.0)));
|
||||
assert!(t.post_mul(&r).transform_point(&a).approx_eq(&r.transform_point(&t.transform_point(&a))));
|
||||
|
||||
assert!(r.pre_mul(&t).transform_point(&a).approx_eq(&Point2D::new(4.0, -3.0)));
|
||||
assert!(t.pre_mul(&r).transform_point(&a).approx_eq(&Point2D::new(3.0, 2.0)));
|
||||
assert!(t.pre_mul(&r).transform_point(&a).approx_eq(&t.transform_point(&r.transform_point(&a))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_size_of() {
|
||||
use std::mem::size_of;
|
||||
assert_eq!(size_of::<Transform2D<f32>>(), 6*size_of::<f32>());
|
||||
assert_eq!(size_of::<Transform2D<f64>>(), 6*size_of::<f64>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_identity() {
|
||||
let m1 = Transform2D::identity();
|
||||
assert!(m1.is_identity());
|
||||
let m2 = m1.post_translate(vec2(0.1, 0.0));
|
||||
assert!(!m2.is_identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_transform_vector() {
|
||||
// Translation does not apply to vectors.
|
||||
let m1 = Mat::create_translation(1.0, 1.0);
|
||||
let v1 = vec2(10.0, -10.0);
|
||||
assert_eq!(v1, m1.transform_vector(&v1));
|
||||
}
|
||||
}
|
|
@ -1,888 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use super::{UnknownUnit, Radians};
|
||||
use approxeq::ApproxEq;
|
||||
use trig::Trig;
|
||||
use point::{TypedPoint2D, TypedPoint3D, point2, point3};
|
||||
use vector::{TypedVector2D, TypedVector3D, vec2, vec3};
|
||||
use rect::TypedRect;
|
||||
use transform2d::TypedTransform2D;
|
||||
use scale_factor::ScaleFactor;
|
||||
use num::{One, Zero};
|
||||
use std::ops::{Add, Mul, Sub, Div, Neg};
|
||||
use std::marker::PhantomData;
|
||||
use std::fmt;
|
||||
|
||||
define_matrix! {
|
||||
/// A 3d transform stored as a 4 by 4 matrix in row-major order in memory.
|
||||
///
|
||||
/// Transforms can be parametrized over the source and destination units, to describe a
|
||||
/// transformation from a space to another.
|
||||
/// For example, `TypedTransform3D<f32, WordSpace, ScreenSpace>::transform_point3d`
|
||||
/// takes a `TypedPoint3D<f32, WordSpace>` and returns a `TypedPoint3D<f32, ScreenSpace>`.
|
||||
///
|
||||
/// Transforms expose a set of convenience methods for pre- and post-transformations.
|
||||
/// A pre-transformation corresponds to adding an operation that is applied before
|
||||
/// the rest of the transformation, while a post-transformation adds an operation
|
||||
/// that is applied after.
|
||||
pub struct TypedTransform3D<T, Src, Dst> {
|
||||
pub m11: T, pub m12: T, pub m13: T, pub m14: T,
|
||||
pub m21: T, pub m22: T, pub m23: T, pub m24: T,
|
||||
pub m31: T, pub m32: T, pub m33: T, pub m34: T,
|
||||
pub m41: T, pub m42: T, pub m43: T, pub m44: T,
|
||||
}
|
||||
}
|
||||
|
||||
/// The default 4d transform type with no units.
|
||||
pub type Transform3D<T> = TypedTransform3D<T, UnknownUnit, UnknownUnit>;
|
||||
|
||||
impl<T, Src, Dst> TypedTransform3D<T, Src, Dst> {
|
||||
/// Create a transform specifying its components in row-major order.
|
||||
///
|
||||
/// For example, the translation terms m41, m42, m43 on the last row with the
|
||||
/// row-major convention) are the 13rd, 14th and 15th parameters.
|
||||
#[inline]
|
||||
pub fn row_major(
|
||||
m11: T, m12: T, m13: T, m14: T,
|
||||
m21: T, m22: T, m23: T, m24: T,
|
||||
m31: T, m32: T, m33: T, m34: T,
|
||||
m41: T, m42: T, m43: T, m44: T)
|
||||
-> Self {
|
||||
TypedTransform3D {
|
||||
m11: m11, m12: m12, m13: m13, m14: m14,
|
||||
m21: m21, m22: m22, m23: m23, m24: m24,
|
||||
m31: m31, m32: m32, m33: m33, m34: m34,
|
||||
m41: m41, m42: m42, m43: m43, m44: m44,
|
||||
_unit: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a transform specifying its components in column-major order.
|
||||
///
|
||||
/// For example, the translation terms m41, m42, m43 on the last column with the
|
||||
/// column-major convention) are the 4th, 8th and 12nd parameters.
|
||||
#[inline]
|
||||
pub fn column_major(
|
||||
m11: T, m21: T, m31: T, m41: T,
|
||||
m12: T, m22: T, m32: T, m42: T,
|
||||
m13: T, m23: T, m33: T, m43: T,
|
||||
m14: T, m24: T, m34: T, m44: T)
|
||||
-> Self {
|
||||
TypedTransform3D {
|
||||
m11: m11, m12: m12, m13: m13, m14: m14,
|
||||
m21: m21, m22: m22, m23: m23, m24: m24,
|
||||
m31: m31, m32: m32, m33: m33, m34: m34,
|
||||
m41: m41, m42: m42, m43: m43, m44: m44,
|
||||
_unit: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl <T, Src, Dst> TypedTransform3D<T, Src, Dst>
|
||||
where T: Copy + Clone +
|
||||
PartialEq +
|
||||
One + Zero {
|
||||
#[inline]
|
||||
pub fn identity() -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
TypedTransform3D::row_major(
|
||||
_1, _0, _0, _0,
|
||||
_0, _1, _0, _0,
|
||||
_0, _0, _1, _0,
|
||||
_0, _0, _0, _1
|
||||
)
|
||||
}
|
||||
|
||||
// Intentional not public, because it checks for exact equivalence
|
||||
// while most consumers will probably want some sort of approximate
|
||||
// equivalence to deal with floating-point errors.
|
||||
#[inline]
|
||||
fn is_identity(&self) -> bool {
|
||||
*self == TypedTransform3D::identity()
|
||||
}
|
||||
}
|
||||
|
||||
impl <T, Src, Dst> TypedTransform3D<T, Src, Dst>
|
||||
where T: Copy + Clone +
|
||||
Add<T, Output=T> +
|
||||
Sub<T, Output=T> +
|
||||
Mul<T, Output=T> +
|
||||
Div<T, Output=T> +
|
||||
Neg<Output=T> +
|
||||
ApproxEq<T> +
|
||||
PartialOrd +
|
||||
Trig +
|
||||
One + Zero {
|
||||
|
||||
/// Create a 4 by 4 transform representing a 2d transformation, specifying its components
|
||||
/// in row-major order.
|
||||
#[inline]
|
||||
pub fn row_major_2d(m11: T, m12: T, m21: T, m22: T, m41: T, m42: T) -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
TypedTransform3D::row_major(
|
||||
m11, m12, _0, _0,
|
||||
m21, m22, _0, _0,
|
||||
_0, _0, _1, _0,
|
||||
m41, m42, _0, _1
|
||||
)
|
||||
}
|
||||
|
||||
/// Create an orthogonal projection transform.
|
||||
pub fn ortho(left: T, right: T,
|
||||
bottom: T, top: T,
|
||||
near: T, far: T) -> Self {
|
||||
let tx = -((right + left) / (right - left));
|
||||
let ty = -((top + bottom) / (top - bottom));
|
||||
let tz = -((far + near) / (far - near));
|
||||
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
let _2 = _1 + _1;
|
||||
TypedTransform3D::row_major(
|
||||
_2 / (right - left), _0 , _0 , _0,
|
||||
_0 , _2 / (top - bottom), _0 , _0,
|
||||
_0 , _0 , -_2 / (far - near), _0,
|
||||
tx , ty , tz , _1
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns true if this transform can be represented with a TypedTransform2D.
|
||||
///
|
||||
/// See https://drafts.csswg.org/css-transforms/#2d-transform
|
||||
#[inline]
|
||||
pub fn is_2d(&self) -> bool {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
self.m31 == _0 && self.m32 == _0 &&
|
||||
self.m13 == _0 && self.m23 == _0 &&
|
||||
self.m43 == _0 && self.m14 == _0 &&
|
||||
self.m24 == _0 && self.m34 == _0 &&
|
||||
self.m33 == _1 && self.m44 == _1
|
||||
}
|
||||
|
||||
/// Create a 2D transform picking the relevent terms from this transform.
|
||||
///
|
||||
/// This method assumes that self represents a 2d transformation, callers
|
||||
/// should check that self.is_2d() returns true beforehand.
|
||||
pub fn to_2d(&self) -> TypedTransform2D<T, Src, Dst> {
|
||||
TypedTransform2D::row_major(
|
||||
self.m11, self.m12,
|
||||
self.m21, self.m22,
|
||||
self.m41, self.m42
|
||||
)
|
||||
}
|
||||
|
||||
pub fn approx_eq(&self, other: &Self) -> bool {
|
||||
self.m11.approx_eq(&other.m11) && self.m12.approx_eq(&other.m12) &&
|
||||
self.m13.approx_eq(&other.m13) && self.m14.approx_eq(&other.m14) &&
|
||||
self.m21.approx_eq(&other.m21) && self.m22.approx_eq(&other.m22) &&
|
||||
self.m23.approx_eq(&other.m23) && self.m24.approx_eq(&other.m24) &&
|
||||
self.m31.approx_eq(&other.m31) && self.m32.approx_eq(&other.m32) &&
|
||||
self.m33.approx_eq(&other.m33) && self.m34.approx_eq(&other.m34) &&
|
||||
self.m41.approx_eq(&other.m41) && self.m42.approx_eq(&other.m42) &&
|
||||
self.m43.approx_eq(&other.m43) && self.m44.approx_eq(&other.m44)
|
||||
}
|
||||
|
||||
/// Returns the same transform with a different destination unit.
|
||||
#[inline]
|
||||
pub fn with_destination<NewDst>(&self) -> TypedTransform3D<T, Src, NewDst> {
|
||||
TypedTransform3D::row_major(
|
||||
self.m11, self.m12, self.m13, self.m14,
|
||||
self.m21, self.m22, self.m23, self.m24,
|
||||
self.m31, self.m32, self.m33, self.m34,
|
||||
self.m41, self.m42, self.m43, self.m44,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the same transform with a different source unit.
|
||||
#[inline]
|
||||
pub fn with_source<NewSrc>(&self) -> TypedTransform3D<T, NewSrc, Dst> {
|
||||
TypedTransform3D::row_major(
|
||||
self.m11, self.m12, self.m13, self.m14,
|
||||
self.m21, self.m22, self.m23, self.m24,
|
||||
self.m31, self.m32, self.m33, self.m34,
|
||||
self.m41, self.m42, self.m43, self.m44,
|
||||
)
|
||||
}
|
||||
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
#[inline]
|
||||
pub fn to_untyped(&self) -> Transform3D<T> {
|
||||
Transform3D::row_major(
|
||||
self.m11, self.m12, self.m13, self.m14,
|
||||
self.m21, self.m22, self.m23, self.m24,
|
||||
self.m31, self.m32, self.m33, self.m34,
|
||||
self.m41, self.m42, self.m43, self.m44,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
#[inline]
|
||||
pub fn from_untyped(m: &Transform3D<T>) -> Self {
|
||||
TypedTransform3D::row_major(
|
||||
m.m11, m.m12, m.m13, m.m14,
|
||||
m.m21, m.m22, m.m23, m.m24,
|
||||
m.m31, m.m32, m.m33, m.m34,
|
||||
m.m41, m.m42, m.m43, m.m44,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the multiplication of the two matrices such that mat's transformation
|
||||
/// applies after self's transformation.
|
||||
pub fn post_mul<NewDst>(&self, mat: &TypedTransform3D<T, Dst, NewDst>) -> TypedTransform3D<T, Src, NewDst> {
|
||||
TypedTransform3D::row_major(
|
||||
self.m11 * mat.m11 + self.m12 * mat.m21 + self.m13 * mat.m31 + self.m14 * mat.m41,
|
||||
self.m11 * mat.m12 + self.m12 * mat.m22 + self.m13 * mat.m32 + self.m14 * mat.m42,
|
||||
self.m11 * mat.m13 + self.m12 * mat.m23 + self.m13 * mat.m33 + self.m14 * mat.m43,
|
||||
self.m11 * mat.m14 + self.m12 * mat.m24 + self.m13 * mat.m34 + self.m14 * mat.m44,
|
||||
self.m21 * mat.m11 + self.m22 * mat.m21 + self.m23 * mat.m31 + self.m24 * mat.m41,
|
||||
self.m21 * mat.m12 + self.m22 * mat.m22 + self.m23 * mat.m32 + self.m24 * mat.m42,
|
||||
self.m21 * mat.m13 + self.m22 * mat.m23 + self.m23 * mat.m33 + self.m24 * mat.m43,
|
||||
self.m21 * mat.m14 + self.m22 * mat.m24 + self.m23 * mat.m34 + self.m24 * mat.m44,
|
||||
self.m31 * mat.m11 + self.m32 * mat.m21 + self.m33 * mat.m31 + self.m34 * mat.m41,
|
||||
self.m31 * mat.m12 + self.m32 * mat.m22 + self.m33 * mat.m32 + self.m34 * mat.m42,
|
||||
self.m31 * mat.m13 + self.m32 * mat.m23 + self.m33 * mat.m33 + self.m34 * mat.m43,
|
||||
self.m31 * mat.m14 + self.m32 * mat.m24 + self.m33 * mat.m34 + self.m34 * mat.m44,
|
||||
self.m41 * mat.m11 + self.m42 * mat.m21 + self.m43 * mat.m31 + self.m44 * mat.m41,
|
||||
self.m41 * mat.m12 + self.m42 * mat.m22 + self.m43 * mat.m32 + self.m44 * mat.m42,
|
||||
self.m41 * mat.m13 + self.m42 * mat.m23 + self.m43 * mat.m33 + self.m44 * mat.m43,
|
||||
self.m41 * mat.m14 + self.m42 * mat.m24 + self.m43 * mat.m34 + self.m44 * mat.m44,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the multiplication of the two matrices such that mat's transformation
|
||||
/// applies before self's transformation.
|
||||
pub fn pre_mul<NewSrc>(&self, mat: &TypedTransform3D<T, NewSrc, Src>) -> TypedTransform3D<T, NewSrc, Dst> {
|
||||
mat.post_mul(self)
|
||||
}
|
||||
|
||||
/// Returns the inverse transform if possible.
|
||||
pub fn inverse(&self) -> Option<TypedTransform3D<T, Dst, Src>> {
|
||||
let det = self.determinant();
|
||||
|
||||
if det == Zero::zero() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// todo(gw): this could be made faster by special casing
|
||||
// for simpler transform types.
|
||||
let m = TypedTransform3D::row_major(
|
||||
self.m23*self.m34*self.m42 - self.m24*self.m33*self.m42 +
|
||||
self.m24*self.m32*self.m43 - self.m22*self.m34*self.m43 -
|
||||
self.m23*self.m32*self.m44 + self.m22*self.m33*self.m44,
|
||||
|
||||
self.m14*self.m33*self.m42 - self.m13*self.m34*self.m42 -
|
||||
self.m14*self.m32*self.m43 + self.m12*self.m34*self.m43 +
|
||||
self.m13*self.m32*self.m44 - self.m12*self.m33*self.m44,
|
||||
|
||||
self.m13*self.m24*self.m42 - self.m14*self.m23*self.m42 +
|
||||
self.m14*self.m22*self.m43 - self.m12*self.m24*self.m43 -
|
||||
self.m13*self.m22*self.m44 + self.m12*self.m23*self.m44,
|
||||
|
||||
self.m14*self.m23*self.m32 - self.m13*self.m24*self.m32 -
|
||||
self.m14*self.m22*self.m33 + self.m12*self.m24*self.m33 +
|
||||
self.m13*self.m22*self.m34 - self.m12*self.m23*self.m34,
|
||||
|
||||
self.m24*self.m33*self.m41 - self.m23*self.m34*self.m41 -
|
||||
self.m24*self.m31*self.m43 + self.m21*self.m34*self.m43 +
|
||||
self.m23*self.m31*self.m44 - self.m21*self.m33*self.m44,
|
||||
|
||||
self.m13*self.m34*self.m41 - self.m14*self.m33*self.m41 +
|
||||
self.m14*self.m31*self.m43 - self.m11*self.m34*self.m43 -
|
||||
self.m13*self.m31*self.m44 + self.m11*self.m33*self.m44,
|
||||
|
||||
self.m14*self.m23*self.m41 - self.m13*self.m24*self.m41 -
|
||||
self.m14*self.m21*self.m43 + self.m11*self.m24*self.m43 +
|
||||
self.m13*self.m21*self.m44 - self.m11*self.m23*self.m44,
|
||||
|
||||
self.m13*self.m24*self.m31 - self.m14*self.m23*self.m31 +
|
||||
self.m14*self.m21*self.m33 - self.m11*self.m24*self.m33 -
|
||||
self.m13*self.m21*self.m34 + self.m11*self.m23*self.m34,
|
||||
|
||||
self.m22*self.m34*self.m41 - self.m24*self.m32*self.m41 +
|
||||
self.m24*self.m31*self.m42 - self.m21*self.m34*self.m42 -
|
||||
self.m22*self.m31*self.m44 + self.m21*self.m32*self.m44,
|
||||
|
||||
self.m14*self.m32*self.m41 - self.m12*self.m34*self.m41 -
|
||||
self.m14*self.m31*self.m42 + self.m11*self.m34*self.m42 +
|
||||
self.m12*self.m31*self.m44 - self.m11*self.m32*self.m44,
|
||||
|
||||
self.m12*self.m24*self.m41 - self.m14*self.m22*self.m41 +
|
||||
self.m14*self.m21*self.m42 - self.m11*self.m24*self.m42 -
|
||||
self.m12*self.m21*self.m44 + self.m11*self.m22*self.m44,
|
||||
|
||||
self.m14*self.m22*self.m31 - self.m12*self.m24*self.m31 -
|
||||
self.m14*self.m21*self.m32 + self.m11*self.m24*self.m32 +
|
||||
self.m12*self.m21*self.m34 - self.m11*self.m22*self.m34,
|
||||
|
||||
self.m23*self.m32*self.m41 - self.m22*self.m33*self.m41 -
|
||||
self.m23*self.m31*self.m42 + self.m21*self.m33*self.m42 +
|
||||
self.m22*self.m31*self.m43 - self.m21*self.m32*self.m43,
|
||||
|
||||
self.m12*self.m33*self.m41 - self.m13*self.m32*self.m41 +
|
||||
self.m13*self.m31*self.m42 - self.m11*self.m33*self.m42 -
|
||||
self.m12*self.m31*self.m43 + self.m11*self.m32*self.m43,
|
||||
|
||||
self.m13*self.m22*self.m41 - self.m12*self.m23*self.m41 -
|
||||
self.m13*self.m21*self.m42 + self.m11*self.m23*self.m42 +
|
||||
self.m12*self.m21*self.m43 - self.m11*self.m22*self.m43,
|
||||
|
||||
self.m12*self.m23*self.m31 - self.m13*self.m22*self.m31 +
|
||||
self.m13*self.m21*self.m32 - self.m11*self.m23*self.m32 -
|
||||
self.m12*self.m21*self.m33 + self.m11*self.m22*self.m33
|
||||
);
|
||||
|
||||
let _1: T = One::one();
|
||||
Some(m.mul_s(_1 / det))
|
||||
}
|
||||
|
||||
/// Compute the determinant of the transform.
|
||||
pub fn determinant(&self) -> T {
|
||||
self.m14 * self.m23 * self.m32 * self.m41 -
|
||||
self.m13 * self.m24 * self.m32 * self.m41 -
|
||||
self.m14 * self.m22 * self.m33 * self.m41 +
|
||||
self.m12 * self.m24 * self.m33 * self.m41 +
|
||||
self.m13 * self.m22 * self.m34 * self.m41 -
|
||||
self.m12 * self.m23 * self.m34 * self.m41 -
|
||||
self.m14 * self.m23 * self.m31 * self.m42 +
|
||||
self.m13 * self.m24 * self.m31 * self.m42 +
|
||||
self.m14 * self.m21 * self.m33 * self.m42 -
|
||||
self.m11 * self.m24 * self.m33 * self.m42 -
|
||||
self.m13 * self.m21 * self.m34 * self.m42 +
|
||||
self.m11 * self.m23 * self.m34 * self.m42 +
|
||||
self.m14 * self.m22 * self.m31 * self.m43 -
|
||||
self.m12 * self.m24 * self.m31 * self.m43 -
|
||||
self.m14 * self.m21 * self.m32 * self.m43 +
|
||||
self.m11 * self.m24 * self.m32 * self.m43 +
|
||||
self.m12 * self.m21 * self.m34 * self.m43 -
|
||||
self.m11 * self.m22 * self.m34 * self.m43 -
|
||||
self.m13 * self.m22 * self.m31 * self.m44 +
|
||||
self.m12 * self.m23 * self.m31 * self.m44 +
|
||||
self.m13 * self.m21 * self.m32 * self.m44 -
|
||||
self.m11 * self.m23 * self.m32 * self.m44 -
|
||||
self.m12 * self.m21 * self.m33 * self.m44 +
|
||||
self.m11 * self.m22 * self.m33 * self.m44
|
||||
}
|
||||
|
||||
/// Multiplies all of the transform's component by a scalar and returns the result.
|
||||
#[must_use]
|
||||
pub fn mul_s(&self, x: T) -> Self {
|
||||
TypedTransform3D::row_major(
|
||||
self.m11 * x, self.m12 * x, self.m13 * x, self.m14 * x,
|
||||
self.m21 * x, self.m22 * x, self.m23 * x, self.m24 * x,
|
||||
self.m31 * x, self.m32 * x, self.m33 * x, self.m34 * x,
|
||||
self.m41 * x, self.m42 * x, self.m43 * x, self.m44 * x
|
||||
)
|
||||
}
|
||||
|
||||
/// Convenience function to create a scale transform from a ScaleFactor.
|
||||
pub fn from_scale_factor(scale: ScaleFactor<T, Src, Dst>) -> Self {
|
||||
TypedTransform3D::create_scale(scale.get(), scale.get(), scale.get())
|
||||
}
|
||||
|
||||
/// Returns the given 2d point transformed by this transform.
|
||||
///
|
||||
/// The input point must be use the unit Src, and the returned point has the unit Dst.
|
||||
#[inline]
|
||||
pub fn transform_point2d(&self, p: &TypedPoint2D<T, Src>) -> TypedPoint2D<T, Dst> {
|
||||
let x = p.x * self.m11 + p.y * self.m21 + self.m41;
|
||||
let y = p.x * self.m12 + p.y * self.m22 + self.m42;
|
||||
|
||||
let w = p.x * self.m14 + p.y * self.m24 + self.m44;
|
||||
|
||||
point2(x/w, y/w)
|
||||
}
|
||||
|
||||
/// Returns the given 2d vector transformed by this matrix.
|
||||
///
|
||||
/// The input point must be use the unit Src, and the returned point has the unit Dst.
|
||||
#[inline]
|
||||
pub fn transform_vector2d(&self, v: &TypedVector2D<T, Src>) -> TypedVector2D<T, Dst> {
|
||||
vec2(
|
||||
v.x * self.m11 + v.y * self.m21,
|
||||
v.x * self.m12 + v.y * self.m22,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the given 3d point transformed by this transform.
|
||||
///
|
||||
/// The input point must be use the unit Src, and the returned point has the unit Dst.
|
||||
#[inline]
|
||||
pub fn transform_point3d(&self, p: &TypedPoint3D<T, Src>) -> TypedPoint3D<T, Dst> {
|
||||
let x = p.x * self.m11 + p.y * self.m21 + p.z * self.m31 + self.m41;
|
||||
let y = p.x * self.m12 + p.y * self.m22 + p.z * self.m32 + self.m42;
|
||||
let z = p.x * self.m13 + p.y * self.m23 + p.z * self.m33 + self.m43;
|
||||
let w = p.x * self.m14 + p.y * self.m24 + p.z * self.m34 + self.m44;
|
||||
|
||||
point3(x/w, y/w, z/w)
|
||||
}
|
||||
|
||||
/// Returns the given 3d vector transformed by this matrix.
|
||||
///
|
||||
/// The input point must be use the unit Src, and the returned point has the unit Dst.
|
||||
#[inline]
|
||||
pub fn transform_vector3d(&self, v: &TypedVector3D<T, Src>) -> TypedVector3D<T, Dst> {
|
||||
vec3(
|
||||
v.x * self.m11 + v.y * self.m21 + v.z * self.m31,
|
||||
v.x * self.m12 + v.y * self.m22 + v.z * self.m32,
|
||||
v.x * self.m13 + v.y * self.m23 + v.z * self.m33,
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a rectangle that encompasses the result of transforming the given rectangle by this
|
||||
/// transform.
|
||||
pub fn transform_rect(&self, rect: &TypedRect<T, Src>) -> TypedRect<T, Dst> {
|
||||
TypedRect::from_points(&[
|
||||
self.transform_point2d(&rect.origin),
|
||||
self.transform_point2d(&rect.top_right()),
|
||||
self.transform_point2d(&rect.bottom_left()),
|
||||
self.transform_point2d(&rect.bottom_right()),
|
||||
])
|
||||
}
|
||||
|
||||
/// Create a 3d translation transform
|
||||
pub fn create_translation(x: T, y: T, z: T) -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
TypedTransform3D::row_major(
|
||||
_1, _0, _0, _0,
|
||||
_0, _1, _0, _0,
|
||||
_0, _0, _1, _0,
|
||||
x, y, z, _1
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a transform with a translation applied before self's transformation.
|
||||
#[must_use]
|
||||
pub fn pre_translate(&self, v: TypedVector3D<T, Src>) -> Self {
|
||||
self.pre_mul(&TypedTransform3D::create_translation(v.x, v.y, v.z))
|
||||
}
|
||||
|
||||
/// Returns a transform with a translation applied after self's transformation.
|
||||
#[must_use]
|
||||
pub fn post_translate(&self, v: TypedVector3D<T, Dst>) -> Self {
|
||||
self.post_mul(&TypedTransform3D::create_translation(v.x, v.y, v.z))
|
||||
}
|
||||
|
||||
/// Create a 3d scale transform
|
||||
pub fn create_scale(x: T, y: T, z: T) -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
TypedTransform3D::row_major(
|
||||
x, _0, _0, _0,
|
||||
_0, y, _0, _0,
|
||||
_0, _0, z, _0,
|
||||
_0, _0, _0, _1
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a transform with a scale applied before self's transformation.
|
||||
#[must_use]
|
||||
pub fn pre_scale(&self, x: T, y: T, z: T) -> Self {
|
||||
TypedTransform3D::row_major(
|
||||
self.m11 * x, self.m12, self.m13, self.m14,
|
||||
self.m21 , self.m22 * y, self.m23, self.m24,
|
||||
self.m31 , self.m32, self.m33 * z, self.m34,
|
||||
self.m41 , self.m42, self.m43, self.m44
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a transform with a scale applied after self's transformation.
|
||||
#[must_use]
|
||||
pub fn post_scale(&self, x: T, y: T, z: T) -> Self {
|
||||
self.post_mul(&TypedTransform3D::create_scale(x, y, z))
|
||||
}
|
||||
|
||||
/// Create a 3d rotation transform from an angle / axis.
|
||||
/// The supplied axis must be normalized.
|
||||
pub fn create_rotation(x: T, y: T, z: T, theta: Radians<T>) -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
let _2 = _1 + _1;
|
||||
|
||||
let xx = x * x;
|
||||
let yy = y * y;
|
||||
let zz = z * z;
|
||||
|
||||
let half_theta = theta.get() / _2;
|
||||
let sc = half_theta.sin() * half_theta.cos();
|
||||
let sq = half_theta.sin() * half_theta.sin();
|
||||
|
||||
TypedTransform3D::row_major(
|
||||
_1 - _2 * (yy + zz) * sq,
|
||||
_2 * (x * y * sq - z * sc),
|
||||
_2 * (x * z * sq + y * sc),
|
||||
_0,
|
||||
|
||||
_2 * (x * y * sq + z * sc),
|
||||
_1 - _2 * (xx + zz) * sq,
|
||||
_2 * (y * z * sq - x * sc),
|
||||
_0,
|
||||
|
||||
_2 * (x * z * sq - y * sc),
|
||||
_2 * (y * z * sq + x * sc),
|
||||
_1 - _2 * (xx + yy) * sq,
|
||||
_0,
|
||||
|
||||
_0,
|
||||
_0,
|
||||
_0,
|
||||
_1
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a transform with a rotation applied after self's transformation.
|
||||
#[must_use]
|
||||
pub fn post_rotate(&self, x: T, y: T, z: T, theta: Radians<T>) -> Self {
|
||||
self.post_mul(&TypedTransform3D::create_rotation(x, y, z, theta))
|
||||
}
|
||||
|
||||
/// Returns a transform with a rotation applied before self's transformation.
|
||||
#[must_use]
|
||||
pub fn pre_rotate(&self, x: T, y: T, z: T, theta: Radians<T>) -> Self {
|
||||
self.pre_mul(&TypedTransform3D::create_rotation(x, y, z, theta))
|
||||
}
|
||||
|
||||
/// Create a 2d skew transform.
|
||||
///
|
||||
/// See https://drafts.csswg.org/css-transforms/#funcdef-skew
|
||||
pub fn create_skew(alpha: Radians<T>, beta: Radians<T>) -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
let (sx, sy) = (beta.get().tan(), alpha.get().tan());
|
||||
TypedTransform3D::row_major(
|
||||
_1, sx, _0, _0,
|
||||
sy, _1, _0, _0,
|
||||
_0, _0, _1, _0,
|
||||
_0, _0, _0, _1
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a simple perspective projection transform
|
||||
pub fn create_perspective(d: T) -> Self {
|
||||
let (_0, _1): (T, T) = (Zero::zero(), One::one());
|
||||
TypedTransform3D::row_major(
|
||||
_1, _0, _0, _0,
|
||||
_0, _1, _0, _0,
|
||||
_0, _0, _1, -_1 / d,
|
||||
_0, _0, _0, _1
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, Src, Dst> TypedTransform3D<T, Src, Dst> {
|
||||
/// Returns an array containing this transform's terms in row-major order (the order
|
||||
/// in which the transform is actually laid out in memory).
|
||||
pub fn to_row_major_array(&self) -> [T; 16] {
|
||||
[
|
||||
self.m11, self.m12, self.m13, self.m14,
|
||||
self.m21, self.m22, self.m23, self.m24,
|
||||
self.m31, self.m32, self.m33, self.m34,
|
||||
self.m41, self.m42, self.m43, self.m44
|
||||
]
|
||||
}
|
||||
|
||||
/// Returns an array containing this transform's terms in column-major order.
|
||||
pub fn to_column_major_array(&self) -> [T; 16] {
|
||||
[
|
||||
self.m11, self.m21, self.m31, self.m41,
|
||||
self.m12, self.m22, self.m32, self.m42,
|
||||
self.m13, self.m23, self.m33, self.m43,
|
||||
self.m14, self.m24, self.m34, self.m44
|
||||
]
|
||||
}
|
||||
|
||||
/// Returns an array containing this transform's 4 rows in (in row-major order)
|
||||
/// as arrays.
|
||||
///
|
||||
/// This is a convenience method to interface with other libraries like glium.
|
||||
pub fn to_row_arrays(&self) -> [[T; 4]; 4] {
|
||||
[
|
||||
[self.m11, self.m12, self.m13, self.m14],
|
||||
[self.m21, self.m22, self.m23, self.m24],
|
||||
[self.m31, self.m32, self.m33, self.m34],
|
||||
[self.m41, self.m42, self.m43, self.m44]
|
||||
]
|
||||
}
|
||||
|
||||
/// Returns an array containing this transform's 4 columns in (in row-major order,
|
||||
/// or 4 rows in column-major order) as arrays.
|
||||
///
|
||||
/// This is a convenience method to interface with other libraries like glium.
|
||||
pub fn to_column_arrays(&self) -> [[T; 4]; 4] {
|
||||
[
|
||||
[self.m11, self.m21, self.m31, self.m41],
|
||||
[self.m12, self.m22, self.m32, self.m42],
|
||||
[self.m13, self.m23, self.m33, self.m43],
|
||||
[self.m14, self.m24, self.m34, self.m44]
|
||||
]
|
||||
}
|
||||
|
||||
/// Creates a transform from an array of 16 elements in row-major order.
|
||||
pub fn from_array(array: [T; 16]) -> Self {
|
||||
Self::row_major(
|
||||
array[0], array[1], array[2], array[3],
|
||||
array[4], array[5], array[6], array[7],
|
||||
array[8], array[9], array[10], array[11],
|
||||
array[12], array[13], array[14], array[15],
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a transform from 4 rows of 4 elements (row-major order).
|
||||
pub fn from_row_arrays(array: [[T; 4]; 4]) -> Self {
|
||||
Self::row_major(
|
||||
array[0][0], array[0][1], array[0][2], array[0][3],
|
||||
array[1][0], array[1][1], array[1][2], array[1][3],
|
||||
array[2][0], array[2][1], array[2][2], array[2][3],
|
||||
array[3][0], array[3][1], array[3][2], array[3][3],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Src, Dst> fmt::Debug for TypedTransform3D<T, Src, Dst>
|
||||
where T: Copy + fmt::Debug +
|
||||
PartialEq +
|
||||
One + Zero {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
if self.is_identity() {
|
||||
write!(f, "[I]")
|
||||
} else {
|
||||
self.to_row_major_array().fmt(f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use approxeq::ApproxEq;
|
||||
use transform2d::Transform2D;
|
||||
use point::{Point2D, Point3D};
|
||||
use Radians;
|
||||
use super::*;
|
||||
|
||||
use std::f32::consts::FRAC_PI_2;
|
||||
|
||||
type Mf32 = Transform3D<f32>;
|
||||
|
||||
// For convenience.
|
||||
fn rad(v: f32) -> Radians<f32> { Radians::new(v) }
|
||||
|
||||
#[test]
|
||||
pub fn test_translation() {
|
||||
let t1 = Mf32::create_translation(1.0, 2.0, 3.0);
|
||||
let t2 = Mf32::identity().pre_translate(vec3(1.0, 2.0, 3.0));
|
||||
let t3 = Mf32::identity().post_translate(vec3(1.0, 2.0, 3.0));
|
||||
assert_eq!(t1, t2);
|
||||
assert_eq!(t1, t3);
|
||||
|
||||
assert_eq!(t1.transform_point3d(&Point3D::new(1.0, 1.0, 1.0)), Point3D::new(2.0, 3.0, 4.0));
|
||||
assert_eq!(t1.transform_point2d(&Point2D::new(1.0, 1.0)), Point2D::new(2.0, 3.0));
|
||||
|
||||
assert_eq!(t1.post_mul(&t1), Mf32::create_translation(2.0, 4.0, 6.0));
|
||||
|
||||
assert!(!t1.is_2d());
|
||||
assert_eq!(Mf32::create_translation(1.0, 2.0, 3.0).to_2d(), Transform2D::create_translation(1.0, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_rotation() {
|
||||
let r1 = Mf32::create_rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
|
||||
let r2 = Mf32::identity().pre_rotate(0.0, 0.0, 1.0, rad(FRAC_PI_2));
|
||||
let r3 = Mf32::identity().post_rotate(0.0, 0.0, 1.0, rad(FRAC_PI_2));
|
||||
assert_eq!(r1, r2);
|
||||
assert_eq!(r1, r3);
|
||||
|
||||
assert!(r1.transform_point3d(&Point3D::new(1.0, 2.0, 3.0)).approx_eq(&Point3D::new(2.0, -1.0, 3.0)));
|
||||
assert!(r1.transform_point2d(&Point2D::new(1.0, 2.0)).approx_eq(&Point2D::new(2.0, -1.0)));
|
||||
|
||||
assert!(r1.post_mul(&r1).approx_eq(&Mf32::create_rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2*2.0))));
|
||||
|
||||
assert!(r1.is_2d());
|
||||
assert!(r1.to_2d().approx_eq(&Transform2D::create_rotation(rad(FRAC_PI_2))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_scale() {
|
||||
let s1 = Mf32::create_scale(2.0, 3.0, 4.0);
|
||||
let s2 = Mf32::identity().pre_scale(2.0, 3.0, 4.0);
|
||||
let s3 = Mf32::identity().post_scale(2.0, 3.0, 4.0);
|
||||
assert_eq!(s1, s2);
|
||||
assert_eq!(s1, s3);
|
||||
|
||||
assert!(s1.transform_point3d(&Point3D::new(2.0, 2.0, 2.0)).approx_eq(&Point3D::new(4.0, 6.0, 8.0)));
|
||||
assert!(s1.transform_point2d(&Point2D::new(2.0, 2.0)).approx_eq(&Point2D::new(4.0, 6.0)));
|
||||
|
||||
assert_eq!(s1.post_mul(&s1), Mf32::create_scale(4.0, 9.0, 16.0));
|
||||
|
||||
assert!(!s1.is_2d());
|
||||
assert_eq!(Mf32::create_scale(2.0, 3.0, 0.0).to_2d(), Transform2D::create_scale(2.0, 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_ortho() {
|
||||
let (left, right, bottom, top) = (0.0f32, 1.0f32, 0.1f32, 1.0f32);
|
||||
let (near, far) = (-1.0f32, 1.0f32);
|
||||
let result = Mf32::ortho(left, right, bottom, top, near, far);
|
||||
let expected = Mf32::row_major(
|
||||
2.0, 0.0, 0.0, 0.0,
|
||||
0.0, 2.22222222, 0.0, 0.0,
|
||||
0.0, 0.0, -1.0, 0.0,
|
||||
-1.0, -1.22222222, -0.0, 1.0
|
||||
);
|
||||
debug!("result={:?} expected={:?}", result, expected);
|
||||
assert!(result.approx_eq(&expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_2d() {
|
||||
assert!(Mf32::identity().is_2d());
|
||||
assert!(Mf32::create_rotation(0.0, 0.0, 1.0, rad(0.7854)).is_2d());
|
||||
assert!(!Mf32::create_rotation(0.0, 1.0, 0.0, rad(0.7854)).is_2d());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_row_major_2d() {
|
||||
let m1 = Mf32::row_major_2d(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
|
||||
let m2 = Mf32::row_major(
|
||||
1.0, 2.0, 0.0, 0.0,
|
||||
3.0, 4.0, 0.0, 0.0,
|
||||
0.0, 0.0, 1.0, 0.0,
|
||||
5.0, 6.0, 0.0, 1.0
|
||||
);
|
||||
assert_eq!(m1, m2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_column_major() {
|
||||
assert_eq!(
|
||||
Mf32::row_major(
|
||||
1.0, 2.0, 3.0, 4.0,
|
||||
5.0, 6.0, 7.0, 8.0,
|
||||
9.0, 10.0, 11.0, 12.0,
|
||||
13.0, 14.0, 15.0, 16.0,
|
||||
),
|
||||
Mf32::column_major(
|
||||
1.0, 5.0, 9.0, 13.0,
|
||||
2.0, 6.0, 10.0, 14.0,
|
||||
3.0, 7.0, 11.0, 15.0,
|
||||
4.0, 8.0, 12.0, 16.0,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_simple() {
|
||||
let m1 = Mf32::identity();
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.approx_eq(&m2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_scale() {
|
||||
let m1 = Mf32::create_scale(1.5, 0.3, 2.1);
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.pre_mul(&m2).approx_eq(&Mf32::identity()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_translate() {
|
||||
let m1 = Mf32::create_translation(-132.0, 0.3, 493.0);
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.pre_mul(&m2).approx_eq(&Mf32::identity()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_rotate() {
|
||||
let m1 = Mf32::create_rotation(0.0, 1.0, 0.0, rad(1.57));
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.pre_mul(&m2).approx_eq(&Mf32::identity()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_inverse_transform_point_2d() {
|
||||
let m1 = Mf32::create_translation(100.0, 200.0, 0.0);
|
||||
let m2 = m1.inverse().unwrap();
|
||||
assert!(m1.pre_mul(&m2).approx_eq(&Mf32::identity()));
|
||||
|
||||
let p1 = Point2D::new(1000.0, 2000.0);
|
||||
let p2 = m1.transform_point2d(&p1);
|
||||
assert!(p2.eq(&Point2D::new(1100.0, 2200.0)));
|
||||
|
||||
let p3 = m2.transform_point2d(&p2);
|
||||
assert!(p3.eq(&p1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inverse_none() {
|
||||
assert!(Mf32::create_scale(2.0, 0.0, 2.0).inverse().is_none());
|
||||
assert!(Mf32::create_scale(2.0, 2.0, 2.0).inverse().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_pre_post() {
|
||||
let m1 = Transform3D::identity().post_scale(1.0, 2.0, 3.0).post_translate(vec3(1.0, 2.0, 3.0));
|
||||
let m2 = Transform3D::identity().pre_translate(vec3(1.0, 2.0, 3.0)).pre_scale(1.0, 2.0, 3.0);
|
||||
assert!(m1.approx_eq(&m2));
|
||||
|
||||
let r = Mf32::create_rotation(0.0, 0.0, 1.0, rad(FRAC_PI_2));
|
||||
let t = Mf32::create_translation(2.0, 3.0, 0.0);
|
||||
|
||||
let a = Point3D::new(1.0, 1.0, 1.0);
|
||||
|
||||
assert!(r.post_mul(&t).transform_point3d(&a).approx_eq(&Point3D::new(3.0, 2.0, 1.0)));
|
||||
assert!(t.post_mul(&r).transform_point3d(&a).approx_eq(&Point3D::new(4.0, -3.0, 1.0)));
|
||||
assert!(t.post_mul(&r).transform_point3d(&a).approx_eq(&r.transform_point3d(&t.transform_point3d(&a))));
|
||||
|
||||
assert!(r.pre_mul(&t).transform_point3d(&a).approx_eq(&Point3D::new(4.0, -3.0, 1.0)));
|
||||
assert!(t.pre_mul(&r).transform_point3d(&a).approx_eq(&Point3D::new(3.0, 2.0, 1.0)));
|
||||
assert!(t.pre_mul(&r).transform_point3d(&a).approx_eq(&t.transform_point3d(&r.transform_point3d(&a))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_size_of() {
|
||||
use std::mem::size_of;
|
||||
assert_eq!(size_of::<Transform3D<f32>>(), 16*size_of::<f32>());
|
||||
assert_eq!(size_of::<Transform3D<f64>>(), 16*size_of::<f64>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_transform_associativity() {
|
||||
let m1 = Mf32::row_major(3.0, 2.0, 1.5, 1.0,
|
||||
0.0, 4.5, -1.0, -4.0,
|
||||
0.0, 3.5, 2.5, 40.0,
|
||||
0.0, 3.0, 0.0, 1.0);
|
||||
let m2 = Mf32::row_major(1.0, -1.0, 3.0, 0.0,
|
||||
-1.0, 0.5, 0.0, 2.0,
|
||||
1.5, -2.0, 6.0, 0.0,
|
||||
-2.5, 6.0, 1.0, 1.0);
|
||||
|
||||
let p = Point3D::new(1.0, 3.0, 5.0);
|
||||
let p1 = m2.pre_mul(&m1).transform_point3d(&p);
|
||||
let p2 = m2.transform_point3d(&m1.transform_point3d(&p));
|
||||
assert!(p1.approx_eq(&p2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_is_identity() {
|
||||
let m1 = Transform3D::identity();
|
||||
assert!(m1.is_identity());
|
||||
let m2 = m1.post_translate(vec3(0.1, 0.0, 0.0));
|
||||
assert!(!m2.is_identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_transform_vector() {
|
||||
// Translation does not apply to vectors.
|
||||
let m = Mf32::create_translation(1.0, 2.0, 3.0);
|
||||
let v1 = vec3(10.0, -10.0, 3.0);
|
||||
assert_eq!(v1, m.transform_vector3d(&v1));
|
||||
// While it does apply to points.
|
||||
assert!(v1.to_point() != m.transform_point3d(&v1.to_point()));
|
||||
|
||||
// same thing with 2d vectors/points
|
||||
let v2 = vec2(10.0, -5.0);
|
||||
assert_eq!(v2, m.transform_vector2d(&v2));
|
||||
assert!(v2.to_point() != m.transform_point2d(&v2.to_point()));
|
||||
}
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
|
||||
/// Trait for basic trigonometry functions, so they can be used on generic numeric types
|
||||
pub trait Trig {
|
||||
fn sin(self) -> Self;
|
||||
fn cos(self) -> Self;
|
||||
fn tan(self) -> Self;
|
||||
}
|
||||
|
||||
macro_rules! trig {
|
||||
($ty:ty) => (
|
||||
impl Trig for $ty {
|
||||
#[inline]
|
||||
fn sin(self) -> $ty { self.sin() }
|
||||
#[inline]
|
||||
fn cos(self) -> $ty { self.cos() }
|
||||
#[inline]
|
||||
fn tan(self) -> $ty { self.tan() }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
trig!(f32);
|
||||
trig!(f64);
|
|
@ -1,894 +0,0 @@
|
|||
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use super::UnknownUnit;
|
||||
use approxeq::ApproxEq;
|
||||
use length::Length;
|
||||
use point::{TypedPoint2D, TypedPoint3D, point2, point3};
|
||||
use size::{TypedSize2D, size2};
|
||||
use scale_factor::ScaleFactor;
|
||||
use num::*;
|
||||
use num_traits::{Float, NumCast};
|
||||
use std::fmt;
|
||||
use std::ops::{Add, Neg, Mul, Sub, Div, AddAssign, SubAssign, MulAssign, DivAssign};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
define_matrix! {
|
||||
/// A 2d Vector tagged with a unit.
|
||||
pub struct TypedVector2D<T, U> {
|
||||
pub x: T,
|
||||
pub y: T,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default 2d vector type with no unit.
|
||||
///
|
||||
/// `Vector2D` provides the same methods as `TypedVector2D`.
|
||||
pub type Vector2D<T> = TypedVector2D<T, UnknownUnit>;
|
||||
|
||||
impl<T: Copy + Zero, U> TypedVector2D<T, U> {
|
||||
/// Constructor, setting all components to zero.
|
||||
#[inline]
|
||||
pub fn zero() -> Self {
|
||||
TypedVector2D::new(Zero::zero(), Zero::zero())
|
||||
}
|
||||
|
||||
/// Convert into a 3d vector.
|
||||
#[inline]
|
||||
pub fn to_3d(&self) -> TypedVector3D<T, U> {
|
||||
vec3(self.x, self.y, Zero::zero())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for TypedVector2D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "({:?},{:?})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display, U> fmt::Display for TypedVector2D<T, U> {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "({},{})", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> TypedVector2D<T, U> {
|
||||
/// Constructor taking scalar values directly.
|
||||
#[inline]
|
||||
pub fn new(x: T, y: T) -> Self {
|
||||
TypedVector2D { x: x, y: y, _unit: PhantomData }
|
||||
}
|
||||
|
||||
/// Constructor taking properly typed Lengths instead of scalar values.
|
||||
#[inline]
|
||||
pub fn from_lengths(x: Length<T, U>, y: Length<T, U>) -> Self {
|
||||
vec2(x.0, y.0)
|
||||
}
|
||||
|
||||
/// Create a 3d vector from this one, using the specified z value.
|
||||
#[inline]
|
||||
pub fn extend(&self, z: T) -> TypedVector3D<T, U> {
|
||||
vec3(self.x, self.y, z)
|
||||
}
|
||||
|
||||
/// Cast this vector into a point.
|
||||
///
|
||||
/// Equivalent to adding this vector to the origin.
|
||||
#[inline]
|
||||
pub fn to_point(&self) -> TypedPoint2D<T, U> {
|
||||
point2(self.x, self.y)
|
||||
}
|
||||
|
||||
/// Cast this vector into a size.
|
||||
#[inline]
|
||||
pub fn to_size(&self) -> TypedSize2D<T, U> {
|
||||
size2(self.x, self.y)
|
||||
}
|
||||
|
||||
|
||||
/// Returns self.x as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn x_typed(&self) -> Length<T, U> { Length::new(self.x) }
|
||||
|
||||
/// Returns self.y as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn y_typed(&self) -> Length<T, U> { Length::new(self.y) }
|
||||
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
#[inline]
|
||||
pub fn to_untyped(&self) -> Vector2D<T> {
|
||||
vec2(self.x, self.y)
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
#[inline]
|
||||
pub fn from_untyped(p: &Vector2D<T>) -> Self {
|
||||
vec2(p.x, p.y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_array(&self) -> [T; 2] {
|
||||
[self.x, self.y]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedVector2D<T, U>
|
||||
where T: Copy + Mul<T, Output=T> + Add<T, Output=T> + Sub<T, Output=T> {
|
||||
/// Dot product.
|
||||
#[inline]
|
||||
pub fn dot(self, other: Self) -> T {
|
||||
self.x * other.x + self.y * other.y
|
||||
}
|
||||
|
||||
/// Returns the norm of the cross product [self.x, self.y, 0] x [other.x, other.y, 0]..
|
||||
#[inline]
|
||||
pub fn cross(self, other: Self) -> T {
|
||||
self.x * other.y - self.y * other.x
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn normalize(self) -> Self where T: Float + ApproxEq<T> {
|
||||
let dot = self.dot(self);
|
||||
if dot.approx_eq(&T::zero()) {
|
||||
self
|
||||
} else {
|
||||
self / dot.sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn square_length(&self) -> T {
|
||||
self.x * self.x + self.y * self.y
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn length(&self) -> T where T: Float + ApproxEq<T> {
|
||||
self.square_length().sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedVector2D<T, U>
|
||||
where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> {
|
||||
/// Linearly interpolate between this vector and another vector.
|
||||
///
|
||||
/// `t` is expected to be between zero and one.
|
||||
#[inline]
|
||||
pub fn lerp(&self, other: Self, t: T) -> Self {
|
||||
let one_t = T::one() - t;
|
||||
(*self) * one_t + other * t
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> Add for TypedVector2D<T, U> {
|
||||
type Output = Self;
|
||||
fn add(self, other: Self) -> Self {
|
||||
TypedVector2D::new(self.x + other.x, self.y + other.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> AddAssign for TypedVector2D<T, U> {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, other: Self) {
|
||||
*self = *self + other
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> SubAssign<TypedVector2D<T, U>> for TypedVector2D<T, U> {
|
||||
#[inline]
|
||||
fn sub_assign(&mut self, other: Self) {
|
||||
*self = *self - other
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedVector2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn sub(self, other: Self) -> Self {
|
||||
vec2(self.x - other.x, self.y - other.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl <T: Copy + Neg<Output=T>, U> Neg for TypedVector2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn neg(self) -> Self {
|
||||
vec2(-self.x, -self.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Float, U> TypedVector2D<T, U> {
|
||||
#[inline]
|
||||
pub fn min(self, other: Self) -> Self {
|
||||
vec2(self.x.min(other.x), self.y.min(other.y))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max(self, other: Self) -> Self {
|
||||
vec2(self.x.max(other.x), self.y.max(other.y))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedVector2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn mul(self, scale: T) -> Self {
|
||||
vec2(self.x * scale, self.y * scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedVector2D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn div(self, scale: T) -> Self {
|
||||
vec2(self.x / scale, self.y / scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> MulAssign<T> for TypedVector2D<T, U> {
|
||||
#[inline]
|
||||
fn mul_assign(&mut self, scale: T) {
|
||||
*self = *self * scale
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> DivAssign<T> for TypedVector2D<T, U> {
|
||||
#[inline]
|
||||
fn div_assign(&mut self, scale: T) {
|
||||
*self = *self / scale
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U1, U2> Mul<ScaleFactor<T, U1, U2>> for TypedVector2D<T, U1> {
|
||||
type Output = TypedVector2D<T, U2>;
|
||||
#[inline]
|
||||
fn mul(self, scale: ScaleFactor<T, U1, U2>) -> TypedVector2D<T, U2> {
|
||||
vec2(self.x * scale.get(), self.y * scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U1, U2> Div<ScaleFactor<T, U1, U2>> for TypedVector2D<T, U2> {
|
||||
type Output = TypedVector2D<T, U1>;
|
||||
#[inline]
|
||||
fn div(self, scale: ScaleFactor<T, U1, U2>) -> TypedVector2D<T, U1> {
|
||||
vec2(self.x / scale.get(), self.y / scale.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Round, U> TypedVector2D<T, U> {
|
||||
/// Rounds each component to the nearest integer value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
/// For example `{ -0.1, -0.8 }.round() == { 0.0, -1.0 }`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn round(&self) -> Self {
|
||||
vec2(self.x.round(), self.y.round())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Ceil, U> TypedVector2D<T, U> {
|
||||
/// Rounds each component to the smallest integer equal or greater than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
/// For example `{ -0.1, -0.8 }.ceil() == { 0.0, 0.0 }`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn ceil(&self) -> Self {
|
||||
vec2(self.x.ceil(), self.y.ceil())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Floor, U> TypedVector2D<T, U> {
|
||||
/// Rounds each component to the biggest integer equal or lower than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
/// For example `{ -0.1, -0.8 }.floor() == { -1.0, -1.0 }`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn floor(&self) -> Self {
|
||||
vec2(self.x.floor(), self.y.floor())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: NumCast + Copy, U> TypedVector2D<T, U> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
///
|
||||
/// When casting from floating vector to integer coordinates, the decimals are truncated
|
||||
/// as one would expect from a simple cast, but this behavior does not always make sense
|
||||
/// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
|
||||
#[inline]
|
||||
pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedVector2D<NewT, U>> {
|
||||
match (NumCast::from(self.x), NumCast::from(self.y)) {
|
||||
(Some(x), Some(y)) => Some(TypedVector2D::new(x, y)),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience functions for common casts
|
||||
|
||||
/// Cast into an `f32` vector.
|
||||
#[inline]
|
||||
pub fn to_f32(&self) -> TypedVector2D<f32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `usize` vector, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating vector vectors, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_usize(&self) -> TypedVector2D<usize, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an i32 vector, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating vector vectors, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i32(&self) -> TypedVector2D<i32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an i64 vector, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating vector vectors, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i64(&self) -> TypedVector2D<i64, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy+ApproxEq<T>, U> ApproxEq<TypedVector2D<T, U>> for TypedVector2D<T, U> {
|
||||
#[inline]
|
||||
fn approx_epsilon() -> Self {
|
||||
vec2(T::approx_epsilon(), T::approx_epsilon())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq(&self, other: &Self) -> bool {
|
||||
self.x.approx_eq(&other.x) && self.y.approx_eq(&other.y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
|
||||
self.x.approx_eq_eps(&other.x, &eps.x) && self.y.approx_eq_eps(&other.y, &eps.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> Into<[T; 2]> for TypedVector2D<T, U> {
|
||||
fn into(self) -> [T; 2] {
|
||||
self.to_array()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> From<[T; 2]> for TypedVector2D<T, U> {
|
||||
fn from(array: [T; 2]) -> Self {
|
||||
vec2(array[0], array[1])
|
||||
}
|
||||
}
|
||||
|
||||
define_matrix! {
|
||||
/// A 3d Vector tagged with a unit.
|
||||
pub struct TypedVector3D<T, U> {
|
||||
pub x: T,
|
||||
pub y: T,
|
||||
pub z: T,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default 3d vector type with no unit.
|
||||
///
|
||||
/// `Vector3D` provides the same methods as `TypedVector3D`.
|
||||
pub type Vector3D<T> = TypedVector3D<T, UnknownUnit>;
|
||||
|
||||
impl<T: Copy + Zero, U> TypedVector3D<T, U> {
|
||||
/// Constructor, setting all copmonents to zero.
|
||||
#[inline]
|
||||
pub fn zero() -> Self {
|
||||
vec3(Zero::zero(), Zero::zero(), Zero::zero())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_array_4d(&self) -> [T; 4] {
|
||||
[self.x, self.y, self.z, Zero::zero()]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for TypedVector3D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "({:?},{:?},{:?})", self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Display, U> fmt::Display for TypedVector3D<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "({},{},{})", self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> TypedVector3D<T, U> {
|
||||
/// Constructor taking scalar values directly.
|
||||
#[inline]
|
||||
pub fn new(x: T, y: T, z: T) -> Self {
|
||||
TypedVector3D { x: x, y: y, z: z, _unit: PhantomData }
|
||||
}
|
||||
|
||||
/// Constructor taking properly typed Lengths instead of scalar values.
|
||||
#[inline]
|
||||
pub fn from_lengths(x: Length<T, U>, y: Length<T, U>, z: Length<T, U>) -> TypedVector3D<T, U> {
|
||||
vec3(x.0, y.0, z.0)
|
||||
}
|
||||
|
||||
/// Cast this vector into a point.
|
||||
///
|
||||
/// Equivalent to adding this vector to the origin.
|
||||
#[inline]
|
||||
pub fn to_point(&self) -> TypedPoint3D<T, U> {
|
||||
point3(self.x, self.y, self.z)
|
||||
}
|
||||
|
||||
/// Returns self.x as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn x_typed(&self) -> Length<T, U> { Length::new(self.x) }
|
||||
|
||||
/// Returns self.y as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn y_typed(&self) -> Length<T, U> { Length::new(self.y) }
|
||||
|
||||
/// Returns self.z as a Length carrying the unit.
|
||||
#[inline]
|
||||
pub fn z_typed(&self) -> Length<T, U> { Length::new(self.z) }
|
||||
|
||||
#[inline]
|
||||
pub fn to_array(&self) -> [T; 3] { [self.x, self.y, self.z] }
|
||||
|
||||
/// Drop the units, preserving only the numeric value.
|
||||
#[inline]
|
||||
pub fn to_untyped(&self) -> Vector3D<T> {
|
||||
vec3(self.x, self.y, self.z)
|
||||
}
|
||||
|
||||
/// Tag a unitless value with units.
|
||||
#[inline]
|
||||
pub fn from_untyped(p: &Vector3D<T>) -> Self {
|
||||
vec3(p.x, p.y, p.z)
|
||||
}
|
||||
|
||||
/// Convert into a 2d vector.
|
||||
#[inline]
|
||||
pub fn to_2d(&self) -> TypedVector2D<T, U> {
|
||||
vec2(self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Mul<T, Output=T> +
|
||||
Add<T, Output=T> +
|
||||
Sub<T, Output=T> +
|
||||
Copy, U> TypedVector3D<T, U> {
|
||||
|
||||
// Dot product.
|
||||
#[inline]
|
||||
pub fn dot(self, other: Self) -> T {
|
||||
self.x * other.x +
|
||||
self.y * other.y +
|
||||
self.z * other.z
|
||||
}
|
||||
|
||||
// Cross product.
|
||||
#[inline]
|
||||
pub fn cross(self, other: Self) -> Self {
|
||||
vec3(
|
||||
self.y * other.z - self.z * other.y,
|
||||
self.z * other.x - self.x * other.z,
|
||||
self.x * other.y - self.y * other.x
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn normalize(self) -> Self where T: Float + ApproxEq<T> {
|
||||
let dot = self.dot(self);
|
||||
if dot.approx_eq(&T::zero()) {
|
||||
self
|
||||
} else {
|
||||
self / dot.sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn square_length(&self) -> T {
|
||||
self.x * self.x + self.y * self.y + self.z * self.z
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn length(&self) -> T where T: Float + ApproxEq<T> {
|
||||
self.square_length().sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> TypedVector3D<T, U>
|
||||
where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> {
|
||||
/// Linearly interpolate between this vector and another vector.
|
||||
///
|
||||
/// `t` is expected to be between zero and one.
|
||||
#[inline]
|
||||
pub fn lerp(&self, other: Self, t: T) -> Self {
|
||||
let one_t = T::one() - t;
|
||||
(*self) * one_t + other * t
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> Add for TypedVector3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn add(self, other: Self) -> Self {
|
||||
vec3(self.x + other.x, self.y + other.y, self.z + other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedVector3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn sub(self, other: Self) -> Self {
|
||||
vec3(self.x - other.x, self.y - other.y, self.z - other.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Add<T, Output=T>, U> AddAssign for TypedVector3D<T, U> {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, other: Self) {
|
||||
*self = *self + other
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Sub<T, Output=T>, U> SubAssign<TypedVector3D<T, U>> for TypedVector3D<T, U> {
|
||||
#[inline]
|
||||
fn sub_assign(&mut self, other: Self) {
|
||||
*self = *self - other
|
||||
}
|
||||
}
|
||||
|
||||
impl <T: Copy + Neg<Output=T>, U> Neg for TypedVector3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn neg(self) -> Self {
|
||||
vec3(-self.x, -self.y, -self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedVector3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn mul(self, scale: T) -> Self {
|
||||
Self::new(self.x * scale, self.y * scale, self.z * scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedVector3D<T, U> {
|
||||
type Output = Self;
|
||||
#[inline]
|
||||
fn div(self, scale: T) -> Self {
|
||||
Self::new(self.x / scale, self.y / scale, self.z / scale)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Mul<T, Output=T>, U> MulAssign<T> for TypedVector3D<T, U> {
|
||||
#[inline]
|
||||
fn mul_assign(&mut self, scale: T) {
|
||||
*self = *self * scale
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy + Div<T, Output=T>, U> DivAssign<T> for TypedVector3D<T, U> {
|
||||
#[inline]
|
||||
fn div_assign(&mut self, scale: T) {
|
||||
*self = *self / scale
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Float, U> TypedVector3D<T, U> {
|
||||
#[inline]
|
||||
pub fn min(self, other: Self) -> Self {
|
||||
vec3(self.x.min(other.x), self.y.min(other.y), self.z.min(other.z))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max(self, other: Self) -> Self {
|
||||
vec3(self.x.max(other.x), self.y.max(other.y), self.z.max(other.z))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Round, U> TypedVector3D<T, U> {
|
||||
/// Rounds each component to the nearest integer value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn round(&self) -> Self {
|
||||
vec3(self.x.round(), self.y.round(), self.z.round())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Ceil, U> TypedVector3D<T, U> {
|
||||
/// Rounds each component to the smallest integer equal or greater than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn ceil(&self) -> Self {
|
||||
vec3(self.x.ceil(), self.y.ceil(), self.z.ceil())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Floor, U> TypedVector3D<T, U> {
|
||||
/// Rounds each component to the biggest integer equal or lower than the original value.
|
||||
///
|
||||
/// This behavior is preserved for negative values (unlike the basic cast).
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn floor(&self) -> Self {
|
||||
vec3(self.x.floor(), self.y.floor(), self.z.floor())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: NumCast + Copy, U> TypedVector3D<T, U> {
|
||||
/// Cast from one numeric representation to another, preserving the units.
|
||||
///
|
||||
/// When casting from floating vector to integer coordinates, the decimals are truncated
|
||||
/// as one would expect from a simple cast, but this behavior does not always make sense
|
||||
/// geometrically. Consider using round(), ceil or floor() before casting.
|
||||
#[inline]
|
||||
pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedVector3D<NewT, U>> {
|
||||
match (NumCast::from(self.x),
|
||||
NumCast::from(self.y),
|
||||
NumCast::from(self.z)) {
|
||||
(Some(x), Some(y), Some(z)) => Some(vec3(x, y, z)),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience functions for common casts
|
||||
|
||||
/// Cast into an `f32` vector.
|
||||
#[inline]
|
||||
pub fn to_f32(&self) -> TypedVector3D<f32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `usize` vector, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating vector vectors, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_usize(&self) -> TypedVector3D<usize, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i32` vector, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating vector vectors, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i32(&self) -> TypedVector3D<i32, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
|
||||
/// Cast into an `i64` vector, truncating decimals if any.
|
||||
///
|
||||
/// When casting from floating vector vectors, it is worth considering whether
|
||||
/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
|
||||
/// the desired conversion behavior.
|
||||
#[inline]
|
||||
pub fn to_i64(&self) -> TypedVector3D<i64, U> {
|
||||
self.cast().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy+ApproxEq<T>, U> ApproxEq<TypedVector3D<T, U>> for TypedVector3D<T, U> {
|
||||
#[inline]
|
||||
fn approx_epsilon() -> Self {
|
||||
vec3(T::approx_epsilon(), T::approx_epsilon(), T::approx_epsilon())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq(&self, other: &Self) -> bool {
|
||||
self.x.approx_eq(&other.x)
|
||||
&& self.y.approx_eq(&other.y)
|
||||
&& self.z.approx_eq(&other.z)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
|
||||
self.x.approx_eq_eps(&other.x, &eps.x)
|
||||
&& self.y.approx_eq_eps(&other.y, &eps.y)
|
||||
&& self.z.approx_eq_eps(&other.z, &eps.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> Into<[T; 3]> for TypedVector3D<T, U> {
|
||||
fn into(self) -> [T; 3] {
|
||||
self.to_array()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy, U> From<[T; 3]> for TypedVector3D<T, U> {
|
||||
fn from(array: [T; 3]) -> Self {
|
||||
vec3(array[0], array[1], array[2])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Convenience constructor.
|
||||
#[inline]
|
||||
pub fn vec2<T: Copy, U>(x: T, y: T) -> TypedVector2D<T, U> {
|
||||
TypedVector2D::new(x, y)
|
||||
}
|
||||
|
||||
/// Convenience constructor.
|
||||
#[inline]
|
||||
pub fn vec3<T: Copy, U>(x: T, y: T, z: T) -> TypedVector3D<T, U> {
|
||||
TypedVector3D::new(x, y, z)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod vector2d {
|
||||
use super::{Vector2D, vec2};
|
||||
type Vec2 = Vector2D<f32>;
|
||||
|
||||
#[test]
|
||||
pub fn test_scalar_mul() {
|
||||
let p1: Vec2 = vec2(3.0, 5.0);
|
||||
|
||||
let result = p1 * 5.0;
|
||||
|
||||
assert_eq!(result, Vector2D::new(15.0, 25.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_dot() {
|
||||
let p1: Vec2 = vec2(2.0, 7.0);
|
||||
let p2: Vec2 = vec2(13.0, 11.0);
|
||||
assert_eq!(p1.dot(p2), 103.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_cross() {
|
||||
let p1: Vec2 = vec2(4.0, 7.0);
|
||||
let p2: Vec2 = vec2(13.0, 8.0);
|
||||
let r = p1.cross(p2);
|
||||
assert_eq!(r, -59.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_normalize() {
|
||||
let p0: Vec2 = Vec2::zero();
|
||||
let p1: Vec2 = vec2(4.0, 0.0);
|
||||
let p2: Vec2 = vec2(3.0, -4.0);
|
||||
assert_eq!(p0.normalize(), p0);
|
||||
assert_eq!(p1.normalize(), vec2(1.0, 0.0));
|
||||
assert_eq!(p2.normalize(), vec2(0.6, -0.8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_min() {
|
||||
let p1: Vec2 = vec2(1.0, 3.0);
|
||||
let p2: Vec2 = vec2(2.0, 2.0);
|
||||
|
||||
let result = p1.min(p2);
|
||||
|
||||
assert_eq!(result, vec2(1.0, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_max() {
|
||||
let p1: Vec2 = vec2(1.0, 3.0);
|
||||
let p2: Vec2 = vec2(2.0, 2.0);
|
||||
|
||||
let result = p1.max(p2);
|
||||
|
||||
assert_eq!(result, vec2(2.0, 3.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod typedvector2d {
|
||||
use super::{TypedVector2D, vec2};
|
||||
use scale_factor::ScaleFactor;
|
||||
|
||||
pub enum Mm {}
|
||||
pub enum Cm {}
|
||||
|
||||
pub type Vector2DMm<T> = TypedVector2D<T, Mm>;
|
||||
pub type Vector2DCm<T> = TypedVector2D<T, Cm>;
|
||||
|
||||
#[test]
|
||||
pub fn test_add() {
|
||||
let p1 = Vector2DMm::new(1.0, 2.0);
|
||||
let p2 = Vector2DMm::new(3.0, 4.0);
|
||||
|
||||
let result = p1 + p2;
|
||||
|
||||
assert_eq!(result, vec2(4.0, 6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_add_assign() {
|
||||
let mut p1 = Vector2DMm::new(1.0, 2.0);
|
||||
p1 += vec2(3.0, 4.0);
|
||||
|
||||
assert_eq!(p1, vec2(4.0, 6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_scalar_mul() {
|
||||
let p1 = Vector2DMm::new(1.0, 2.0);
|
||||
let cm_per_mm: ScaleFactor<f32, Mm, Cm> = ScaleFactor::new(0.1);
|
||||
|
||||
let result: Vector2DCm<f32> = p1 * cm_per_mm;
|
||||
|
||||
assert_eq!(result, vec2(0.1, 0.2));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod vector3d {
|
||||
use super::{Vector3D, vec3};
|
||||
type Vec3 = Vector3D<f32>;
|
||||
|
||||
#[test]
|
||||
pub fn test_dot() {
|
||||
let p1: Vec3 = vec3(7.0, 21.0, 32.0);
|
||||
let p2: Vec3 = vec3(43.0, 5.0, 16.0);
|
||||
assert_eq!(p1.dot(p2), 918.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_cross() {
|
||||
let p1: Vec3 = vec3(4.0, 7.0, 9.0);
|
||||
let p2: Vec3 = vec3(13.0, 8.0, 3.0);
|
||||
let p3 = p1.cross(p2);
|
||||
assert_eq!(p3, vec3(-51.0, 105.0, -59.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_normalize() {
|
||||
let p0: Vec3 = Vec3::zero();
|
||||
let p1: Vec3 = vec3(0.0, -6.0, 0.0);
|
||||
let p2: Vec3 = vec3(1.0, 2.0, -2.0);
|
||||
assert_eq!(p0.normalize(), p0);
|
||||
assert_eq!(p1.normalize(), vec3(0.0, -1.0, 0.0));
|
||||
assert_eq!(p2.normalize(), vec3(1.0/3.0, 2.0/3.0, -2.0/3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_min() {
|
||||
let p1: Vec3 = vec3(1.0, 3.0, 5.0);
|
||||
let p2: Vec3 = vec3(2.0, 2.0, -1.0);
|
||||
|
||||
let result = p1.min(p2);
|
||||
|
||||
assert_eq!(result, vec3(1.0, 2.0, -1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_max() {
|
||||
let p1: Vec3 = vec3(1.0, 3.0, 5.0);
|
||||
let p2: Vec3 = vec3(2.0, 2.0, -1.0);
|
||||
|
||||
let result = p1.max(p2);
|
||||
|
||||
assert_eq!(result, vec3(2.0, 3.0, 5.0));
|
||||
}
|
||||
}
|
|
@ -1 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"f9b1ca6ae27d1c18215265024629a8960c31379f206d9ed20f64e0b2dcf79805",".travis.yml":"b76d49f66f842c652d40825c67791352364a6b6bbb7d8d1009f2ac79eb413e66","Cargo.toml":"42a432c2bd866b37698e064e7f72b6cf96d7aa57dcc5ae32c9474bd6eef745a2","LICENSE":"b946744aeda89b467929585fe8eeb5461847695220c1b168fb375d8abd4ea3d0","README.md":"62f99334c17b451342fcea70eb1cc27b26612616b7c1a58fab50dd493f766f32","benches/split.rs":"dfe01759652e2098f20547e0ddcc1b2937e88c6d6ddb025353c037a46b7ef85d","src/bsp.rs":"66e1690aa8540f744ee013ac0e550ecdee84633727cb3a2d8239db3597ad25d6","src/lib.rs":"21d6135c10dd820c2b9ac484cc018e1149f2bf44c315d27134edd3ecb8a7f3d2","src/naive.rs":"444d3298224009209ae329458fe8df953193b15a04da29cdd6f498572a6471bf","tests/main.rs":"d65d7fe01ff3091a9b470a2f26b28108968ca5d32a5a14defba4336df31c7d7f","tests/split.rs":"19d5bfaaf93115ddecdac0f720893c61b2ed73a0bcb4711534ac7e4500cc06ae"},"package":"da4c13e9ba1388fd628ec2bcd69f3346dec64357e9b552601b244f92189d4610"}
|
||||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"f9b1ca6ae27d1c18215265024629a8960c31379f206d9ed20f64e0b2dcf79805",".travis.yml":"b76d49f66f842c652d40825c67791352364a6b6bbb7d8d1009f2ac79eb413e66","Cargo.toml":"dafb727ecf8ce1c097737e0fc3c82a047591ac34c1c04362cd489c1e1fb1f91e","LICENSE":"b946744aeda89b467929585fe8eeb5461847695220c1b168fb375d8abd4ea3d0","README.md":"62f99334c17b451342fcea70eb1cc27b26612616b7c1a58fab50dd493f766f32","benches/split.rs":"dfe01759652e2098f20547e0ddcc1b2937e88c6d6ddb025353c037a46b7ef85d","src/bsp.rs":"66e1690aa8540f744ee013ac0e550ecdee84633727cb3a2d8239db3597ad25d6","src/lib.rs":"21d6135c10dd820c2b9ac484cc018e1149f2bf44c315d27134edd3ecb8a7f3d2","src/naive.rs":"444d3298224009209ae329458fe8df953193b15a04da29cdd6f498572a6471bf","tests/main.rs":"d65d7fe01ff3091a9b470a2f26b28108968ca5d32a5a14defba4336df31c7d7f","tests/split.rs":"19d5bfaaf93115ddecdac0f720893c61b2ed73a0bcb4711534ac7e4500cc06ae"},"package":"e57800a97ca52c556db6b6184a3201f05366ad5e11876f7d17e234589ca2fa26"}
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "plane-split"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
description = "Plane splitting"
|
||||
authors = ["Dzmitry Malyshau <kvark@mozilla.com>"]
|
||||
license = "MPL-2.0"
|
||||
|
@ -10,6 +10,6 @@ documentation = "https://docs.rs/plane-split"
|
|||
|
||||
[dependencies]
|
||||
binary-space-partition = "0.1.2"
|
||||
euclid = "0.14.2"
|
||||
euclid = "0.15"
|
||||
log = "0.3"
|
||||
num-traits = {version = "0.1.37", default-features = false}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"e2817af66db5f058a55b5f126ca9a663925bfeb36a592a4121e7e9a44d3a3453","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"ebe318a04cf4e547e0f3ab97f1345ecb553358ee13ea81f99e3323e37d70ccdf","src/bytes.rs":"2b6a9c2c3d6eabe8633adee6655a3b94f0d1e931e740e72699b6965bee21e226","src/de/content.rs":"469d3298d4109d514a8cd630273a288a361544979e2ab23aaa325b2201f9361f","src/de/from_primitive.rs":"b1bd165e343a4380965551709119ef9ed895e4b025045a810dabd671511ba3ab","src/de/impls.rs":"762c3f32627d12555ccd08fcdf3dfb621403c35cde8a5af7866e2ad74c95a4c8","src/de/mod.rs":"365ee7038c53e88cddd451afd11d459f65185fd04523bd000a6b424ac4f71db7","src/de/private.rs":"2578dbc89c2f2a852caed3fdc40f710d4828d085c4e954dd96789d678583424e","src/de/value.rs":"67a34c03fda6521c082548984b0116494e5fbff7e60e30e06f0dda62d9d3e083","src/error.rs":"3af5286c1daad9bfd504693f8a8587f7044c9b9520e23e072549c43a72e4821d","src/export.rs":"0b8e6b642010ad6a71f13f5facfd91e9da1d7c99d479dba020dec10e88fb6b0f","src/iter.rs":"af3c43712c240b3a06870e0b0b6e837b142d5a65c62742fa358fe36a9d9319a7","src/lib.rs":"75df159c150e62c99887c0a4f23ed1271c9eb910ebc79a2d4bd279b0e11ce7e3","src/macros.rs":"af1f75bb34460b814e44f7bc67bdd1dc1bba97f1f2a31744c22e1bfcdc29499a","src/ser/content.rs":"f1cd3724e5ddeacb75b3585b2fd2be7c42fc764444b1f764e31ed9fe49f62025","src/ser/impls.rs":"51d4036b8309381af8267375778bf80c3a9114577c03a04da9a679462077efac","src/ser/impossible.rs":"f1332a1250f9c1d85d679653ade502cf99bdff0344b9f864e6cf1a1789d7c597","src/ser/mod.rs":"d1d821488453651a986bb4e4608f72868c09a71a8dbf693584758b25603ae8bf","src/ser/private.rs":"3999dc19d61d43a64d5d1bdda61f80ea16405a926b074b5441b39d87318be73b","src/utils.rs":"ed271c0825c01d7b24968bf47ce9e2475ca219faf733eb33831d6e19bf07aaf1"},"package":"05a67b8a53f885f4b6e3ed183806035819f9862474e747fe4488a6d63bcbfcb7"}
|
|
@ -1,34 +0,0 @@
|
|||
[package]
|
||||
name = "serde"
|
||||
version = "0.9.9"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde/"
|
||||
keywords = ["serde", "serialization", "no_std"]
|
||||
categories = ["encoding"]
|
||||
readme = "../README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
|
||||
std = []
|
||||
unstable = []
|
||||
alloc = ["unstable"]
|
||||
collections = ["alloc"]
|
||||
unstable-testing = ["unstable", "std"]
|
||||
|
||||
# to get serde_derive picked up by play.integer32.com
|
||||
playground = ["serde_derive"]
|
||||
|
||||
[dependencies]
|
||||
serde_derive = { version = "0.9", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_derive = "0.9"
|
|
@ -1,201 +0,0 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -1,315 +0,0 @@
|
|||
//! Wrapper types to enable optimized handling of `&[u8]` and `Vec<u8>`.
|
||||
//!
|
||||
//! Without specialization, Rust forces us to treat `&[u8]` just like any other
|
||||
//! slice and `Vec<u8>` just like any other vector. In reality this particular
|
||||
//! slice and vector can often be serialized and deserialized in a more
|
||||
//! efficient, compact representation in many formats.
|
||||
//!
|
||||
//! When working with such a format, you can opt into specialized handling of
|
||||
//! `&[u8]` by wrapping it in `bytes::Bytes` and `Vec<u8>` by wrapping it in
|
||||
//! `bytes::ByteBuf`.
|
||||
//!
|
||||
//! Rust support for specialization is being tracked in
|
||||
//! [rust-lang/rust#31844][specialization]. Once it lands in the stable compiler
|
||||
//! we will be deprecating these wrapper types in favor of optimizing `&[u8]`
|
||||
//! and `Vec<u8>` out of the box.
|
||||
//!
|
||||
//! [specialization]: https://github.com/rust-lang/rust/issues/31844
|
||||
|
||||
use core::{ops, fmt, char, iter, slice};
|
||||
use core::fmt::Write;
|
||||
|
||||
use ser;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub use self::bytebuf::ByteBuf;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[doc(hidden)] // does anybody need this?
|
||||
pub use self::bytebuf::ByteBufVisitor;
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::Vec;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Wraps a `&[u8]` in order to serialize in an efficient way. Does not support
|
||||
/// deserialization.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde_derive;
|
||||
/// # extern crate serde;
|
||||
/// # use std::net::IpAddr;
|
||||
/// #
|
||||
/// use serde::bytes::Bytes;
|
||||
///
|
||||
/// # #[allow(dead_code)]
|
||||
/// #[derive(Serialize)]
|
||||
/// struct Packet<'a> {
|
||||
/// destination: IpAddr,
|
||||
/// payload: Bytes<'a>,
|
||||
/// }
|
||||
/// #
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||
pub struct Bytes<'a> {
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Bytes<'a> {
|
||||
/// Wrap an existing `&[u8]`.
|
||||
pub fn new(bytes: &'a [u8]) -> Self {
|
||||
Bytes { bytes: bytes }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> fmt::Debug for Bytes<'a> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
try!(f.write_str("b\""));
|
||||
for c in escape_bytestring(self.bytes) {
|
||||
try!(f.write_char(c));
|
||||
}
|
||||
f.write_char('"')
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a [u8]> for Bytes<'a> {
|
||||
fn from(bytes: &'a [u8]) -> Self {
|
||||
Bytes::new(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a> From<&'a Vec<u8>> for Bytes<'a> {
|
||||
fn from(bytes: &'a Vec<u8>) -> Self {
|
||||
Bytes::new(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Into<&'a [u8]> for Bytes<'a> {
|
||||
fn into(self) -> &'a [u8] {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ops::Deref for Bytes<'a> {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ser::Serialize for Bytes<'a> {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: ser::Serializer
|
||||
{
|
||||
serializer.serialize_bytes(self.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
mod bytebuf {
|
||||
use core::cmp;
|
||||
use core::ops;
|
||||
use core::fmt;
|
||||
use core::fmt::Write;
|
||||
|
||||
use ser;
|
||||
use de;
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::{String, Vec};
|
||||
|
||||
/// Wraps a `Vec<u8>` in order to serialize and deserialize in an efficient
|
||||
/// way.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde_derive;
|
||||
/// # extern crate serde;
|
||||
/// # use std::net::IpAddr;
|
||||
/// #
|
||||
/// use serde::bytes::ByteBuf;
|
||||
///
|
||||
/// # #[allow(dead_code)]
|
||||
/// #[derive(Serialize, Deserialize)]
|
||||
/// struct Packet {
|
||||
/// destination: IpAddr,
|
||||
/// payload: ByteBuf,
|
||||
/// }
|
||||
/// #
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||
pub struct ByteBuf {
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ByteBuf {
|
||||
/// Construct a new, empty `ByteBuf`.
|
||||
pub fn new() -> Self {
|
||||
ByteBuf::from(Vec::new())
|
||||
}
|
||||
|
||||
/// Construct a new, empty `ByteBuf` with the specified capacity.
|
||||
pub fn with_capacity(cap: usize) -> Self {
|
||||
ByteBuf::from(Vec::with_capacity(cap))
|
||||
}
|
||||
|
||||
/// Wrap existing bytes in a `ByteBuf`.
|
||||
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
|
||||
ByteBuf { bytes: bytes.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ByteBuf {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
try!(f.write_str("b\""));
|
||||
for c in super::escape_bytestring(self.bytes.as_ref()) {
|
||||
try!(f.write_char(c));
|
||||
}
|
||||
f.write_char('"')
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Vec<u8>> for ByteBuf {
|
||||
fn into(self) -> Vec<u8> {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for ByteBuf {
|
||||
fn from(bytes: Vec<u8>) -> Self {
|
||||
ByteBuf::from(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Vec<u8>> for ByteBuf {
|
||||
fn as_ref(&self) -> &Vec<u8> {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for ByteBuf {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<Vec<u8>> for ByteBuf {
|
||||
fn as_mut(&mut self) -> &mut Vec<u8> {
|
||||
&mut self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<[u8]> for ByteBuf {
|
||||
fn as_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Deref for ByteBuf {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] {
|
||||
&self.bytes[..]
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::DerefMut for ByteBuf {
|
||||
fn deref_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.bytes[..]
|
||||
}
|
||||
}
|
||||
|
||||
impl ser::Serialize for ByteBuf {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: ser::Serializer
|
||||
{
|
||||
serializer.serialize_bytes(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// This type implements the `serde::de::Visitor` trait for a `ByteBuf`.
|
||||
pub struct ByteBufVisitor;
|
||||
|
||||
impl de::Visitor for ByteBufVisitor {
|
||||
type Value = ByteBuf;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("byte array")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(self) -> Result<ByteBuf, E>
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error>
|
||||
where V: de::SeqVisitor
|
||||
{
|
||||
let len = cmp::min(visitor.size_hint().0, 4096);
|
||||
let mut values = Vec::with_capacity(len);
|
||||
|
||||
while let Some(value) = try!(visitor.visit()) {
|
||||
values.push(value);
|
||||
}
|
||||
|
||||
Ok(ByteBuf::from(values))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E>
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E>
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E>
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<ByteBuf, E>
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserialize for ByteBuf {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
|
||||
where D: de::Deserializer
|
||||
{
|
||||
deserializer.deserialize_byte_buf(ByteBufVisitor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[inline]
|
||||
fn escape_bytestring<'a>
|
||||
(bytes: &'a [u8])
|
||||
-> iter::FlatMap<slice::Iter<'a, u8>, char::EscapeDefault, fn(&u8) -> char::EscapeDefault> {
|
||||
fn f(b: &u8) -> char::EscapeDefault {
|
||||
char::from_u32(*b as u32).unwrap().escape_default()
|
||||
}
|
||||
bytes.iter().flat_map(f as fn(&u8) -> char::EscapeDefault)
|
||||
}
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -1,409 +0,0 @@
|
|||
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
||||
// file at the top-level directory of this distribution and at
|
||||
// http://rust-lang.org/COPYRIGHT.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
// Extracted from https://github.com/rust-num/num.
|
||||
|
||||
// Rust 1.5 is unhappy that this private module is undocumented.
|
||||
#![allow(missing_docs)]
|
||||
|
||||
use core::{usize, u8, u16, u32, u64};
|
||||
use core::{isize, i8, i16, i32, i64};
|
||||
use core::{f32, f64};
|
||||
use core::mem::size_of;
|
||||
|
||||
/// Numbers which have upper and lower bounds
|
||||
pub trait Bounded {
|
||||
// FIXME (#5527): These should be associated constants
|
||||
/// returns the smallest finite number this type can represent
|
||||
fn min_value() -> Self;
|
||||
/// returns the largest finite number this type can represent
|
||||
fn max_value() -> Self;
|
||||
}
|
||||
|
||||
macro_rules! bounded_impl {
|
||||
($t:ty, $min:expr, $max:expr) => {
|
||||
impl Bounded for $t {
|
||||
#[inline]
|
||||
fn min_value() -> $t { $min }
|
||||
|
||||
#[inline]
|
||||
fn max_value() -> $t { $max }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bounded_impl!(usize, usize::MIN, usize::MAX);
|
||||
bounded_impl!(u8, u8::MIN, u8::MAX);
|
||||
bounded_impl!(u16, u16::MIN, u16::MAX);
|
||||
bounded_impl!(u32, u32::MIN, u32::MAX);
|
||||
bounded_impl!(u64, u64::MIN, u64::MAX);
|
||||
|
||||
bounded_impl!(isize, isize::MIN, isize::MAX);
|
||||
bounded_impl!(i8, i8::MIN, i8::MAX);
|
||||
bounded_impl!(i16, i16::MIN, i16::MAX);
|
||||
bounded_impl!(i32, i32::MIN, i32::MAX);
|
||||
bounded_impl!(i64, i64::MIN, i64::MAX);
|
||||
|
||||
bounded_impl!(f32, f32::MIN, f32::MAX);
|
||||
bounded_impl!(f64, f64::MIN, f64::MAX);
|
||||
|
||||
/// A generic trait for converting a value to a number.
|
||||
pub trait ToPrimitive {
|
||||
/// Converts the value of `self` to an `isize`.
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> {
|
||||
self.to_i64().and_then(|x| x.to_isize())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i8`.
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> {
|
||||
self.to_i64().and_then(|x| x.to_i8())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i16`.
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> {
|
||||
self.to_i64().and_then(|x| x.to_i16())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i32`.
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> {
|
||||
self.to_i64().and_then(|x| x.to_i32())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `i64`.
|
||||
fn to_i64(&self) -> Option<i64>;
|
||||
|
||||
/// Converts the value of `self` to a `usize`.
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> {
|
||||
self.to_u64().and_then(|x| x.to_usize())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u8`.
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> {
|
||||
self.to_u64().and_then(|x| x.to_u8())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u16`.
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> {
|
||||
self.to_u64().and_then(|x| x.to_u16())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u32`.
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> {
|
||||
self.to_u64().and_then(|x| x.to_u32())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `u64`.
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64>;
|
||||
|
||||
/// Converts the value of `self` to an `f32`.
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> {
|
||||
self.to_f64().and_then(|x| x.to_f32())
|
||||
}
|
||||
|
||||
/// Converts the value of `self` to an `f64`.
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> {
|
||||
self.to_i64().and_then(|x| x.to_f64())
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_int_to_int {
|
||||
($SrcT:ty, $DstT:ty, $slf:expr) => (
|
||||
{
|
||||
if size_of::<$SrcT>() <= size_of::<$DstT>() {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
let n = $slf as i64;
|
||||
let min_value: $DstT = Bounded::min_value();
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if min_value as i64 <= n && n <= max_value as i64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_int_to_uint {
|
||||
($SrcT:ty, $DstT:ty, $slf:expr) => (
|
||||
{
|
||||
let zero: $SrcT = 0;
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if zero <= $slf && $slf as u64 <= max_value as u64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_int {
|
||||
($T:ty) => (
|
||||
impl ToPrimitive for $T {
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> { impl_to_primitive_int_to_int!($T, isize, *self) }
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
|
||||
#[inline]
|
||||
fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> { impl_to_primitive_int_to_uint!($T, usize, *self) }
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_to_primitive_int! { isize }
|
||||
impl_to_primitive_int! { i8 }
|
||||
impl_to_primitive_int! { i16 }
|
||||
impl_to_primitive_int! { i32 }
|
||||
impl_to_primitive_int! { i64 }
|
||||
|
||||
macro_rules! impl_to_primitive_uint_to_int {
|
||||
($DstT:ty, $slf:expr) => (
|
||||
{
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if $slf as u64 <= max_value as u64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_uint_to_uint {
|
||||
($SrcT:ty, $DstT:ty, $slf:expr) => (
|
||||
{
|
||||
if size_of::<$SrcT>() <= size_of::<$DstT>() {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
let zero: $SrcT = 0;
|
||||
let max_value: $DstT = Bounded::max_value();
|
||||
if zero <= $slf && $slf as u64 <= max_value as u64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_uint {
|
||||
($T:ty) => (
|
||||
impl ToPrimitive for $T {
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> { impl_to_primitive_uint_to_int!(isize, *self) }
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
|
||||
#[inline]
|
||||
fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> {
|
||||
impl_to_primitive_uint_to_uint!($T, usize, *self)
|
||||
}
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
|
||||
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_to_primitive_uint! { usize }
|
||||
impl_to_primitive_uint! { u8 }
|
||||
impl_to_primitive_uint! { u16 }
|
||||
impl_to_primitive_uint! { u32 }
|
||||
impl_to_primitive_uint! { u64 }
|
||||
|
||||
macro_rules! impl_to_primitive_float_to_float {
|
||||
($SrcT:ident, $DstT:ident, $slf:expr) => (
|
||||
if size_of::<$SrcT>() <= size_of::<$DstT>() {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
let n = $slf as f64;
|
||||
let max_value: $SrcT = ::core::$SrcT::MAX;
|
||||
if -max_value as f64 <= n && n <= max_value as f64 {
|
||||
Some($slf as $DstT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! impl_to_primitive_float {
|
||||
($T:ident) => (
|
||||
impl ToPrimitive for $T {
|
||||
#[inline]
|
||||
fn to_isize(&self) -> Option<isize> { Some(*self as isize) }
|
||||
#[inline]
|
||||
fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
|
||||
#[inline]
|
||||
fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
|
||||
#[inline]
|
||||
fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
|
||||
#[inline]
|
||||
fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
|
||||
|
||||
#[inline]
|
||||
fn to_usize(&self) -> Option<usize> { Some(*self as usize) }
|
||||
#[inline]
|
||||
fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
|
||||
#[inline]
|
||||
fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
|
||||
#[inline]
|
||||
fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
|
||||
#[inline]
|
||||
fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
|
||||
|
||||
#[inline]
|
||||
fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
|
||||
#[inline]
|
||||
fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_to_primitive_float! { f32 }
|
||||
impl_to_primitive_float! { f64 }
|
||||
|
||||
pub trait FromPrimitive: Sized {
|
||||
#[inline]
|
||||
fn from_isize(n: isize) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_i8(n: i8) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_i16(n: i16) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_i32(n: i32) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
|
||||
fn from_i64(n: i64) -> Option<Self>;
|
||||
|
||||
#[inline]
|
||||
fn from_usize(n: usize) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_u8(n: u8) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_u16(n: u16) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_u32(n: u32) -> Option<Self> {
|
||||
FromPrimitive::from_u64(n as u64)
|
||||
}
|
||||
|
||||
fn from_u64(n: u64) -> Option<Self>;
|
||||
|
||||
#[inline]
|
||||
fn from_f32(n: f32) -> Option<Self> {
|
||||
FromPrimitive::from_f64(n as f64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_f64(n: f64) -> Option<Self> {
|
||||
FromPrimitive::from_i64(n as i64)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_from_primitive {
|
||||
($T:ty, $to_ty:ident) => (
|
||||
impl FromPrimitive for $T {
|
||||
#[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
|
||||
|
||||
#[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
|
||||
|
||||
#[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
|
||||
#[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
impl_from_primitive! { isize, to_isize }
|
||||
impl_from_primitive! { i8, to_i8 }
|
||||
impl_from_primitive! { i16, to_i16 }
|
||||
impl_from_primitive! { i32, to_i32 }
|
||||
impl_from_primitive! { i64, to_i64 }
|
||||
impl_from_primitive! { usize, to_usize }
|
||||
impl_from_primitive! { u8, to_u8 }
|
||||
impl_from_primitive! { u16, to_u16 }
|
||||
impl_from_primitive! { u32, to_u32 }
|
||||
impl_from_primitive! { u64, to_u64 }
|
||||
impl_from_primitive! { f32, to_f32 }
|
||||
impl_from_primitive! { f64, to_f64 }
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -1,44 +0,0 @@
|
|||
use core::marker::PhantomData;
|
||||
|
||||
use de::{Deserialize, Deserializer, Error, Visitor};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub use de::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor,
|
||||
TagOrContentField, TagOrContentFieldVisitor, InternallyTaggedUnitVisitor,
|
||||
UntaggedUnitVisitor};
|
||||
|
||||
/// If the missing field is of type `Option<T>` then treat is as `None`,
|
||||
/// otherwise it is an error.
|
||||
pub fn missing_field<V, E>(field: &'static str) -> Result<V, E>
|
||||
where V: Deserialize,
|
||||
E: Error
|
||||
{
|
||||
struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>);
|
||||
|
||||
impl<E> Deserializer for MissingFieldDeserializer<E>
|
||||
where E: Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, _visitor: V) -> Result<V::Value, E>
|
||||
where V: Visitor
|
||||
{
|
||||
Err(Error::missing_field(self.0))
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
|
||||
where V: Visitor
|
||||
{
|
||||
visitor.visit_none()
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||
seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
let deserializer = MissingFieldDeserializer(field, PhantomData);
|
||||
Deserialize::deserialize(deserializer)
|
||||
}
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -1,17 +0,0 @@
|
|||
//! A stand-in for `std::error`
|
||||
use core::fmt::{Debug, Display};
|
||||
|
||||
/// A stand-in for `std::error::Error`, which requires no allocation.
|
||||
pub trait Error: Debug + Display {
|
||||
/// A short description of the error.
|
||||
///
|
||||
/// The description should not contain newlines or sentence-ending
|
||||
/// punctuation, to facilitate embedding in larger user-facing
|
||||
/// strings.
|
||||
fn description(&self) -> &str;
|
||||
|
||||
/// The lower-level cause of this error, if any.
|
||||
fn cause(&self) -> Option<&Error> {
|
||||
None
|
||||
}
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::String;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::borrow::Cow;
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::borrow::Cow;
|
||||
|
||||
pub use core::default::Default;
|
||||
pub use core::fmt;
|
||||
pub use core::marker::PhantomData;
|
||||
pub use core::option::Option::{self, None, Some};
|
||||
pub use core::result::Result::{self, Ok, Err};
|
||||
|
||||
#[cfg(any(feature = "collections", feature = "std"))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
|
||||
String::from_utf8_lossy(bytes)
|
||||
}
|
||||
|
||||
// The generated code calls this like:
|
||||
//
|
||||
// let value = &_serde::export::from_utf8_lossy(bytes);
|
||||
// Err(_serde::de::Error::unknown_variant(value, VARIANTS))
|
||||
//
|
||||
// so it is okay for the return type to be different from the std case as long
|
||||
// as the above works.
|
||||
#[cfg(not(any(feature = "collections", feature = "std")))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> &str {
|
||||
use core::str;
|
||||
// Three unicode replacement characters if it fails. They look like a
|
||||
// white-on-black question mark. The user will recognize it as invalid
|
||||
// UTF-8.
|
||||
str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}")
|
||||
}
|
|
@ -1,73 +0,0 @@
|
|||
//! Module that contains helper iterators.
|
||||
|
||||
use std::io;
|
||||
use std::iter::Peekable;
|
||||
|
||||
/// Iterator over a byte stream that tracks the current position's line and column.
|
||||
pub struct LineColIterator<Iter: Iterator<Item = io::Result<u8>>> {
|
||||
iter: Iter,
|
||||
line: usize,
|
||||
col: usize,
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Iter> {
|
||||
/// Construct a new `LineColIterator<Iter>`.
|
||||
pub fn new(iter: Iter) -> LineColIterator<Iter> {
|
||||
LineColIterator {
|
||||
iter: iter,
|
||||
line: 1,
|
||||
col: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Report the current line inside the iterator.
|
||||
pub fn line(&self) -> usize {
|
||||
self.line
|
||||
}
|
||||
|
||||
/// Report the current column inside the iterator.
|
||||
pub fn col(&self) -> usize {
|
||||
self.col
|
||||
}
|
||||
|
||||
/// Gets a reference to the underlying iterator.
|
||||
pub fn get_ref(&self) -> &Iter {
|
||||
&self.iter
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the underlying iterator.
|
||||
pub fn get_mut(&mut self) -> &mut Iter {
|
||||
&mut self.iter
|
||||
}
|
||||
|
||||
/// Unwraps this `LineColIterator`, returning the underlying iterator.
|
||||
pub fn into_inner(self) -> Iter {
|
||||
self.iter
|
||||
}
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Peekable<Iter>> {
|
||||
/// peeks at the next value
|
||||
pub fn peek(&mut self) -> Option<&io::Result<u8>> {
|
||||
self.iter.peek()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item = io::Result<u8>>> Iterator for LineColIterator<Iter> {
|
||||
type Item = io::Result<u8>;
|
||||
fn next(&mut self) -> Option<io::Result<u8>> {
|
||||
match self.iter.next() {
|
||||
None => None,
|
||||
Some(Ok(b'\n')) => {
|
||||
self.line += 1;
|
||||
self.col = 0;
|
||||
Some(Ok(b'\n'))
|
||||
}
|
||||
Some(Ok(c)) => {
|
||||
self.col += 1;
|
||||
Some(Ok(c))
|
||||
}
|
||||
Some(Err(e)) => Some(Err(e)),
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,107 +0,0 @@
|
|||
//! # Serde
|
||||
//!
|
||||
//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data
|
||||
//! structures efficiently and generically.
|
||||
//!
|
||||
//! The Serde ecosystem consists of data structures that know how to serialize
|
||||
//! and deserialize themselves along with data formats that know how to
|
||||
//! serialize and deserialize other things. Serde provides the layer by which
|
||||
//! these two groups interact with each other, allowing any supported data
|
||||
//! structure to be serialized and deserialized using any supported data format.
|
||||
//!
|
||||
//! See the Serde website https://serde.rs/ for additional documentation and
|
||||
//! usage examples.
|
||||
//!
|
||||
//! ### Design
|
||||
//!
|
||||
//! Where many other languages rely on runtime reflection for serializing data,
|
||||
//! Serde is instead built on Rust's powerful trait system. A data structure
|
||||
//! that knows how to serialize and deserialize itself is one that implements
|
||||
//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's code
|
||||
//! generation to automatically derive implementations at compile time). This
|
||||
//! avoids any overhead of reflection or runtime type information. In fact in
|
||||
//! many situations the interaction between data structure and data format can
|
||||
//! be completely optimized away by the Rust compiler, leaving Serde
|
||||
//! serialization to perform roughly the same speed as a handwritten serializer
|
||||
//! for the specific selection of data structure and data format.
|
||||
//!
|
||||
//! ### Data formats
|
||||
//!
|
||||
//! The following is a partial list of data formats that have been implemented
|
||||
//! for Serde by the community.
|
||||
//!
|
||||
//! - [JSON](https://github.com/serde-rs/json), the ubiquitous JavaScript Object
|
||||
//! Notation used by many HTTP APIs.
|
||||
//! - [Bincode](https://github.com/TyOverby/bincode), a compact binary format
|
||||
//! used for IPC within the Servo rendering engine.
|
||||
//! - [CBOR](https://github.com/pyfisch/cbor), a Concise Binary Object
|
||||
//! Representation designed for small message size without the need for
|
||||
//! version negotiation.
|
||||
//! - [YAML](https://github.com/dtolnay/serde-yaml), a popular human-friendly
|
||||
//! configuration language that ain't markup language.
|
||||
//! - [MessagePack](https://github.com/3Hren/msgpack-rust), an efficient binary
|
||||
//! format that resembles a compact JSON.
|
||||
//! - [TOML](https://github.com/alexcrichton/toml-rs), a minimal configuration
|
||||
//! format used by [Cargo](http://doc.crates.io/manifest.html).
|
||||
//! - [Pickle](https://github.com/birkenfeld/serde-pickle), a format common in
|
||||
//! the Python world.
|
||||
//! - [Hjson](https://github.com/laktak/hjson-rust), a variant of JSON designed
|
||||
//! to be readable and writable by humans.
|
||||
//! - [BSON](https://github.com/zonyitoo/bson-rs), the data storage and network
|
||||
//! transfer format used by MongoDB.
|
||||
//! - [URL](https://github.com/nox/serde_urlencoded), the x-www-form-urlencoded
|
||||
//! format.
|
||||
//! - [XML](https://github.com/serde-rs/xml), the flexible machine-friendly W3C
|
||||
//! standard. *(deserialization only)*
|
||||
//! - [Envy](https://github.com/softprops/envy), a way to deserialize
|
||||
//! environment variables into Rust structs. *(deserialization only)*
|
||||
//! - [Redis](https://github.com/OneSignal/serde-redis), deserialize values from
|
||||
//! Redis when using [redis-rs](https://crates.io/crates/redis).
|
||||
//! *(deserialization only)*
|
||||
|
||||
#![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 = "alloc", feature(alloc))]
|
||||
#![cfg_attr(feature = "collections", feature(collections))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
extern crate collections;
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
extern crate alloc;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
extern crate core as actual_core;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
mod core {
|
||||
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
|
||||
usize, f32, f64, char, str, num, slice, iter, cell, default, result, option};
|
||||
#[cfg(feature = "unstable")]
|
||||
pub use actual_core::nonzero;
|
||||
}
|
||||
|
||||
#[doc(inline)]
|
||||
pub use ser::{Serialize, Serializer};
|
||||
#[doc(inline)]
|
||||
pub use de::{Deserialize, Deserializer};
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
pub mod bytes;
|
||||
pub mod de;
|
||||
#[cfg(feature = "std")]
|
||||
#[doc(hidden)]
|
||||
pub mod iter;
|
||||
pub mod ser;
|
||||
#[cfg_attr(feature = "std", doc(hidden))]
|
||||
pub mod error;
|
||||
mod utils;
|
||||
|
||||
// Generated code uses these to support no_std. Not public API.
|
||||
#[doc(hidden)]
|
||||
pub mod export;
|
|
@ -1,222 +0,0 @@
|
|||
#[cfg(feature = "std")]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_method {
|
||||
($func:ident($($arg:ty),*)) => {
|
||||
#[inline]
|
||||
fn $func<__V>(self, $(_: $arg,)* visitor: __V) -> ::std::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor
|
||||
{
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_method {
|
||||
($func:ident($($arg:ty),*)) => {
|
||||
#[inline]
|
||||
fn $func<__V>(self, $(_: $arg,)* visitor: __V) -> ::core::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor
|
||||
{
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_helper {
|
||||
(bool) => {
|
||||
forward_to_deserialize_method!{deserialize_bool()}
|
||||
};
|
||||
(u8) => {
|
||||
forward_to_deserialize_method!{deserialize_u8()}
|
||||
};
|
||||
(u16) => {
|
||||
forward_to_deserialize_method!{deserialize_u16()}
|
||||
};
|
||||
(u32) => {
|
||||
forward_to_deserialize_method!{deserialize_u32()}
|
||||
};
|
||||
(u64) => {
|
||||
forward_to_deserialize_method!{deserialize_u64()}
|
||||
};
|
||||
(i8) => {
|
||||
forward_to_deserialize_method!{deserialize_i8()}
|
||||
};
|
||||
(i16) => {
|
||||
forward_to_deserialize_method!{deserialize_i16()}
|
||||
};
|
||||
(i32) => {
|
||||
forward_to_deserialize_method!{deserialize_i32()}
|
||||
};
|
||||
(i64) => {
|
||||
forward_to_deserialize_method!{deserialize_i64()}
|
||||
};
|
||||
(f32) => {
|
||||
forward_to_deserialize_method!{deserialize_f32()}
|
||||
};
|
||||
(f64) => {
|
||||
forward_to_deserialize_method!{deserialize_f64()}
|
||||
};
|
||||
(char) => {
|
||||
forward_to_deserialize_method!{deserialize_char()}
|
||||
};
|
||||
(str) => {
|
||||
forward_to_deserialize_method!{deserialize_str()}
|
||||
};
|
||||
(string) => {
|
||||
forward_to_deserialize_method!{deserialize_string()}
|
||||
};
|
||||
(unit) => {
|
||||
forward_to_deserialize_method!{deserialize_unit()}
|
||||
};
|
||||
(option) => {
|
||||
forward_to_deserialize_method!{deserialize_option()}
|
||||
};
|
||||
(seq) => {
|
||||
forward_to_deserialize_method!{deserialize_seq()}
|
||||
};
|
||||
(seq_fixed_size) => {
|
||||
forward_to_deserialize_method!{deserialize_seq_fixed_size(usize)}
|
||||
};
|
||||
(bytes) => {
|
||||
forward_to_deserialize_method!{deserialize_bytes()}
|
||||
};
|
||||
(byte_buf) => {
|
||||
forward_to_deserialize_method!{deserialize_byte_buf()}
|
||||
};
|
||||
(map) => {
|
||||
forward_to_deserialize_method!{deserialize_map()}
|
||||
};
|
||||
(unit_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_unit_struct(&'static str)}
|
||||
};
|
||||
(newtype_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_newtype_struct(&'static str)}
|
||||
};
|
||||
(tuple_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_tuple_struct(&'static str, usize)}
|
||||
};
|
||||
(struct) => {
|
||||
forward_to_deserialize_method!{deserialize_struct(&'static str, &'static [&'static str])}
|
||||
};
|
||||
(struct_field) => {
|
||||
forward_to_deserialize_method!{deserialize_struct_field()}
|
||||
};
|
||||
(tuple) => {
|
||||
forward_to_deserialize_method!{deserialize_tuple(usize)}
|
||||
};
|
||||
(enum) => {
|
||||
forward_to_deserialize_method!{deserialize_enum(&'static str, &'static [&'static str])}
|
||||
};
|
||||
(ignored_any) => {
|
||||
forward_to_deserialize_method!{deserialize_ignored_any()}
|
||||
};
|
||||
}
|
||||
|
||||
// Super explicit first paragraph because this shows up at the top level and
|
||||
// trips up people who are just looking for basic Serialize / Deserialize
|
||||
// documentation.
|
||||
//
|
||||
/// Helper macro when implementing the `Deserializer` part of a new data format
|
||||
/// for Serde.
|
||||
///
|
||||
/// Some `Deserializer` implementations for self-describing formats do not care
|
||||
/// what hint the `Visitor` gives them, they just want to blindly call the
|
||||
/// `Visitor` method corresponding to the data they can tell is in the input.
|
||||
/// This requires repetitive implementations of all the `Deserializer` trait
|
||||
/// methods.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde;
|
||||
/// # use serde::de::{value, Deserializer, Visitor};
|
||||
/// # pub struct MyDeserializer;
|
||||
/// # impl Deserializer for MyDeserializer {
|
||||
/// # type Error = value::Error;
|
||||
/// # fn deserialize<V>(self, _: V) -> Result<V::Value, Self::Error>
|
||||
/// # where V: Visitor
|
||||
/// # { unimplemented!() }
|
||||
/// #
|
||||
/// #[inline]
|
||||
/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
/// where V: Visitor
|
||||
/// {
|
||||
/// self.deserialize(visitor)
|
||||
/// }
|
||||
/// # forward_to_deserialize! {
|
||||
/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
|
||||
/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||
/// # tuple_struct struct struct_field tuple enum ignored_any
|
||||
/// # }
|
||||
/// # }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// The `forward_to_deserialize!` macro implements these simple forwarding
|
||||
/// methods so that they forward directly to `Deserializer::deserialize`. You
|
||||
/// can choose which methods to forward.
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use] extern crate serde;
|
||||
/// # use serde::de::{value, Deserializer, Visitor};
|
||||
/// # pub struct MyDeserializer;
|
||||
/// impl Deserializer for MyDeserializer {
|
||||
/// # type Error = value::Error;
|
||||
/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
/// where V: Visitor
|
||||
/// {
|
||||
/// /* ... */
|
||||
/// # let _ = visitor;
|
||||
/// # unimplemented!()
|
||||
/// }
|
||||
///
|
||||
/// forward_to_deserialize! {
|
||||
/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
|
||||
/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||
/// tuple_struct struct struct_field tuple enum ignored_any
|
||||
/// }
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize {
|
||||
($($func:ident)*) => {
|
||||
$(forward_to_deserialize_helper!{$func})*
|
||||
};
|
||||
}
|
||||
|
||||
/// Seralize the `$value` that implements Display as a string,
|
||||
/// when that string is statically known to never have more than
|
||||
/// a constant `$MAX_LEN` bytes.
|
||||
///
|
||||
/// Panics if the Display impl tries to write more than `$MAX_LEN` bytes.
|
||||
#[cfg(feature = "std")]
|
||||
// Not exported
|
||||
macro_rules! serialize_display_bounded_length {
|
||||
($value: expr, $MAX_LEN: expr, $serializer: expr) => {
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut buffer: [u8; $MAX_LEN] = unsafe { ::std::mem::uninitialized() };
|
||||
let remaining_len;
|
||||
{
|
||||
let mut remaining = &mut buffer[..];
|
||||
write!(remaining, "{}", $value).unwrap();
|
||||
remaining_len = remaining.len()
|
||||
}
|
||||
let written_len = buffer.len() - remaining_len;
|
||||
let written = &buffer[..written_len];
|
||||
|
||||
// write! only provides std::fmt::Formatter to Display implementations,
|
||||
// which has methods write_str and write_char but no method to write arbitrary bytes.
|
||||
// Therefore, `written` is well-formed in UTF-8.
|
||||
let written_str = unsafe {
|
||||
::std::str::from_utf8_unchecked(written)
|
||||
};
|
||||
$serializer.serialize_str(written_str)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,635 +0,0 @@
|
|||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(all(not(feature = "std"), feature = "collections"))]
|
||||
use collections::{String, Vec};
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::boxed::Box;
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::borrow::ToOwned;
|
||||
|
||||
use ser::{self, Serialize, Serializer};
|
||||
|
||||
pub struct SerializeTupleVariantAsMapValue<M> {
|
||||
map: M,
|
||||
name: &'static str,
|
||||
fields: Vec<Content>,
|
||||
}
|
||||
|
||||
impl<M> SerializeTupleVariantAsMapValue<M> {
|
||||
pub fn new(map: M, name: &'static str, len: usize) -> Self {
|
||||
SerializeTupleVariantAsMapValue {
|
||||
map: map,
|
||||
name: name,
|
||||
fields: Vec::with_capacity(len),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<M> ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<M>
|
||||
where M: ser::SerializeMap
|
||||
{
|
||||
type Ok = M::Ok;
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
value: &T)
|
||||
-> Result<(), M::Error>
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
self.fields.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(mut self) -> Result<M::Ok, M::Error> {
|
||||
try!(self.map.serialize_value(&Content::TupleStruct(self.name, self.fields)));
|
||||
self.map.end()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SerializeStructVariantAsMapValue<M> {
|
||||
map: M,
|
||||
name: &'static str,
|
||||
fields: Vec<(&'static str, Content)>,
|
||||
}
|
||||
|
||||
impl<M> SerializeStructVariantAsMapValue<M> {
|
||||
pub fn new(map: M, name: &'static str, len: usize) -> Self {
|
||||
SerializeStructVariantAsMapValue {
|
||||
map: map,
|
||||
name: name,
|
||||
fields: Vec::with_capacity(len),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<M> ser::SerializeStructVariant for SerializeStructVariantAsMapValue<M>
|
||||
where M: ser::SerializeMap
|
||||
{
|
||||
type Ok = M::Ok;
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), M::Error>
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(mut self) -> Result<M::Ok, M::Error> {
|
||||
try!(self.map.serialize_value(&Content::Struct(self.name, self.fields)));
|
||||
self.map.end()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Content {
|
||||
Bool(bool),
|
||||
|
||||
U8(u8),
|
||||
U16(u16),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
|
||||
I8(i8),
|
||||
I16(i16),
|
||||
I32(i32),
|
||||
I64(i64),
|
||||
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
|
||||
Char(char),
|
||||
String(String),
|
||||
Bytes(Vec<u8>),
|
||||
|
||||
None,
|
||||
Some(Box<Content>),
|
||||
|
||||
Unit,
|
||||
UnitStruct(&'static str),
|
||||
UnitVariant(&'static str, usize, &'static str),
|
||||
NewtypeStruct(&'static str, Box<Content>),
|
||||
NewtypeVariant(&'static str, usize, &'static str, Box<Content>),
|
||||
|
||||
Seq(Vec<Content>),
|
||||
SeqFixedSize(Vec<Content>),
|
||||
Tuple(Vec<Content>),
|
||||
TupleStruct(&'static str, Vec<Content>),
|
||||
TupleVariant(&'static str, usize, &'static str, Vec<Content>),
|
||||
Map(Vec<(Content, Content)>),
|
||||
Struct(&'static str, Vec<(&'static str, Content)>),
|
||||
StructVariant(&'static str, usize, &'static str, Vec<(&'static str, Content)>),
|
||||
}
|
||||
|
||||
impl Serialize for Content {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
Content::Bool(b) => serializer.serialize_bool(b),
|
||||
Content::U8(u) => serializer.serialize_u8(u),
|
||||
Content::U16(u) => serializer.serialize_u16(u),
|
||||
Content::U32(u) => serializer.serialize_u32(u),
|
||||
Content::U64(u) => serializer.serialize_u64(u),
|
||||
Content::I8(i) => serializer.serialize_i8(i),
|
||||
Content::I16(i) => serializer.serialize_i16(i),
|
||||
Content::I32(i) => serializer.serialize_i32(i),
|
||||
Content::I64(i) => serializer.serialize_i64(i),
|
||||
Content::F32(f) => serializer.serialize_f32(f),
|
||||
Content::F64(f) => serializer.serialize_f64(f),
|
||||
Content::Char(c) => serializer.serialize_char(c),
|
||||
Content::String(ref s) => serializer.serialize_str(s),
|
||||
Content::Bytes(ref b) => serializer.serialize_bytes(b),
|
||||
Content::None => serializer.serialize_none(),
|
||||
Content::Some(ref c) => serializer.serialize_some(&**c),
|
||||
Content::Unit => serializer.serialize_unit(),
|
||||
Content::UnitStruct(n) => serializer.serialize_unit_struct(n),
|
||||
Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v),
|
||||
Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c),
|
||||
Content::NewtypeVariant(n, i, v, ref c) => serializer.serialize_newtype_variant(n, i, v, &**c),
|
||||
Content::Seq(ref elements) => elements.serialize(serializer),
|
||||
Content::SeqFixedSize(ref elements) => {
|
||||
use ser::SerializeSeq;
|
||||
let mut seq = try!(serializer.serialize_seq_fixed_size(elements.len()));
|
||||
for e in elements {
|
||||
try!(seq.serialize_element(e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
Content::Tuple(ref elements) => {
|
||||
use ser::SerializeTuple;
|
||||
let mut tuple = try!(serializer.serialize_tuple(elements.len()));
|
||||
for e in elements {
|
||||
try!(tuple.serialize_element(e));
|
||||
}
|
||||
tuple.end()
|
||||
}
|
||||
Content::TupleStruct(n, ref fields) => {
|
||||
use ser::SerializeTupleStruct;
|
||||
let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len()));
|
||||
for f in fields {
|
||||
try!(ts.serialize_field(f));
|
||||
}
|
||||
ts.end()
|
||||
}
|
||||
Content::TupleVariant(n, i, v, ref fields) => {
|
||||
use ser::SerializeTupleVariant;
|
||||
let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len()));
|
||||
for f in fields {
|
||||
try!(tv.serialize_field(f));
|
||||
}
|
||||
tv.end()
|
||||
}
|
||||
Content::Map(ref entries) => {
|
||||
use ser::SerializeMap;
|
||||
let mut map = try!(serializer.serialize_map(Some(entries.len())));
|
||||
for &(ref k, ref v) in entries {
|
||||
try!(map.serialize_entry(k, v));
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
Content::Struct(n, ref fields) => {
|
||||
use ser::SerializeStruct;
|
||||
let mut s = try!(serializer.serialize_struct(n, fields.len()));
|
||||
for &(k, ref v) in fields {
|
||||
try!(s.serialize_field(k, v));
|
||||
}
|
||||
s.end()
|
||||
}
|
||||
Content::StructVariant(n, i, v, ref fields) => {
|
||||
use ser::SerializeStructVariant;
|
||||
let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len()));
|
||||
for &(k, ref v) in fields {
|
||||
try!(sv.serialize_field(k, v));
|
||||
}
|
||||
sv.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentSerializer<E> {
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ContentSerializer<E> {
|
||||
fn new() -> Self {
|
||||
ContentSerializer {
|
||||
error: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> Serializer for ContentSerializer<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
type SerializeSeq = SerializeSeq<E>;
|
||||
type SerializeTuple = SerializeTuple<E>;
|
||||
type SerializeTupleStruct = SerializeTupleStruct<E>;
|
||||
type SerializeTupleVariant = SerializeTupleVariant<E>;
|
||||
type SerializeMap = SerializeMap<E>;
|
||||
type SerializeStruct = SerializeStruct<E>;
|
||||
type SerializeStructVariant = SerializeStructVariant<E>;
|
||||
|
||||
fn serialize_bool(self, v: bool) -> Result<Content, E> {
|
||||
Ok(Content::Bool(v))
|
||||
}
|
||||
|
||||
fn serialize_i8(self, v: i8) -> Result<Content, E> {
|
||||
Ok(Content::I8(v))
|
||||
}
|
||||
|
||||
fn serialize_i16(self, v: i16) -> Result<Content, E> {
|
||||
Ok(Content::I16(v))
|
||||
}
|
||||
|
||||
fn serialize_i32(self, v: i32) -> Result<Content, E> {
|
||||
Ok(Content::I32(v))
|
||||
}
|
||||
|
||||
fn serialize_i64(self, v: i64) -> Result<Content, E> {
|
||||
Ok(Content::I64(v))
|
||||
}
|
||||
|
||||
fn serialize_u8(self, v: u8) -> Result<Content, E> {
|
||||
Ok(Content::U8(v))
|
||||
}
|
||||
|
||||
fn serialize_u16(self, v: u16) -> Result<Content, E> {
|
||||
Ok(Content::U16(v))
|
||||
}
|
||||
|
||||
fn serialize_u32(self, v: u32) -> Result<Content, E> {
|
||||
Ok(Content::U32(v))
|
||||
}
|
||||
|
||||
fn serialize_u64(self, v: u64) -> Result<Content, E> {
|
||||
Ok(Content::U64(v))
|
||||
}
|
||||
|
||||
fn serialize_f32(self, v: f32) -> Result<Content, E> {
|
||||
Ok(Content::F32(v))
|
||||
}
|
||||
|
||||
fn serialize_f64(self, v: f64) -> Result<Content, E> {
|
||||
Ok(Content::F64(v))
|
||||
}
|
||||
|
||||
fn serialize_char(self, v: char) -> Result<Content, E> {
|
||||
Ok(Content::Char(v))
|
||||
}
|
||||
|
||||
fn serialize_str(self, value: &str) -> Result<Content, E> {
|
||||
Ok(Content::String(value.to_owned()))
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> {
|
||||
Ok(Content::Bytes(value.to_owned()))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<Content, E> {
|
||||
Ok(Content::None)
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized + Serialize>(self,
|
||||
value: &T)
|
||||
-> Result<Content, E> {
|
||||
Ok(Content::Some(Box::new(try!(value.serialize(self)))))
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<Content, E> {
|
||||
Ok(Content::Unit)
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self,
|
||||
name: &'static str)
|
||||
-> Result<Content, E> {
|
||||
Ok(Content::UnitStruct(name))
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str)
|
||||
-> Result<Content, E> {
|
||||
Ok(Content::UnitVariant(name, variant_index, variant))
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized + Serialize>(self,
|
||||
name: &'static str,
|
||||
value: &T)
|
||||
-> Result<Content, E> {
|
||||
Ok(Content::NewtypeStruct(name, Box::new(try!(value.serialize(self)))))
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized + Serialize>(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
value: &T)
|
||||
-> Result<Content, E> {
|
||||
Ok(Content::NewtypeVariant(name, variant_index, variant, Box::new(try!(value.serialize(self)))))
|
||||
}
|
||||
|
||||
fn serialize_seq(self,
|
||||
len: Option<usize>)
|
||||
-> Result<Self::SerializeSeq, E> {
|
||||
Ok(SerializeSeq {
|
||||
fixed_size: false,
|
||||
elements: Vec::with_capacity(len.unwrap_or(0)),
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_seq_fixed_size(self,
|
||||
size: usize)
|
||||
-> Result<Self::SerializeSeq, E> {
|
||||
Ok(SerializeSeq {
|
||||
fixed_size: true,
|
||||
elements: Vec::with_capacity(size),
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_tuple(self,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTuple, E> {
|
||||
Ok(SerializeTuple {
|
||||
elements: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTupleStruct, E> {
|
||||
Ok(SerializeTupleStruct {
|
||||
name: name,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTupleVariant, E> {
|
||||
Ok(SerializeTupleVariant {
|
||||
name: name,
|
||||
variant_index: variant_index,
|
||||
variant: variant,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_map(self,
|
||||
len: Option<usize>)
|
||||
-> Result<Self::SerializeMap, E> {
|
||||
Ok(SerializeMap {
|
||||
entries: Vec::with_capacity(len.unwrap_or(0)),
|
||||
key: None,
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStruct, E> {
|
||||
Ok(SerializeStruct {
|
||||
name: name,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStructVariant, E> {
|
||||
Ok(SerializeStructVariant {
|
||||
name: name,
|
||||
variant_index: variant_index,
|
||||
variant: variant,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeSeq<E> {
|
||||
fixed_size: bool,
|
||||
elements: Vec<Content>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ser::SerializeSeq for SerializeSeq<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self,
|
||||
value: &T)
|
||||
-> Result<(), E> {
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.elements.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Content, E> {
|
||||
Ok(if self.fixed_size {
|
||||
Content::SeqFixedSize(self.elements)
|
||||
} else {
|
||||
Content::Seq(self.elements)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeTuple<E> {
|
||||
elements: Vec<Content>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ser::SerializeTuple for SerializeTuple<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self,
|
||||
value: &T)
|
||||
-> Result<(), E> {
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.elements.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Content, E> {
|
||||
Ok(Content::Tuple(self.elements))
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeTupleStruct<E> {
|
||||
name: &'static str,
|
||||
fields: Vec<Content>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
value: &T)
|
||||
-> Result<(), E> {
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Content, E> {
|
||||
Ok(Content::TupleStruct(self.name, self.fields))
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeTupleVariant<E> {
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
fields: Vec<Content>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
value: &T)
|
||||
-> Result<(), E> {
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Content, E> {
|
||||
Ok(Content::TupleVariant(self.name, self.variant_index, self.variant, self.fields))
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeMap<E> {
|
||||
entries: Vec<(Content, Content)>,
|
||||
key: Option<Content>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ser::SerializeMap for SerializeMap<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_key<T: ?Sized + Serialize>(&mut self,
|
||||
key: &T)
|
||||
-> Result<(), E> {
|
||||
let key = try!(key.serialize(ContentSerializer::<E>::new()));
|
||||
self.key = Some(key);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized + Serialize>(&mut self,
|
||||
value: &T)
|
||||
-> Result<(), E> {
|
||||
let key = self.key.take().expect("serialize_value called before serialize_key");
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.entries.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Content, E> {
|
||||
Ok(Content::Map(self.entries))
|
||||
}
|
||||
|
||||
fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(&mut self,
|
||||
key: &K,
|
||||
value: &V)
|
||||
-> Result<(), E> {
|
||||
let key = try!(key.serialize(ContentSerializer::<E>::new()));
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.entries.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeStruct<E> {
|
||||
name: &'static str,
|
||||
fields: Vec<(&'static str, Content)>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ser::SerializeStruct for SerializeStruct<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), E> {
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Content, E> {
|
||||
Ok(Content::Struct(self.name, self.fields))
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeStructVariant<E> {
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
fields: Vec<(&'static str, Content)>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ser::SerializeStructVariant for SerializeStructVariant<E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), E> {
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Content, E> {
|
||||
Ok(Content::StructVariant(self.name, self.variant_index, self.variant, self.fields))
|
||||
}
|
||||
}
|
|
@ -1,723 +0,0 @@
|
|||
#[cfg(feature = "std")]
|
||||
use std::borrow::Cow;
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::borrow::Cow;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, HashMap, HashSet, VecDeque};
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque, String, Vec};
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::borrow::ToOwned;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use core::hash::{Hash, BuildHasher};
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::iter;
|
||||
#[cfg(feature = "std")]
|
||||
use std::net;
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::ops;
|
||||
#[cfg(feature = "std")]
|
||||
use std::path;
|
||||
#[cfg(feature = "std")]
|
||||
use std::rc::Rc;
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::rc::Rc;
|
||||
#[cfg(feature = "std")]
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::sync::Arc;
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::arc::Arc;
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::boxed::Box;
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::nonzero::{NonZero, Zeroable};
|
||||
|
||||
use super::{Serialize, SerializeSeq, SerializeTuple, Serializer};
|
||||
#[cfg(feature = "std")]
|
||||
use super::Error;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! impl_visit {
|
||||
($ty:ty, $method:ident $($cast:tt)*) => {
|
||||
impl Serialize for $ty {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.$method(*self $($cast)*)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_visit!(bool, serialize_bool);
|
||||
impl_visit!(isize, serialize_i64 as i64);
|
||||
impl_visit!(i8, serialize_i8);
|
||||
impl_visit!(i16, serialize_i16);
|
||||
impl_visit!(i32, serialize_i32);
|
||||
impl_visit!(i64, serialize_i64);
|
||||
impl_visit!(usize, serialize_u64 as u64);
|
||||
impl_visit!(u8, serialize_u8);
|
||||
impl_visit!(u16, serialize_u16);
|
||||
impl_visit!(u32, serialize_u32);
|
||||
impl_visit!(u64, serialize_u64);
|
||||
impl_visit!(f32, serialize_f32);
|
||||
impl_visit!(f64, serialize_f64);
|
||||
impl_visit!(char, serialize_char);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Serialize for str {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
serializer.serialize_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl Serialize for String {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(&self[..]).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T> Serialize for Option<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
Some(ref value) => serializer.serialize_some(value),
|
||||
None => serializer.serialize_none(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T> Serialize for PhantomData<T> {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
serializer.serialize_unit_struct("PhantomData")
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! array_impls {
|
||||
($len:expr) => {
|
||||
impl<T> Serialize for [T; $len] where T: Serialize {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq_fixed_size($len));
|
||||
for e in self {
|
||||
try!(seq.serialize_element(e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
array_impls!(0);
|
||||
array_impls!(1);
|
||||
array_impls!(2);
|
||||
array_impls!(3);
|
||||
array_impls!(4);
|
||||
array_impls!(5);
|
||||
array_impls!(6);
|
||||
array_impls!(7);
|
||||
array_impls!(8);
|
||||
array_impls!(9);
|
||||
array_impls!(10);
|
||||
array_impls!(11);
|
||||
array_impls!(12);
|
||||
array_impls!(13);
|
||||
array_impls!(14);
|
||||
array_impls!(15);
|
||||
array_impls!(16);
|
||||
array_impls!(17);
|
||||
array_impls!(18);
|
||||
array_impls!(19);
|
||||
array_impls!(20);
|
||||
array_impls!(21);
|
||||
array_impls!(22);
|
||||
array_impls!(23);
|
||||
array_impls!(24);
|
||||
array_impls!(25);
|
||||
array_impls!(26);
|
||||
array_impls!(27);
|
||||
array_impls!(28);
|
||||
array_impls!(29);
|
||||
array_impls!(30);
|
||||
array_impls!(31);
|
||||
array_impls!(32);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! serialize_seq {
|
||||
() => {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.collect_seq(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for [T]
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for BinaryHeap<T>
|
||||
where T: Serialize + Ord
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for BTreeSet<T>
|
||||
where T: Serialize + Ord
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T, H> Serialize for HashSet<T, H>
|
||||
where T: Serialize + Eq + Hash,
|
||||
H: BuildHasher
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for LinkedList<T>
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for Vec<T>
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for VecDeque<T>
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<A> Serialize for ops::Range<A>
|
||||
where ops::Range<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||
A: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self.clone() {
|
||||
try!(seq.serialize_element(&e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<A> Serialize for ops::RangeInclusive<A>
|
||||
where ops::RangeInclusive<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||
A: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self.clone() {
|
||||
try!(seq.serialize_element(&e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Serialize for () {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
serializer.serialize_unit()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
($(
|
||||
$TupleVisitor:ident ($len:expr, $($T:ident),+) {
|
||||
$($state:pat => $idx:tt,)+
|
||||
}
|
||||
)+) => {
|
||||
$(
|
||||
impl<$($T),+> Serialize for ($($T,)+)
|
||||
where $($T: Serialize),+
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut tuple = try!(serializer.serialize_tuple($len));
|
||||
$(
|
||||
try!(tuple.serialize_element(&self.$idx));
|
||||
)+
|
||||
tuple.end()
|
||||
}
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
tuple_impls! {
|
||||
TupleVisitor1 (1, T0) {
|
||||
0 => 0,
|
||||
}
|
||||
TupleVisitor2 (2, T0, T1) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
}
|
||||
TupleVisitor3 (3, T0, T1, T2) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
}
|
||||
TupleVisitor4 (4, T0, T1, T2, T3) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
}
|
||||
TupleVisitor5 (5, T0, T1, T2, T3, T4) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
}
|
||||
TupleVisitor6 (6, T0, T1, T2, T3, T4, T5) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
}
|
||||
TupleVisitor7 (7, T0, T1, T2, T3, T4, T5, T6) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
}
|
||||
TupleVisitor8 (8, T0, T1, T2, T3, T4, T5, T6, T7) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
}
|
||||
TupleVisitor9 (9, T0, T1, T2, T3, T4, T5, T6, T7, T8) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
}
|
||||
TupleVisitor10 (10, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
}
|
||||
TupleVisitor11 (11, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
}
|
||||
TupleVisitor12 (12, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
}
|
||||
TupleVisitor13 (13, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
}
|
||||
TupleVisitor14 (14, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
13 => 13,
|
||||
}
|
||||
TupleVisitor15 (15, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
13 => 13,
|
||||
14 => 14,
|
||||
}
|
||||
TupleVisitor16 (16, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) {
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 2,
|
||||
3 => 3,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 6,
|
||||
7 => 7,
|
||||
8 => 8,
|
||||
9 => 9,
|
||||
10 => 10,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
13 => 13,
|
||||
14 => 14,
|
||||
15 => 15,
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! serialize_map {
|
||||
() => {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.collect_map(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<K, V> Serialize for BTreeMap<K, V>
|
||||
where K: Serialize + Ord,
|
||||
V: Serialize
|
||||
{
|
||||
serialize_map!();
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<K, V, H> Serialize for HashMap<K, V, H>
|
||||
where K: Serialize + Eq + Hash,
|
||||
V: Serialize,
|
||||
H: BuildHasher
|
||||
{
|
||||
serialize_map!();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'a, T: ?Sized> Serialize for &'a T
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: ?Sized> Serialize for &'a mut T
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T: ?Sized> Serialize for Box<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T> Serialize for Rc<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T> Serialize for Arc<T>
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, T: ?Sized> Serialize for Cow<'a, T>
|
||||
where T: Serialize + ToOwned
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T, E> Serialize for Result<T, E>
|
||||
where T: Serialize,
|
||||
E: Serialize
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value),
|
||||
Result::Err(ref value) => {
|
||||
serializer.serialize_newtype_variant("Result", 1, "Err", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for Duration {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = try!(serializer.serialize_struct("Duration", 2));
|
||||
try!(state.serialize_field("secs", &self.as_secs()));
|
||||
try!(state.serialize_field("nanos", &self.subsec_nanos()));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::IpAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
net::IpAddr::V4(ref a) => a.serialize(serializer),
|
||||
net::IpAddr::V6(ref a) => a.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::Ipv4Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
/// "101.102.103.104".len()
|
||||
const MAX_LEN: usize = 15;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::Ipv6Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
/// "1000:1002:1003:1004:1005:1006:1007:1008".len()
|
||||
const MAX_LEN: usize = 39;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
|
||||
net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddrV4 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
/// "101.102.103.104:65000".len()
|
||||
const MAX_LEN: usize = 21;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddrV6 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
/// "[1000:1002:1003:1004:1005:1006:1007:1008]:65000".len()
|
||||
const MAX_LEN: usize = 47;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for path::Path {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match self.to_str() {
|
||||
Some(s) => s.serialize(serializer),
|
||||
None => Err(Error::custom("path contains invalid UTF-8 characters")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for path::PathBuf {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
self.as_path().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<T> Serialize for NonZero<T>
|
||||
where T: Serialize + Zeroable
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
|
@ -1,156 +0,0 @@
|
|||
//! This module contains `Impossible` serializer and its implementations.
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use ser::{self, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct,
|
||||
SerializeTupleVariant, SerializeMap, SerializeStruct, SerializeStructVariant};
|
||||
|
||||
/// Helper type for implementing a `Serializer` that does not support
|
||||
/// serializing one of the compound types.
|
||||
///
|
||||
/// This type cannot be instantiated, but implements every one of the traits
|
||||
/// corresponding to the `Serializer` compound types: `SerializeSeq`,
|
||||
/// `SerializeTuple`, `SerializeTupleStruct`, `SerializeTupleVariant`,
|
||||
/// `SerializeMap`, `SerializeStruct`, and `SerializeStructVariant`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl Serializer for MySerializer {
|
||||
/// type Ok = ();
|
||||
/// type Error = Error;
|
||||
///
|
||||
/// type SerializeSeq = Impossible<(), Error>;
|
||||
/// /* other associated types */
|
||||
///
|
||||
/// /// This data format does not support serializing sequences.
|
||||
/// fn serialize_seq(self,
|
||||
/// len: Option<usize>)
|
||||
/// -> Result<Self::SerializeSeq, Error> {
|
||||
/// // Given Impossible cannot be instantiated, the only
|
||||
/// // thing we can do here is to return an error.
|
||||
/// Err(...)
|
||||
/// }
|
||||
///
|
||||
/// /* other Serializer methods */
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Impossible<Ok, E> {
|
||||
void: Void,
|
||||
_marker: PhantomData<(Ok, E)>,
|
||||
}
|
||||
|
||||
enum Void {}
|
||||
|
||||
impl<Ok, E> SerializeSeq for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTuple for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTupleStruct for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTupleVariant for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeMap for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_key<T: ?Sized + Serialize>(&mut self, _key: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeStruct for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_key: &'static str,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeStructVariant for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_key: &'static str,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
|
@ -1,848 +0,0 @@
|
|||
//! Generic data structure serialization framework.
|
||||
//!
|
||||
//! The two most important traits in this module are `Serialize` and
|
||||
//! `Serializer`.
|
||||
//!
|
||||
//! - **A type that implements `Serialize` is a data structure** that can be
|
||||
//! serialized to any data format supported by Serde, and conversely
|
||||
//! - **A type that implements `Serializer` is a data format** that can
|
||||
//! serialize any data structure supported by Serde.
|
||||
//!
|
||||
//! # The Serialize trait
|
||||
//!
|
||||
//! Serde provides `Serialize` implementations for many Rust primitive and
|
||||
//! standard library types. The complete list is below. All of these can be
|
||||
//! serialized using Serde out of the box.
|
||||
//!
|
||||
//! Additionally, Serde provides a procedural macro called `serde_derive` to
|
||||
//! automatically generate `Serialize` implementations for structs and enums in
|
||||
//! your program. See the [codegen section of the manual][codegen] for how to
|
||||
//! use this.
|
||||
//!
|
||||
//! In rare cases it may be necessary to implement `Serialize` manually for some
|
||||
//! type in your program. See the [Implementing `Serialize`][impl-serialize]
|
||||
//! section of the manual for more about this.
|
||||
//!
|
||||
//! Third-party crates may provide `Serialize` implementations for types that
|
||||
//! they expose. For example the `linked-hash-map` crate provides a
|
||||
//! `LinkedHashMap<K, V>` type that is serializable by Serde because the crate
|
||||
//! provides an implementation of `Serialize` for it.
|
||||
//!
|
||||
//! # The Serializer trait
|
||||
//!
|
||||
//! `Serializer` implementations are provided by third-party crates, for example
|
||||
//! [`serde_json`][serde_json], [`serde_yaml`][serde_yaml] and
|
||||
//! [`bincode`][bincode].
|
||||
//!
|
||||
//! A partial list of well-maintained formats is given on the [Serde
|
||||
//! website][data-formats].
|
||||
//!
|
||||
//! # Implementations of Serialize provided by Serde
|
||||
//!
|
||||
//! - **Primitive types**:
|
||||
//! - bool
|
||||
//! - isize, i8, i16, i32, i64
|
||||
//! - usize, u8, u16, u32, u64
|
||||
//! - f32, f64
|
||||
//! - char
|
||||
//! - str
|
||||
//! - &T and &mut T
|
||||
//! - **Compound types**:
|
||||
//! - [T]
|
||||
//! - [T; 0] through [T; 32]
|
||||
//! - tuples up to size 16
|
||||
//! - **Common standard library types**:
|
||||
//! - String
|
||||
//! - Option\<T\>
|
||||
//! - Result\<T, E\>
|
||||
//! - PhantomData\<T\>
|
||||
//! - **Wrapper types**:
|
||||
//! - Box\<T\>
|
||||
//! - Rc\<T\>
|
||||
//! - Arc\<T\>
|
||||
//! - Cow\<'a, T\>
|
||||
//! - **Collection types**:
|
||||
//! - BTreeMap\<K, V\>
|
||||
//! - BTreeSet\<T\>
|
||||
//! - BinaryHeap\<T\>
|
||||
//! - HashMap\<K, V, H\>
|
||||
//! - HashSet\<T, H\>
|
||||
//! - LinkedList\<T\>
|
||||
//! - VecDeque\<T\>
|
||||
//! - Vec\<T\>
|
||||
//! - EnumSet\<T\> (unstable)
|
||||
//! - Range\<T\> (unstable)
|
||||
//! - RangeInclusive\<T\> (unstable)
|
||||
//! - **Miscellaneous standard library types**:
|
||||
//! - Duration
|
||||
//! - Path
|
||||
//! - PathBuf
|
||||
//! - NonZero\<T\> (unstable)
|
||||
//! - **Net types**:
|
||||
//! - IpAddr
|
||||
//! - Ipv4Addr
|
||||
//! - Ipv6Addr
|
||||
//! - SocketAddr
|
||||
//! - SocketAddrV4
|
||||
//! - SocketAddrV6
|
||||
//!
|
||||
//! [codegen]: https://serde.rs/codegen.html
|
||||
//! [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||
//! [serde_json]: https://github.com/serde-rs/json
|
||||
//! [serde_yaml]: https://github.com/dtolnay/serde-yaml
|
||||
//! [bincode]: https://github.com/TyOverby/bincode
|
||||
//! [data-formats]: https://serde.rs/#data-formats
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::error;
|
||||
#[cfg(not(feature = "std"))]
|
||||
use error;
|
||||
|
||||
use core::fmt::Display;
|
||||
use core::iter::IntoIterator;
|
||||
|
||||
mod impls;
|
||||
mod impossible;
|
||||
|
||||
// Helpers used by generated code. Not public API.
|
||||
#[doc(hidden)]
|
||||
pub mod private;
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
mod content;
|
||||
|
||||
pub use self::impossible::Impossible;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Trait used by `Serialize` implementations to generically construct errors
|
||||
/// belonging to the `Serializer` against which they are currently running.
|
||||
pub trait Error: Sized + error::Error {
|
||||
/// Raised when a `Serialize` implementation encounters a general error
|
||||
/// while serializing a type.
|
||||
///
|
||||
/// The message should not be capitalized and should not end with a period.
|
||||
///
|
||||
/// For example, a filesystem `Path` may refuse to serialize itself if it
|
||||
/// contains invalid UTF-8 data.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use serde::ser::{Serialize, Serializer, Error};
|
||||
/// # struct Path;
|
||||
/// # impl Path { fn to_str(&self) -> Option<&str> { unimplemented!() } }
|
||||
/// impl Serialize for Path {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where S: Serializer
|
||||
/// {
|
||||
/// match self.to_str() {
|
||||
/// Some(s) => s.serialize(serializer),
|
||||
/// None => Err(Error::custom("path contains invalid UTF-8 characters")),
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn custom<T: Display>(msg: T) -> Self;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A **data structure** that can be serialized into any data format supported
|
||||
/// by Serde.
|
||||
///
|
||||
/// Serde provides `Serialize` implementations for many Rust primitive and
|
||||
/// standard library types. The complete list is [here][ser]. All of these can
|
||||
/// be serialized using Serde out of the box.
|
||||
///
|
||||
/// Additionally, Serde provides a procedural macro called `serde_derive` to
|
||||
/// automatically generate `Serialize` implementations for structs and enums in
|
||||
/// your program. See the [codegen section of the manual][codegen] for how to
|
||||
/// use this.
|
||||
///
|
||||
/// In rare cases it may be necessary to implement `Serialize` manually for some
|
||||
/// type in your program. See the [Implementing `Serialize`][impl-serialize]
|
||||
/// section of the manual for more about this.
|
||||
///
|
||||
/// Third-party crates may provide `Serialize` implementations for types that
|
||||
/// they expose. For example the `linked-hash-map` crate provides a
|
||||
/// `LinkedHashMap<K, V>` type that is serializable by Serde because the crate
|
||||
/// provides an implementation of `Serialize` for it.
|
||||
///
|
||||
/// [ser]: https://docs.serde.rs/serde/ser/index.html
|
||||
/// [codegen]: https://serde.rs/codegen.html
|
||||
/// [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||
pub trait Serialize {
|
||||
/// Serialize this value into the given Serde serializer.
|
||||
///
|
||||
/// See the [Implementing `Serialize`][impl-serialize] section of the manual
|
||||
/// for more information about how to implement this method.
|
||||
///
|
||||
/// [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A **data format** that can serialize any data structure supported by Serde.
|
||||
///
|
||||
/// The role of this trait is to define the serialization half of the Serde data
|
||||
/// model, which is a way to categorize every Rust data structure into one of 28
|
||||
/// possible types. Each method of the `Serializer` trait corresponds to one of
|
||||
/// the types of the data model.
|
||||
///
|
||||
/// Implementations of `Serialize` map themselves into this data model by
|
||||
/// invoking exactly one of the `Serializer` methods.
|
||||
///
|
||||
/// The types that make up the Serde data model are:
|
||||
///
|
||||
/// - 12 primitive types:
|
||||
/// - bool
|
||||
/// - i8, i16, i32, i64
|
||||
/// - u8, u16, u32, u64
|
||||
/// - f32, f64
|
||||
/// - char
|
||||
/// - string
|
||||
/// - byte array - [u8]
|
||||
/// - option
|
||||
/// - either none or some value
|
||||
/// - unit
|
||||
/// - unit is the type of () in Rust
|
||||
/// - unit_struct
|
||||
/// - for example `struct Unit` or `PhantomData<T>`
|
||||
/// - unit_variant
|
||||
/// - the `E::A` and `E::B` in `enum E { A, B }`
|
||||
/// - newtype_struct
|
||||
/// - for example `struct Millimeters(u8)`
|
||||
/// - newtype_variant
|
||||
/// - the `E::N` in `enum E { N(u8) }`
|
||||
/// - seq
|
||||
/// - a dynamically sized sequence of values, for example `Vec<T>` or
|
||||
/// `HashSet<T>`
|
||||
/// - seq_fixed_size
|
||||
/// - a statically sized sequence of values for which the size will be known
|
||||
/// at deserialization time without looking at the serialized data, for
|
||||
/// example `[u64; 10]`
|
||||
/// - tuple
|
||||
/// - for example `(u8,)` or `(String, u64, Vec<T>)`
|
||||
/// - tuple_struct
|
||||
/// - for example `struct Rgb(u8, u8, u8)`
|
||||
/// - tuple_variant
|
||||
/// - the `E::T` in `enum E { T(u8, u8) }`
|
||||
/// - map
|
||||
/// - for example `BTreeMap<K, V>`
|
||||
/// - struct
|
||||
/// - a key-value pairing in which the keys will be known at deserialization
|
||||
/// time without looking at the serialized data, for example `struct S { r:
|
||||
/// u8, g: u8, b: u8 }`
|
||||
/// - struct_variant
|
||||
/// - the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`
|
||||
///
|
||||
/// Many Serde serializers produce text or binary data as output, for example
|
||||
/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and
|
||||
/// there are serializers that do not produce text or binary output. One example
|
||||
/// is the `serde_json::value::Serializer` (distinct from the main `serde_json`
|
||||
/// serializer) that produces a `serde_json::Value` data structure in memory as
|
||||
/// output.
|
||||
pub trait Serializer: Sized {
|
||||
/// The output type produced by this `Serializer` during successful
|
||||
/// serialization. Most serializers that produce text or binary output
|
||||
/// should set `Ok = ()` and serialize into an `io::Write` or buffer
|
||||
/// contained within the `Serializer` instance. Serializers that build
|
||||
/// in-memory data structures may be simplified by using `Ok` to propagate
|
||||
/// the data structure around.
|
||||
type Ok;
|
||||
|
||||
/// The error type when some error occurs during serialization.
|
||||
type Error: Error;
|
||||
|
||||
/// Type returned from `serialize_seq` and `serialize_seq_fixed_size` for
|
||||
/// serializing the content of the sequence.
|
||||
type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple` for serializing the content of the
|
||||
/// tuple.
|
||||
type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple_struct` for serializing the content
|
||||
/// of the tuple struct.
|
||||
type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple_variant` for serializing the content
|
||||
/// of the tuple variant.
|
||||
type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_map` for serializing the content of the
|
||||
/// map.
|
||||
type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_struct` for serializing the content of the
|
||||
/// struct.
|
||||
type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_struct_variant` for serializing the
|
||||
/// content of the struct variant.
|
||||
type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Serialize a `bool` value.
|
||||
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i8` value.
|
||||
///
|
||||
/// If the format does not differentiate between `i8` and `i64`, a
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i16` value.
|
||||
///
|
||||
/// If the format does not differentiate between `i16` and `i64`, a
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i32` value.
|
||||
///
|
||||
/// If the format does not differentiate between `i32` and `i64`, a
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `i64` value.
|
||||
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u8` value.
|
||||
///
|
||||
/// If the format does not differentiate between `u8` and `u64`, a
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u16` value.
|
||||
///
|
||||
/// If the format does not differentiate between `u16` and `u64`, a
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u32` value.
|
||||
///
|
||||
/// If the format does not differentiate between `u32` and `u64`, a
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `u64` value.
|
||||
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `f32` value.
|
||||
///
|
||||
/// If the format does not differentiate between `f32` and `f64`, a
|
||||
/// reasonable implementation would be to cast the value to `f64` and
|
||||
/// forward to `serialize_f64`.
|
||||
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize an `f64` value.
|
||||
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a character.
|
||||
///
|
||||
/// If the format does not support characters, it is reasonable to serialize
|
||||
/// it as a single element `str` or a `u32`.
|
||||
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `&str`.
|
||||
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a chunk of raw byte data.
|
||||
///
|
||||
/// Enables serializers to serialize byte slices more compactly or more
|
||||
/// efficiently than other types of slices. If no efficient implementation
|
||||
/// is available, a reasonable implementation would be to forward to
|
||||
/// `serialize_seq`. If forwarded, the implementation looks usually just
|
||||
/// like this:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = self.serialize_seq(Some(value.len()))?;
|
||||
/// for b in value {
|
||||
/// seq.serialize_element(b)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `None` value.
|
||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `Some(T)` value.
|
||||
fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `()` value.
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
|
||||
///
|
||||
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||
fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a unit variant like `E::A` in `enum E { A, B }`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, and the `variant` is the name of the
|
||||
/// variant.
|
||||
///
|
||||
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::A => serializer.serialize_unit_variant("E", 0, "A"),
|
||||
/// E::B => serializer.serialize_unit_variant("E", 1, "B"),
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_unit_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str)
|
||||
-> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a newtype struct like `struct Millimeters(u8)`.
|
||||
///
|
||||
/// Serializers are encouraged to treat newtype structs as insignificant
|
||||
/// wrappers around the data they contain. A reasonable implementation would
|
||||
/// be to forward to `value.serialize(self)`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// serializer.serialize_newtype_struct("Millimeters", &self.0)
|
||||
/// ```
|
||||
fn serialize_newtype_struct<T: ?Sized + Serialize>(self,
|
||||
name: &'static str,
|
||||
value: &T)
|
||||
-> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, and the `variant` is the name of the
|
||||
/// variant. The `value` is the data contained within this newtype variant.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::N(ref n) => serializer.serialize_newtype_variant("E", 0, "N", n),
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_newtype_variant<T: ?Sized + Serialize>(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
value: &T)
|
||||
-> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Begin to serialize a dynamically sized sequence. This call must be
|
||||
/// followed by zero or more calls to `serialize_element`, then a call to
|
||||
/// `end`.
|
||||
///
|
||||
/// The argument is the number of elements in the sequence, which may or may
|
||||
/// not be computable before the sequence is iterated. Some serializers only
|
||||
/// support sequences whose length is known up front.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = serializer.serialize_seq(Some(self.len()))?;
|
||||
/// for element in self {
|
||||
/// seq.serialize_element(element)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
|
||||
/// Begin to serialize a statically sized sequence whose length will be
|
||||
/// known at deserialization time without looking at the serialized data.
|
||||
/// This call must be followed by zero or more calls to `serialize_element`,
|
||||
/// then a call to `end`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = serializer.serialize_seq_fixed_size(self.len())?;
|
||||
/// for element in self {
|
||||
/// seq.serialize_element(element)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple. This call must be followed by zero or more
|
||||
/// calls to `serialize_field`, then a call to `end`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut tup = serializer.serialize_tuple(3)?;
|
||||
/// tup.serialize_field(&self.0)?;
|
||||
/// tup.serialize_field(&self.1)?;
|
||||
/// tup.serialize_field(&self.2)?;
|
||||
/// tup.end()
|
||||
/// ```
|
||||
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
|
||||
/// call must be followed by zero or more calls to `serialize_field`, then a
|
||||
/// call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the tuple struct and the `len` is the number
|
||||
/// of data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
|
||||
/// ts.serialize_field(&self.0)?;
|
||||
/// ts.serialize_field(&self.1)?;
|
||||
/// ts.serialize_field(&self.2)?;
|
||||
/// ts.end()
|
||||
/// ```
|
||||
fn serialize_tuple_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTupleStruct, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
|
||||
/// }`. This call must be followed by zero or more calls to
|
||||
/// `serialize_field`, then a call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, the `variant` is the name of the variant,
|
||||
/// and the `len` is the number of data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::T(ref a, ref b) => {
|
||||
/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
|
||||
/// tv.serialize_field(a)?;
|
||||
/// tv.serialize_field(b)?;
|
||||
/// tv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_tuple_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTupleVariant, Self::Error>;
|
||||
|
||||
/// Begin to serialize a map. This call must be followed by zero or more
|
||||
/// calls to `serialize_key` and `serialize_value`, then a call to `end`.
|
||||
///
|
||||
/// The argument is the number of elements in the map, which may or may not
|
||||
/// be computable before the map is iterated. Some serializers only support
|
||||
/// maps whose length is known up front.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut map = serializer.serialize_map(Some(self.len()))?;
|
||||
/// for (k, v) in self {
|
||||
/// map.serialize_entry(k, v)?;
|
||||
/// }
|
||||
/// map.end()
|
||||
/// ```
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>;
|
||||
|
||||
/// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
|
||||
/// This call must be followed by zero or more calls to `serialize_field`,
|
||||
/// then a call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the struct and the `len` is the number of
|
||||
/// data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut struc = serializer.serialize_struct("Rgb", 3)?;
|
||||
/// struc.serialize_field("r", &self.r)?;
|
||||
/// struc.serialize_field("g", &self.g)?;
|
||||
/// struc.serialize_field("b", &self.b)?;
|
||||
/// struc.end()
|
||||
/// ```
|
||||
fn serialize_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStruct, Self::Error>;
|
||||
|
||||
/// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
|
||||
/// g: u8, b: u8 } }`. This call must be followed by zero or more calls to
|
||||
/// `serialize_field`, then a call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, the `variant` is the name of the variant,
|
||||
/// and the `len` is the number of data fields that will be serialized.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::S { ref r, ref g, ref b } => {
|
||||
/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
|
||||
/// sv.serialize_field("r", r)?;
|
||||
/// sv.serialize_field("g", g)?;
|
||||
/// sv.serialize_field("b", b)?;
|
||||
/// sv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_struct_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStructVariant, Self::Error>;
|
||||
|
||||
/// Collect an iterator as a sequence.
|
||||
///
|
||||
/// The default implementation serializes each item yielded by the iterator
|
||||
/// using `Self::SerializeSeq`. Implementors should not need to override
|
||||
/// this method.
|
||||
fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
|
||||
where I: IntoIterator,
|
||||
<I as IntoIterator>::Item: Serialize
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_seq(iter.len_hint()));
|
||||
for item in iter {
|
||||
try!(serializer.serialize_element(&item));
|
||||
}
|
||||
serializer.end()
|
||||
}
|
||||
|
||||
/// Collect an iterator as a map.
|
||||
///
|
||||
/// The default implementation serializes each pair yielded by the iterator
|
||||
/// using `Self::SerializeMap`. Implementors should not need to override
|
||||
/// this method.
|
||||
fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
|
||||
where K: Serialize,
|
||||
V: Serialize,
|
||||
I: IntoIterator<Item = (K, V)>
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_map(iter.len_hint()));
|
||||
for (key, value) in iter {
|
||||
try!(serializer.serialize_entry(&key, &value));
|
||||
}
|
||||
serializer.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_seq` and
|
||||
/// `Serializer::serialize_seq_fixed_size`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut seq = serializer.serialize_seq(Some(self.len()))?;
|
||||
/// for element in self {
|
||||
/// seq.serialize_element(element)?;
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
pub trait SerializeSeq {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a sequence element.
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a sequence.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_tuple`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut tup = serializer.serialize_tuple(3)?;
|
||||
/// tup.serialize_field(&self.0)?;
|
||||
/// tup.serialize_field(&self.1)?;
|
||||
/// tup.serialize_field(&self.2)?;
|
||||
/// tup.end()
|
||||
/// ```
|
||||
pub trait SerializeTuple {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple element.
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a tuple.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_tuple_struct`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
|
||||
/// ts.serialize_field(&self.0)?;
|
||||
/// ts.serialize_field(&self.1)?;
|
||||
/// ts.serialize_field(&self.2)?;
|
||||
/// ts.end()
|
||||
/// ```
|
||||
pub trait SerializeTupleStruct {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple struct field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a tuple struct.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_tuple_variant`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::T(ref a, ref b) => {
|
||||
/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
|
||||
/// tv.serialize_field(a)?;
|
||||
/// tv.serialize_field(b)?;
|
||||
/// tv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait SerializeTupleVariant {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple variant field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a tuple variant.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_map`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut map = serializer.serialize_map(Some(self.len()))?;
|
||||
/// for (k, v) in self {
|
||||
/// map.serialize_entry(k, v)?;
|
||||
/// }
|
||||
/// map.end()
|
||||
/// ```
|
||||
pub trait SerializeMap {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a map key.
|
||||
fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Serialize a map value.
|
||||
fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||
|
||||
/// Serialize a map entry consisting of a key and a value.
|
||||
///
|
||||
/// Some `Serialize` types are not able to hold a key and value in memory at
|
||||
/// the same time so `SerializeMap` implementations are required to support
|
||||
/// `serialize_key` and `serialize_value` individually. The
|
||||
/// `serialize_entry` method allows serializers to optimize for the case
|
||||
/// where key and value are both available. `Serialize` implementations are
|
||||
/// encouraged to use `serialize_entry` if possible.
|
||||
///
|
||||
/// The default implementation delegates to `serialize_key` and
|
||||
/// `serialize_value`. This is appropriate for serializers that do not care
|
||||
/// about performance or are not able to optimize `serialize_entry` any
|
||||
/// better than this.
|
||||
fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(&mut self,
|
||||
key: &K,
|
||||
value: &V)
|
||||
-> Result<(), Self::Error> {
|
||||
try!(self.serialize_key(key));
|
||||
self.serialize_value(value)
|
||||
}
|
||||
|
||||
/// Finish serializing a map.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_struct`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let mut struc = serializer.serialize_struct("Rgb", 3)?;
|
||||
/// struc.serialize_field("r", &self.r)?;
|
||||
/// struc.serialize_field("g", &self.g)?;
|
||||
/// struc.serialize_field("b", &self.b)?;
|
||||
/// struc.end()
|
||||
/// ```
|
||||
pub trait SerializeStruct {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a struct.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_struct_variant`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// match *self {
|
||||
/// E::S { ref r, ref g, ref b } => {
|
||||
/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
|
||||
/// sv.serialize_field("r", r)?;
|
||||
/// sv.serialize_field("g", g)?;
|
||||
/// sv.serialize_field("b", b)?;
|
||||
/// sv.end()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait SerializeStructVariant {
|
||||
/// Must match the `Ok` type of our `Serializer`.
|
||||
type Ok;
|
||||
|
||||
/// Must match the `Error` type of our `Serializer`.
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct variant field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a struct variant.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
trait LenHint: Iterator {
|
||||
fn len_hint(&self) -> Option<usize>;
|
||||
}
|
||||
|
||||
impl<I: Iterator> LenHint for I {
|
||||
#[cfg(not(feature = "unstable"))]
|
||||
fn len_hint(&self) -> Option<usize> {
|
||||
iterator_len_hint(self)
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
default fn len_hint(&self) -> Option<usize> {
|
||||
iterator_len_hint(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<I: ExactSizeIterator> LenHint for I {
|
||||
fn len_hint(&self) -> Option<usize> {
|
||||
Some(self.len())
|
||||
}
|
||||
}
|
||||
|
||||
fn iterator_len_hint<I: Iterator>(iter: &I) -> Option<usize> {
|
||||
match iter.size_hint() {
|
||||
(lo, Some(hi)) if lo == hi => Some(lo),
|
||||
_ => None,
|
||||
}
|
||||
}
|
|
@ -1,313 +0,0 @@
|
|||
use core::fmt::{self, Display};
|
||||
|
||||
use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct, Impossible};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
use ser::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMapValue};
|
||||
|
||||
/// Not public API.
|
||||
pub fn serialize_tagged_newtype<S, T>(serializer: S,
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
tag: &'static str,
|
||||
variant_name: &'static str,
|
||||
value: T)
|
||||
-> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
T: Serialize
|
||||
{
|
||||
value.serialize(TaggedSerializer {
|
||||
type_ident: type_ident,
|
||||
variant_ident: variant_ident,
|
||||
tag: tag,
|
||||
variant_name: variant_name,
|
||||
delegate: serializer,
|
||||
})
|
||||
}
|
||||
|
||||
struct TaggedSerializer<S> {
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
tag: &'static str,
|
||||
variant_name: &'static str,
|
||||
delegate: S,
|
||||
}
|
||||
|
||||
enum Unsupported {
|
||||
Boolean,
|
||||
Integer,
|
||||
Float,
|
||||
Char,
|
||||
String,
|
||||
ByteArray,
|
||||
Optional,
|
||||
Unit,
|
||||
UnitStruct,
|
||||
Sequence,
|
||||
Tuple,
|
||||
TupleStruct,
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
Enum,
|
||||
}
|
||||
|
||||
impl Display for Unsupported {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Unsupported::Boolean => formatter.write_str("a boolean"),
|
||||
Unsupported::Integer => formatter.write_str("an integer"),
|
||||
Unsupported::Float => formatter.write_str("a float"),
|
||||
Unsupported::Char => formatter.write_str("a char"),
|
||||
Unsupported::String => formatter.write_str("a string"),
|
||||
Unsupported::ByteArray => formatter.write_str("a byte array"),
|
||||
Unsupported::Optional => formatter.write_str("an optional"),
|
||||
Unsupported::Unit => formatter.write_str("unit"),
|
||||
Unsupported::UnitStruct => formatter.write_str("a unit struct"),
|
||||
Unsupported::Sequence => formatter.write_str("a sequence"),
|
||||
Unsupported::Tuple => formatter.write_str("a tuple"),
|
||||
Unsupported::TupleStruct => formatter.write_str("a tuple struct"),
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
Unsupported::Enum => formatter.write_str("an enum"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Error {
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
ty: Unsupported,
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter,
|
||||
"cannot serialize tagged newtype variant {}::{} containing {}",
|
||||
self.type_ident, self.variant_ident, self.ty)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> TaggedSerializer<S>
|
||||
where S: Serializer
|
||||
{
|
||||
fn bad_type(self, what: Unsupported) -> S::Error {
|
||||
ser::Error::custom(Error {
|
||||
type_ident: self.type_ident,
|
||||
variant_ident: self.variant_ident,
|
||||
ty: what,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Serializer for TaggedSerializer<S>
|
||||
where S: Serializer
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
|
||||
type SerializeSeq = Impossible<S::Ok, S::Error>;
|
||||
type SerializeTuple = Impossible<S::Ok, S::Error>;
|
||||
type SerializeTupleStruct = Impossible<S::Ok, S::Error>;
|
||||
type SerializeMap = S::SerializeMap;
|
||||
type SerializeStruct = S::SerializeStruct;
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
type SerializeTupleVariant = Impossible<S::Ok, S::Error>;
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>;
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
type SerializeStructVariant = Impossible<S::Ok, S::Error>;
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>;
|
||||
|
||||
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Boolean))
|
||||
}
|
||||
|
||||
fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Char))
|
||||
}
|
||||
|
||||
fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::String))
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::ByteArray))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Unit))
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::UnitStruct))
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
inner_variant: &'static str)
|
||||
-> Result<Self::Ok, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_entry(inner_variant, &()));
|
||||
map.end()
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self,
|
||||
_: &'static str,
|
||||
value: &T)
|
||||
-> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
inner_variant: &'static str,
|
||||
inner_value: &T)
|
||||
-> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_entry(inner_variant, inner_value));
|
||||
map.end()
|
||||
}
|
||||
|
||||
fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Sequence))
|
||||
}
|
||||
|
||||
fn serialize_seq_fixed_size(self, _: usize) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Sequence))
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Tuple))
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self,
|
||||
_: &'static str,
|
||||
_: usize)
|
||||
-> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::TupleStruct))
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
fn serialize_tuple_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: &'static str,
|
||||
_: usize)
|
||||
-> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
// Lack of push-based serialization means we need to buffer the content
|
||||
// of the tuple variant, so it requires std.
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
fn serialize_tuple_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
inner_variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_key(inner_variant));
|
||||
Ok(SerializeTupleVariantAsMapValue::new(map, inner_variant, len))
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
fn serialize_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStruct, Self::Error> {
|
||||
let mut state = try!(self.delegate.serialize_struct(name, len + 1));
|
||||
try!(state.serialize_field(self.tag, self.variant_name));
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
fn serialize_struct_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: &'static str,
|
||||
_: usize)
|
||||
-> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
// Lack of push-based serialization means we need to buffer the content
|
||||
// of the struct variant, so it requires std.
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
fn serialize_struct_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
inner_variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_key(inner_variant));
|
||||
Ok(SerializeStructVariantAsMapValue::new(map, inner_variant, len))
|
||||
}
|
||||
}
|
|
@ -1,74 +0,0 @@
|
|||
//! Private utility functions
|
||||
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_THREE_B: u8 = 0b1110_0000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
|
||||
#[inline]
|
||||
pub fn encode_utf8(c: char) -> EncodeUtf8 {
|
||||
let code = c as u32;
|
||||
let mut buf = [0; 4];
|
||||
let pos = if code < MAX_ONE_B {
|
||||
buf[3] = code as u8;
|
||||
3
|
||||
} else if code < MAX_TWO_B {
|
||||
buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
2
|
||||
} else if code < MAX_THREE_B {
|
||||
buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
1
|
||||
} else {
|
||||
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
|
||||
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
0
|
||||
};
|
||||
EncodeUtf8 {
|
||||
buf: buf,
|
||||
pos: pos,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EncodeUtf8 {
|
||||
buf: [u8; 4],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl EncodeUtf8 {
|
||||
// FIXME: use this from_utf8_unchecked, since we know it can never fail
|
||||
pub fn as_str(&self) -> &str {
|
||||
::core::str::from_utf8(&self.buf[self.pos..]).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
const Pattern_White_Space_table: &'static [(char, char)] = &[('\u{9}', '\u{d}'),
|
||||
('\u{20}', '\u{20}'),
|
||||
('\u{85}', '\u{85}'),
|
||||
('\u{200e}', '\u{200f}'),
|
||||
('\u{2028}', '\u{2029}')];
|
||||
|
||||
fn bsearch_range_table(c: char, r: &'static [(char, char)]) -> bool {
|
||||
use core::cmp::Ordering::{Equal, Less, Greater};
|
||||
r.binary_search_by(|&(lo, hi)| if c < lo {
|
||||
Greater
|
||||
} else if hi < c {
|
||||
Less
|
||||
} else {
|
||||
Equal
|
||||
})
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub fn Pattern_White_Space(c: char) -> bool {
|
||||
bsearch_range_table(c, Pattern_White_Space_table)
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"f11d07b974965dc94833195275fa536a0d7790e16ad3389d08f1e198202073fa","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"ebe318a04cf4e547e0f3ab97f1345ecb553358ee13ea81f99e3323e37d70ccdf","src/ast.rs":"7eedebeb0d2b76bda66c0b414a2a40ac19ff1d8604a84cd5d207b76d2d57de97","src/attr.rs":"77daffa2fd682d85debac843c5e69ebf1a1061a680c5d8e590ecf8fcf63976b7","src/case.rs":"44e5506efb5a99478b357f1b2ee1baf40a44b8630997cd62d657b1c677752932","src/ctxt.rs":"3650e9cfc8b58e65137bc5e5ee250117c5abe4a543807a908adabf1a1f57825a","src/lib.rs":"e620949a156816b0e326481d1070febc449cf72849bffd3ca15c473ff3af13e8"},"package":"4d52006899f910528a10631e5b727973fe668f3228109d1707ccf5bad5490b6e"}
|
|
@ -1,18 +0,0 @@
|
|||
[package]
|
||||
name = "serde_codegen_internals"
|
||||
version = "0.14.1"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "AST representation used by Serde codegen. Unstable."
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde_codegen_internals/"
|
||||
keywords = ["serde", "serialization"]
|
||||
readme = "../README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[dependencies]
|
||||
syn = { version = "0.11", default-features = false, features = ["parsing"] }
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
|
@ -1,201 +0,0 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -1,25 +0,0 @@
|
|||
Copyright (c) 2014 The Rust Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
|
@ -1,71 +0,0 @@
|
|||
# Serde   [![Build Status](https://api.travis-ci.org/serde-rs/serde.svg?branch=master)](https://travis-ci.org/serde-rs/serde) [![Latest Version](https://img.shields.io/crates/v/serde.svg)](https://crates.io/crates/serde)
|
||||
|
||||
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
|
||||
|
||||
---
|
||||
|
||||
You may be looking for:
|
||||
|
||||
- [An overview of Serde](https://serde.rs/)
|
||||
- [Data formats supported by Serde](https://serde.rs/#data-formats)
|
||||
- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html)
|
||||
- [Examples](https://serde.rs/examples.html)
|
||||
- [API documentation](https://docs.serde.rs/serde/)
|
||||
- [Release notes](https://github.com/serde-rs/serde/releases)
|
||||
|
||||
## Serde in action
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde_json;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
struct Point {
|
||||
x: i32,
|
||||
y: i32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let point = Point { x: 1, y: 2 };
|
||||
|
||||
// Convert the Point to a JSON string.
|
||||
let serialized = serde_json::to_string(&point).unwrap();
|
||||
|
||||
// Prints serialized = {"x":1,"y":2}
|
||||
println!("serialized = {}", serialized);
|
||||
|
||||
// Convert the JSON string back to a Point.
|
||||
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
|
||||
|
||||
// Prints deserialized = Point { x: 1, y: 2 }
|
||||
println!("deserialized = {:?}", deserialized);
|
||||
}
|
||||
```
|
||||
|
||||
## Getting help
|
||||
|
||||
Serde developers live in the #serde channel on
|
||||
[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a
|
||||
good resource with generally faster response time but less specific knowledge
|
||||
about Serde. If IRC is not your thing or you don't get a good response, we are
|
||||
happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new)
|
||||
as well.
|
||||
|
||||
## License
|
||||
|
||||
Serde is licensed under either of
|
||||
|
||||
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
|
||||
http://www.apache.org/licenses/LICENSE-2.0)
|
||||
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
|
||||
http://opensource.org/licenses/MIT)
|
||||
|
||||
at your option.
|
||||
|
||||
### Contribution
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted
|
||||
for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be
|
||||
dual licensed as above, without any additional terms or conditions.
|
|
@ -1,9 +0,0 @@
|
|||
extern crate syn;
|
||||
|
||||
pub mod ast;
|
||||
pub mod attr;
|
||||
|
||||
mod ctxt;
|
||||
pub use ctxt::Ctxt;
|
||||
|
||||
mod case;
|
|
@ -1 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"b48eda1c232a1fb0725482abbe38616d3e9df3ba207c6581b2c918b6976cdcbf","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"ebe318a04cf4e547e0f3ab97f1345ecb553358ee13ea81f99e3323e37d70ccdf","src/bound.rs":"9af80108627e7065366bd065e5125fbf292a3aac4e4014977decc42f659d3af2","src/de.rs":"51cedf6f6711b90829cb625f0e43ed765380321e1add80646cda3561dfe3d074","src/fragment.rs":"a4d5286453b280d457579bd17b4deb3f9ce2e5f6c3e446c4ef61774b87045589","src/lib.rs":"53826d40b094cb4c39d5b99dcc4ce1f84e96cec8d7e51e158b00036d18c7442a","src/ser.rs":"19aab089d33b23e46805b5d58185b1471b6d2ede5fe5f272767ce95ff1d48a31"},"package":"f15ea24bd037b2d64646b4d934fa99c649be66e3f7b29fb595a5543b212b1452"}
|
||||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"fc1c90305d1d8d6debda370913068486b2465b4ac548651f9122169def6da94c","Cargo.toml.orig":"75ec66d9e09e8a4c08c6e88441a14b429d2d6f2ea47d6d45cea30a1bac138205","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"eedee04bddb61e99bc816656bb3b8ae2fa50ff00045ecdb5212682f3592d9ab2","src/bound.rs":"c01b1ec82b830b01a840d27654f2b1d3354e62a2b404227fccbb84d80cc6a593","src/de.rs":"518d74b38a7c254383fa6b2e5bfd71137e3abfbeda8b2577d25b7d8acdb03df5","src/fragment.rs":"f1642a1c2abbc36191206a5ec8077e314bdc20a420d7649e4bec3a69d555f78d","src/lib.rs":"fda8bd7ae031370f004d2672c12bfb9a5ae4314f499b5c7cbf9947e810d1d255","src/ser.rs":"b573af63ecfc51849b1157e2c3ae55b3bc256c3ce4b2712a639c5750e42eddfa"},"package":"10552fad5500771f3902d0c5ba187c5881942b811b7ba0d8fbbfbf84d80806d3"}
|
|
@ -1,21 +1,27 @@
|
|||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g. crates.io) dependencies
|
||||
#
|
||||
# If you believe there's an error in this file please file an
|
||||
# issue against the rust-lang/cargo repository. If you're
|
||||
# editing this file be aware that the upstream Cargo.toml
|
||||
# will likely look very different (and much more reasonable)
|
||||
|
||||
[package]
|
||||
name = "serde_derive"
|
||||
version = "0.9.11"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
version = "1.0.8"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://serde.rs/codegen.html"
|
||||
readme = "README.md"
|
||||
keywords = ["serde", "serialization", "no_std"]
|
||||
readme = "../README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[features]
|
||||
unstable = []
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
license = "MIT/Apache-2.0"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
|
||||
[lib]
|
||||
name = "serde_derive"
|
||||
|
@ -23,5 +29,13 @@ proc-macro = true
|
|||
|
||||
[dependencies]
|
||||
quote = "0.3.8"
|
||||
serde_codegen_internals = { version = "=0.14.1", default-features = false, path = "../serde_codegen_internals" }
|
||||
syn = { version = "0.11", features = ["visit"] }
|
||||
|
||||
[dependencies.syn]
|
||||
version = "0.11"
|
||||
features = ["visit"]
|
||||
|
||||
[dependencies.serde_derive_internals]
|
||||
version = "=0.15.1"
|
||||
default-features = false
|
||||
[badges.travis-ci]
|
||||
repository = "serde-rs/serde"
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
[package]
|
||||
name = "serde_derive"
|
||||
version = "1.0.8" # remember to update html_root_url
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://serde.rs/codegen.html"
|
||||
keywords = ["serde", "serialization", "no_std"]
|
||||
readme = "README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
|
||||
[lib]
|
||||
name = "serde_derive"
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "0.3.8"
|
||||
serde_derive_internals = { version = "=0.15.1", default-features = false, path = "../serde_derive_internals" }
|
||||
syn = { version = "0.11", features = ["visit"] }
|
|
@ -1,4 +1,9 @@
|
|||
# Serde   [![Build Status](https://api.travis-ci.org/serde-rs/serde.svg?branch=master)](https://travis-ci.org/serde-rs/serde) [![Latest Version](https://img.shields.io/crates/v/serde.svg)](https://crates.io/crates/serde)
|
||||
# Serde   [![Build Status]][travis] [![Latest Version]][crates.io]
|
||||
|
||||
[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master
|
||||
[travis]: https://travis-ci.org/serde-rs/serde
|
||||
[Latest Version]: https://img.shields.io/crates/v/serde.svg
|
||||
[crates.io]: https://crates.io/crates/serde
|
||||
|
||||
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
|
||||
|
||||
|
@ -15,10 +20,15 @@ You may be looking for:
|
|||
|
||||
## Serde in action
|
||||
|
||||
<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">
|
||||
<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png">
|
||||
</a>
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde;
|
||||
extern crate serde_json;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
|
|
|
@ -1,33 +1,21 @@
|
|||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use syn::{self, visit};
|
||||
|
||||
use internals::ast::Item;
|
||||
use internals::ast::Container;
|
||||
use internals::attr;
|
||||
|
||||
macro_rules! path {
|
||||
($first:ident $(:: $rest:ident)*) => {
|
||||
syn::Path {
|
||||
global: false,
|
||||
segments: vec![
|
||||
stringify!($first).into(),
|
||||
$(
|
||||
stringify!($rest).into(),
|
||||
)*
|
||||
],
|
||||
}
|
||||
};
|
||||
|
||||
(::$first:ident $(:: $rest:ident)*) => {
|
||||
syn::Path {
|
||||
global: true,
|
||||
segments: vec![
|
||||
stringify!($first).into(),
|
||||
$(
|
||||
stringify!($rest).into(),
|
||||
)*
|
||||
],
|
||||
}
|
||||
($($path:tt)+) => {
|
||||
syn::parse_path(stringify!($($path)+)).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -36,29 +24,43 @@ macro_rules! path {
|
|||
// allowed here".
|
||||
pub fn without_defaults(generics: &syn::Generics) -> syn::Generics {
|
||||
syn::Generics {
|
||||
ty_params: generics.ty_params
|
||||
ty_params: generics
|
||||
.ty_params
|
||||
.iter()
|
||||
.map(|ty_param| syn::TyParam { default: None, ..ty_param.clone() })
|
||||
.map(
|
||||
|ty_param| {
|
||||
syn::TyParam {
|
||||
default: None,
|
||||
..ty_param.clone()
|
||||
}
|
||||
},
|
||||
)
|
||||
.collect(),
|
||||
..generics.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_where_predicates(generics: &syn::Generics,
|
||||
predicates: &[syn::WherePredicate])
|
||||
-> syn::Generics {
|
||||
pub fn with_where_predicates(
|
||||
generics: &syn::Generics,
|
||||
predicates: &[syn::WherePredicate],
|
||||
) -> syn::Generics {
|
||||
let mut generics = generics.clone();
|
||||
generics.where_clause.predicates.extend_from_slice(predicates);
|
||||
generics
|
||||
.where_clause
|
||||
.predicates
|
||||
.extend_from_slice(predicates);
|
||||
generics
|
||||
}
|
||||
|
||||
pub fn with_where_predicates_from_fields<F>(item: &Item,
|
||||
generics: &syn::Generics,
|
||||
from_field: F)
|
||||
-> syn::Generics
|
||||
where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>
|
||||
pub fn with_where_predicates_from_fields<F>(
|
||||
cont: &Container,
|
||||
generics: &syn::Generics,
|
||||
from_field: F,
|
||||
) -> syn::Generics
|
||||
where
|
||||
F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
|
||||
{
|
||||
let predicates = item.body
|
||||
let predicates = cont.body
|
||||
.all_fields()
|
||||
.flat_map(|field| from_field(&field.attrs))
|
||||
.flat_map(|predicates| predicates.to_vec());
|
||||
|
@ -79,12 +81,14 @@ pub fn with_where_predicates_from_fields<F>(item: &Item,
|
|||
// #[serde(skip_serializing)]
|
||||
// c: C,
|
||||
// }
|
||||
pub fn with_bound<F>(item: &Item,
|
||||
generics: &syn::Generics,
|
||||
filter: F,
|
||||
bound: &syn::Path)
|
||||
-> syn::Generics
|
||||
where F: Fn(&attr::Field) -> bool
|
||||
pub fn with_bound<F>(
|
||||
cont: &Container,
|
||||
generics: &syn::Generics,
|
||||
filter: F,
|
||||
bound: &syn::Path,
|
||||
) -> syn::Generics
|
||||
where
|
||||
F: Fn(&attr::Field) -> bool,
|
||||
{
|
||||
struct FindTyParams {
|
||||
// Set of all generic type parameters on the current struct (A, B, C in
|
||||
|
@ -114,12 +118,13 @@ pub fn with_bound<F>(item: &Item,
|
|||
}
|
||||
}
|
||||
|
||||
let all_ty_params: HashSet<_> = generics.ty_params
|
||||
let all_ty_params: HashSet<_> = generics
|
||||
.ty_params
|
||||
.iter()
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.collect();
|
||||
|
||||
let relevant_tys = item.body
|
||||
let relevant_tys = cont.body
|
||||
.all_fields()
|
||||
.filter(|&field| filter(&field.attrs))
|
||||
.map(|field| &field.ty);
|
||||
|
@ -132,58 +137,70 @@ pub fn with_bound<F>(item: &Item,
|
|||
visit::walk_ty(&mut visitor, ty);
|
||||
}
|
||||
|
||||
let new_predicates = generics.ty_params
|
||||
let new_predicates = generics
|
||||
.ty_params
|
||||
.iter()
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.filter(|id| visitor.relevant_ty_params.contains(id))
|
||||
.map(|id| {
|
||||
syn::WherePredicate::BoundPredicate(syn::WhereBoundPredicate {
|
||||
bound_lifetimes: Vec::new(),
|
||||
// the type parameter that is being bounded e.g. T
|
||||
bounded_ty: syn::Ty::Path(None, id.into()),
|
||||
// the bound e.g. Serialize
|
||||
bounds: vec![syn::TyParamBound::Trait(
|
||||
syn::PolyTraitRef {
|
||||
.map(
|
||||
|id| {
|
||||
syn::WherePredicate::BoundPredicate(
|
||||
syn::WhereBoundPredicate {
|
||||
bound_lifetimes: Vec::new(),
|
||||
trait_ref: bound.clone(),
|
||||
// the type parameter that is being bounded e.g. T
|
||||
bounded_ty: syn::Ty::Path(None, id.into()),
|
||||
// the bound e.g. Serialize
|
||||
bounds: vec![
|
||||
syn::TyParamBound::Trait(
|
||||
syn::PolyTraitRef {
|
||||
bound_lifetimes: Vec::new(),
|
||||
trait_ref: bound.clone(),
|
||||
},
|
||||
syn::TraitBoundModifier::None,
|
||||
),
|
||||
],
|
||||
},
|
||||
syn::TraitBoundModifier::None
|
||||
)],
|
||||
})
|
||||
});
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
let mut generics = generics.clone();
|
||||
generics.where_clause.predicates.extend(new_predicates);
|
||||
generics
|
||||
}
|
||||
|
||||
pub fn with_self_bound(item: &Item,
|
||||
generics: &syn::Generics,
|
||||
bound: &syn::Path)
|
||||
-> syn::Generics
|
||||
{
|
||||
pub fn with_self_bound(
|
||||
cont: &Container,
|
||||
generics: &syn::Generics,
|
||||
bound: &syn::Path,
|
||||
) -> syn::Generics {
|
||||
let mut generics = generics.clone();
|
||||
generics.where_clause.predicates.push(
|
||||
syn::WherePredicate::BoundPredicate(syn::WhereBoundPredicate {
|
||||
bound_lifetimes: Vec::new(),
|
||||
// the type that is being bounded e.g. MyStruct<'a, T>
|
||||
bounded_ty: type_of_item(item),
|
||||
// the bound e.g. Default
|
||||
bounds: vec![syn::TyParamBound::Trait(
|
||||
syn::PolyTraitRef {
|
||||
generics
|
||||
.where_clause
|
||||
.predicates
|
||||
.push(
|
||||
syn::WherePredicate::BoundPredicate(
|
||||
syn::WhereBoundPredicate {
|
||||
bound_lifetimes: Vec::new(),
|
||||
trait_ref: bound.clone(),
|
||||
// the type that is being bounded e.g. MyStruct<'a, T>
|
||||
bounded_ty: type_of_item(cont),
|
||||
// the bound e.g. Default
|
||||
bounds: vec![
|
||||
syn::TyParamBound::Trait(
|
||||
syn::PolyTraitRef {
|
||||
bound_lifetimes: Vec::new(),
|
||||
trait_ref: bound.clone(),
|
||||
},
|
||||
syn::TraitBoundModifier::None,
|
||||
),
|
||||
],
|
||||
},
|
||||
syn::TraitBoundModifier::None
|
||||
)],
|
||||
})
|
||||
);
|
||||
),
|
||||
);
|
||||
generics
|
||||
}
|
||||
|
||||
pub fn with_lifetime_bound(generics: &syn::Generics,
|
||||
lifetime: &str)
|
||||
-> syn::Generics {
|
||||
pub fn with_lifetime_bound(generics: &syn::Generics, lifetime: &str) -> syn::Generics {
|
||||
let mut generics = generics.clone();
|
||||
|
||||
for lifetime_def in &mut generics.lifetimes {
|
||||
|
@ -191,38 +208,49 @@ pub fn with_lifetime_bound(generics: &syn::Generics,
|
|||
}
|
||||
|
||||
for ty_param in &mut generics.ty_params {
|
||||
ty_param.bounds.push(syn::TyParamBound::Region(syn::Lifetime::new(lifetime)));
|
||||
ty_param
|
||||
.bounds
|
||||
.push(syn::TyParamBound::Region(syn::Lifetime::new(lifetime)));
|
||||
}
|
||||
|
||||
generics.lifetimes.push(syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new(lifetime),
|
||||
bounds: Vec::new(),
|
||||
});
|
||||
generics
|
||||
.lifetimes
|
||||
.push(
|
||||
syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new(lifetime),
|
||||
bounds: Vec::new(),
|
||||
},
|
||||
);
|
||||
|
||||
generics
|
||||
}
|
||||
|
||||
fn type_of_item(item: &Item) -> syn::Ty {
|
||||
syn::Ty::Path(None, syn::Path {
|
||||
global: false,
|
||||
segments: vec![
|
||||
syn::PathSegment {
|
||||
ident: item.ident.clone(),
|
||||
parameters: syn::PathParameters::AngleBracketed(syn::AngleBracketedParameterData {
|
||||
lifetimes: item.generics
|
||||
.lifetimes
|
||||
.iter()
|
||||
.map(|def| def.lifetime.clone())
|
||||
.collect(),
|
||||
types: item.generics
|
||||
fn type_of_item(cont: &Container) -> syn::Ty {
|
||||
syn::Ty::Path(
|
||||
None,
|
||||
syn::Path {
|
||||
global: false,
|
||||
segments: vec![
|
||||
syn::PathSegment {
|
||||
ident: cont.ident.clone(),
|
||||
parameters: syn::PathParameters::AngleBracketed(
|
||||
syn::AngleBracketedParameterData {
|
||||
lifetimes: cont.generics
|
||||
.lifetimes
|
||||
.iter()
|
||||
.map(|def| def.lifetime.clone())
|
||||
.collect(),
|
||||
types: cont.generics
|
||||
.ty_params
|
||||
.iter()
|
||||
.map(|param| syn::Ty::Path(None, param.ident.clone().into()))
|
||||
.collect(),
|
||||
bindings: Vec::new(),
|
||||
}),
|
||||
}
|
||||
]
|
||||
})
|
||||
bindings: Vec::new(),
|
||||
},
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -1,3 +1,11 @@
|
|||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use quote::{Tokens, ToTokens};
|
||||
|
||||
pub enum Fragment {
|
||||
|
|
|
@ -1,3 +1,23 @@
|
|||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
//! This crate provides Serde's two derive macros.
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! #[derive(Serialize, Deserialize)]
|
||||
//! ```
|
||||
//!
|
||||
//! Please refer to [https://serde.rs/derive.html] for how to set this up.
|
||||
//!
|
||||
//! [https://serde.rs/derive.html]: https://serde.rs/derive.html
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.8")]
|
||||
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]
|
||||
|
||||
|
@ -8,7 +28,7 @@ extern crate syn;
|
|||
#[macro_use]
|
||||
extern crate quote;
|
||||
|
||||
extern crate serde_codegen_internals as internals;
|
||||
extern crate serde_derive_internals as internals;
|
||||
|
||||
extern crate proc_macro;
|
||||
use proc_macro::TokenStream;
|
||||
|
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1 @@
|
|||
{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"511194979a2e34ebea7b27d4abe9350a6d6d2beb4ee074e296c5b95f4c8fc6e9","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"eedee04bddb61e99bc816656bb3b8ae2fa50ff00045ecdb5212682f3592d9ab2","src/ast.rs":"6d41e5055cc012474f72a2fb25874d8f59b872ccccddc2dee83ceaaa08135cd9","src/attr.rs":"bfd6120502807f8a5531a846fd76128ce133b9f9d162a6ea35e471afb73a3b20","src/case.rs":"036711fc550a405ab86d9470c94bac1d58dcdcad4e3a672c73cc0c5a0ecc138b","src/check.rs":"69ecc07d0916ae33ba868eb697ca35f7cd2e97127187f1e95efdcf7ad8e5e2f8","src/ctxt.rs":"98eab1acd3de8617b516d1de7d5d870bb1d2a1c1aca258a4cca2bde3f8df88e4","src/lib.rs":"7fef231c76b77486d813fa43a5dc7394fdeb8b1e95e02f5c1205213725ed400b"},"package":"37aee4e0da52d801acfbc0cc219eb1eda7142112339726e427926a6f6ee65d3a"}
|
|
@ -0,0 +1,19 @@
|
|||
[package]
|
||||
name = "serde_derive_internals"
|
||||
version = "0.15.1" # remember to update html_root_url
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "AST representation used by Serde derive macros. Unstable."
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde_derive_internals/"
|
||||
keywords = ["serde", "serialization"]
|
||||
readme = "README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[dependencies]
|
||||
syn = { version = "0.11.10", default-features = false, features = ["parsing"] }
|
||||
synom = "0.11"
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Загрузка…
Ссылка в новой задаче