deleted file mode 100644
--- a/third_party/rust/app_units-0.3.0/.cargo-checksum.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"12cc0f91b51fedf41ae1670d1624ee1d78a284bdb101645b60a06a12de16c069",".travis.yml":"6b96b2c6bfd7e1acef4b825a2813fc4277859eb9400a16800db8835c25e4087d","Cargo.toml":"789b93a48ce76901375209d5462408469c31809e09a98e71370c57187a4b0923","README.md":"9f048d969f9f8333cdcdb892744cd0816e4f2922c8817fa5e9e07f9472fe1050","src/app_unit.rs":"71b0ac2fa378427883649def1a03008ac9d4eb45addd084b7d9885867049551e","src/lib.rs":"2df7d863c47d8b22f9af66caeafa87e6a206ee713a8aeaa55c5a80a42a92513b"},"package":"636ee56f12e31dbc11dc0a1ac6004f08b04e6e6595963716fc8130e90d4e04cf"}
\ No newline at end of file
deleted file mode 100644
--- a/third_party/rust/app_units-0.3.0/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-target/
-Cargo.lock
deleted file mode 100644
--- a/third_party/rust/app_units-0.3.0/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: rust
-notifications:
- webhooks: http://build.servo.org:54856/travis
-
-rust:
- - stable
- - beta
- - nightly
deleted file mode 100644
--- a/third_party/rust/app_units-0.3.0/Cargo.toml
+++ /dev/null
@@ -1,18 +0,0 @@
-[package]
-name = "app_units"
-version = "0.3.0"
-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"
-
-[features]
-default = []
-plugins = []
-
-[dependencies]
-heapsize = "0.3"
-num-traits = "0.1.32"
-rustc-serialize = "0.3"
-serde = "0.8"
deleted file mode 100644
--- a/third_party/rust/app_units-0.3.0/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# app-units
-
-[Documentation](http://doc.servo.org/app_units/index.html)
deleted file mode 100644
--- a/third_party/rust/app_units-0.3.0/src/app_unit.rs
+++ /dev/null
@@ -1,315 +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)]
-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: &mut D) -> Result<Au, D::Error> {
- Ok(Au(try!(i32::deserialize(deserializer))))
- }
-}
-
-impl Serialize for Au {
- fn serialize<S: Serializer>(&self, serializer: &mut S) -> Result<(), 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
- }
-}
-
-pub const MIN_AU: Au = Au(i32::MIN);
-pub const MAX_AU: Au = Au(i32::MAX);
-
-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.wrapping_add(other.0))
- }
-}
-
-impl Sub for Au {
- type Output = Au;
-
- #[inline]
- fn sub(self, other: Au) -> Au {
- Au(self.0.wrapping_sub(other.0))
- }
-
-}
-
-impl Mul<i32> for Au {
- type Output = Au;
-
- #[inline]
- fn mul(self, other: i32) -> Au {
- Au(self.0.wrapping_mul(other))
- }
-}
-
-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;
- }
-}
-
-impl SubAssign for Au {
- #[inline]
- fn sub_assign(&mut self, other: Au) {
- *self = *self - other;
- }
-}
-
-impl MulAssign<i32> for Au {
- #[inline]
- fn mul_assign(&mut self, other: i32) {
- *self = *self * other;
- }
-}
-
-impl DivAssign<i32> for Au {
- #[inline]
- fn div_assign(&mut self, other: i32) {
- *self = *self / other;
- }
-}
-
-impl Au {
- /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
- #[inline]
- pub fn new(value: i32) -> Au {
- Au(value)
- }
-
- #[inline]
- pub fn scale_by(self, factor: f32) -> Au {
- Au(((self.0 as f32) * factor) as i32)
- }
-
- #[inline]
- pub fn from_px(px: i32) -> Au {
- Au((px * AU_PER_PX) as i32)
- }
-
- /// 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 {
- Au((px * (AU_PER_PX as f32)) as i32)
- }
-
- #[inline]
- pub fn from_f64_px(px: f64) -> Au {
- Au((px * (AU_PER_PX as f64)) 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), MIN_AU);
-
- assert_eq!(Au(7) - Au(5), Au(2));
- assert_eq!(MIN_AU - Au(1), MAX_AU);
-
- assert_eq!(Au(7) * 5, Au(35));
- assert_eq!(MAX_AU * -1, MIN_AU + Au(1));
- assert_eq!(MIN_AU * -1, MIN_AU);
-
- assert_eq!(Au(35) / 5, Au(7));
- assert_eq!(Au(35) % 6, Au(5));
-
- assert_eq!(-Au(7), Au(-7));
-}
-
-#[test]
-#[should_panic]
-fn overflowing_div() {
- MIN_AU / -1;
-}
-
-#[test]
-#[should_panic]
-fn overflowing_rem() {
- MIN_AU % -1;
-}
-
-#[test]
-fn scale() {
- assert_eq!(Au(12).scale_by(1.5), Au(18));
-}
-
-#[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(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::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_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));
-}
-
-#[test]
-fn heapsize() {
- use heapsize::HeapSizeOf;
- fn f<T: HeapSizeOf>(_: T) {}
- f(Au::new(0));
-}
deleted file mode 100644
--- a/third_party/rust/app_units-0.3.0/src/lib.rs
+++ /dev/null
@@ -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};
--- a/third_party/rust/bincode/.cargo-checksum.json
+++ b/third_party/rust/bincode/.cargo-checksum.json
@@ -1,1 +1,1 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"e084df3ce631ce22082bd63f9e421e7f4d7a2408d6520de532f6a649e4d320dd",".travis.yml":"cb3f687453522852cb74371892a77d5e6eb61d771b8ef27f6cc6628e556de3d6","Cargo.toml":"d631ecb2eef5a18307a68e795080ed073851c9bea0800405cad98642ed3cc053","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","examples/basic.rs":"cdf97f2c4facbc202bf9e1496030d09bef3b7cd5538407325a38f0fe2e49415e","logo.png":"ebc5305aae938c1f834cf35302faa8be0f1b7b8c3c3beef5cf6b2f68b9628c35","readme.dev.md":"43bad3bcc13a5c057344d3ba7f64bd2b313f8c133d6afa068108df73e8e8facd","readme.md":"1fe1bda36327400cfedfcf103d58091c8465067b62706b0a368d287ca0312cd9","src/lib.rs":"1a85a12afad0b6150b8dbede093d19f4a32a3cd6976ee018a625fbc05051bf80","src/refbox.rs":"f0470baabbf0f9852df939c2535865793dc31c9d9d35eecf9c237a9df431a9fc","src/rustc_serialize/mod.rs":"188f5ff7fc9c5e0ac1404b919ceafac5ce4385950d22ae470ddc1775d2a0643b","src/rustc_serialize/reader.rs":"7983c37556fdef552bfeba386d557863fb5113c8fada55d4cf6a605f13214253","src/rustc_serialize/writer.rs":"684844799673fce3c54f1aca42430b6730da13473d732ee2954ebc56994ebd95","src/serde/mod.rs":"7818bbe5c320af2a15762c421d5471865a7364e1c9754c57960402fdcf09c595","src/serde/reader.rs":"1f88a55923dfc3ad82ec32571c9c7ca42818d996897966dea08a595f804d117f","src/serde/writer.rs":"d987134b3a00eb17a25e601757ad20607dd1de8989452266e9e4e7955fcd87f1","tests/test.rs":"b72a5902be11c3210dd56814276ff036155eba10d5f0aa566c86e7a1ce463adf"},"package":"55eb0b7fd108527b0c77860f75eca70214e11a8b4c6ef05148c54c05a25d48ad"}
\ No newline at end of file
+{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"e084df3ce631ce22082bd63f9e421e7f4d7a2408d6520de532f6a649e4d320dd",".travis.yml":"f705a11b487bf71c41ebd8223cc1f3cbde0dfdfeea96a100af55e06e93397a1b","Cargo.toml":"c1d0f68b42bff71b04c8e763f13b0141f30dc849bee5b0ab5b9008e3627aac99","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","changelist.org":"90bb4036f90c3792c8294de2e3d52a54cc6230c3e5dc78013a781a9aa468f5f3","examples/basic.rs":"57aeca11d5cc5c3d5bb613e78b2ea43a2e80d66c15a2fffae303b165aa4ab41d","logo.png":"ebc5305aae938c1f834cf35302faa8be0f1b7b8c3c3beef5cf6b2f68b9628c35","readme.dev.md":"43bad3bcc13a5c057344d3ba7f64bd2b313f8c133d6afa068108df73e8e8facd","readme.md":"1fe1bda36327400cfedfcf103d58091c8465067b62706b0a368d287ca0312cd9","src/lib.rs":"04d6e4533f4bbb2ce2126bca414f95610075642b223f4e0c0b8f7a573792d7fd","src/refbox.rs":"fe266cec4f9f36942a1a9a9ad094a4bb1003d0c0f3c070cfb6214790d0f21b69","src/serde/mod.rs":"ef0c0a55936d835ae756d84a6ac38de312687d7c0f2cfc6810ec994413464516","src/serde/reader.rs":"6bfde2e2df9b450f6c07576198e47fdc837bbc4ddc74f447c72875c188c72ddc","src/serde/writer.rs":"eb3b439e8822871d715464ef6aca4b93a73b2b57625f9c586b68007f7386ab12","tests/test.rs":"f009e979fda892ad531ddd0f2003f0a7df607b19bd453a53f87c9041dfd9c745"},"package":"62650bb5651ba8f0580cebf4ef255d791b8b0ef53800322661e1bb5791d42966"}
\ No newline at end of file
--- a/third_party/rust/bincode/.travis.yml
+++ b/third_party/rust/bincode/.travis.yml
@@ -1,29 +1,5 @@
-lang: c
-after_success: |
- [ $TRAVIS_BRANCH = master ] &&
- [ $TRAVIS_PULL_REQUEST = false ] &&
- cargo doc &&
- echo "<meta http-equiv=refresh content=0;url=`echo $TRAVIS_REPO_SLUG | cut -d '/' -f 2`/index.html>" > target/doc/index.html &&
- sudo pip install ghp-import &&
- ghp-import -n target/doc &&
- git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
-
-env:
- matrix:
- - CHANNEL='stable'
- - CHANNEL='beta'
- - CHANNEL='nightly'
- global:
- - secure: SZSxNqg9wiGx8EnJhifJ2kb/aCRcLim9TzTQyfurPqd8qVGkDOeVjTtbs+VTxLVXYtMJAz+YYnrQDwsu8kc/uYpQajU+gRMqNGEP5gNj3Ha5iNGDasAS6piIHQSMROayZ+D9g22nlGnjk8t9eZtLHC/Z8IWMCnjcIHvqMFY6cgI=
-
-install:
- - curl -sf https://raw.githubusercontent.com/brson/multirust/master/blastoff.sh > ./rustup.sh
- - chmod +x ./rustup.sh
- - ./rustup.sh --yes
-
-script:
- - multirust default $CHANNEL
- - cargo build
- - cargo build --no-default-features --features "rustc-serialize"
- - cargo build --no-default-features --features "serde"
- - if [ $CHANNEL = 'nightly' ] ; then cargo test ; fi
+language: rust
+rust:
+ - stable
+ - beta
+ - nightly
--- a/third_party/rust/bincode/Cargo.toml
+++ b/third_party/rust/bincode/Cargo.toml
@@ -1,29 +1,21 @@
[package]
name = "bincode"
-version = "0.6.1"
-authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>"]
+version = "1.0.0-alpha2"
+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"
-documentation = "http://tyoverby.github.io/bincode/bincode/"
+documentation = "https://docs.rs/bincode"
keywords = ["binary", "encode", "decode", "serialize", "deserialize"]
license = "MIT"
-description = "A binary serialization / deserialization strategy and implementation with serde and rustc-serialize backends."
+description = "A binary serialization / deserialization strategy that uses Serde for transforming structs into bytes and vice versa!"
[dependencies]
byteorder = "1.0.0"
num-traits = "0.1.32"
-[dependencies.rustc-serialize]
-version = "0.3.*"
-optional = true
-
[dependencies.serde]
-version = "0.8.*"
-optional = true
+version = "0.9.*"
[dev-dependencies]
-serde_derive = "0.8.*"
-
-[features]
-default = ["rustc-serialize", "serde"]
+serde_derive = "0.9.*"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bincode/changelist.org
@@ -0,0 +1,18 @@
+* 1.0.0
+** Removed depricated rustc-serialize support
+ Rustc-serialize was a stopgap until projects like Serde were able to catch up.
+ With macros stabilization on its way, we are able to switch to serde without any
+ big user-friendliness issues. Major congratulations to Serde for coming this far!
+
+** Moved Refbox, Strbox and Slicebox into a "refbox" module
+ Refbox, Strbox and Slicebox are still an integral piece of bincode, but since
+ they are mainly used by power-users, this move will make the crate API more organized
+ and easier for new users to understand.
+
+** Upgraded to Serde 0.9.*
+ Serde 0.9.* gives us a better API surface area and allows use of procedural macros for
+ deriving serialize and deserialize implemenetations.
+
+** Moved serde functions into global module
+ Since serde is the only supported serialization mechanism, it makes sense to have these
+ functions available at the top level.
--- a/third_party/rust/bincode/examples/basic.rs
+++ b/third_party/rust/bincode/examples/basic.rs
@@ -1,10 +1,11 @@
+/*
extern crate bincode;
-extern crate rustc_serialize;
+extern crate
use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, decode};
#[derive(RustcEncodable, RustcDecodable, PartialEq)]
struct Entity {
x: f32,
y: f32,
@@ -24,8 +25,11 @@ fn main() {
// 8 bytes for the length of the vector, 4 bytes per float.
assert_eq!(encoded.len(), 8 + 4 * 4);
let decoded: World = decode(&encoded[..]).unwrap();
assert!(world == decoded);
}
+ */
+
+fn main() {}
--- a/third_party/rust/bincode/src/lib.rs
+++ b/third_party/rust/bincode/src/lib.rs
@@ -11,52 +11,44 @@
//! 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`.
//!
//! ### Using Basic Functions
//!
//! ```rust
-//! #![allow(unstable)]
//! extern crate bincode;
-//! use bincode::rustc_serialize::{encode, decode};
+//! use bincode::{serialize, deserialize};
//! fn main() {
//! // The object that we will serialize.
//! let target = Some("hello world".to_string());
//! // The maximum size of the encoded message.
//! let limit = bincode::SizeLimit::Bounded(20);
//!
-//! let encoded: Vec<u8> = encode(&target, limit).unwrap();
-//! let decoded: Option<String> = decode(&encoded[..]).unwrap();
+//! let encoded: Vec<u8> = serialize(&target, limit).unwrap();
+//! let decoded: Option<String> = deserialize(&encoded[..]).unwrap();
//! assert_eq!(target, decoded);
//! }
//! ```
#![crate_name = "bincode"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "./icon.png")]
-#[cfg(feature = "rustc-serialize")]
-extern crate rustc_serialize as rustc_serialize_crate;
extern crate byteorder;
extern crate num_traits;
-#[cfg(feature = "serde")]
extern crate serde as serde_crate;
-
-pub use refbox::{RefBox, StrBox, SliceBox};
+pub mod refbox;
+mod serde;
-mod refbox;
-#[cfg(feature = "rustc-serialize")]
-pub mod rustc_serialize;
-#[cfg(feature = "serde")]
-pub mod serde;
+pub use serde::*;
/// A limit on the amount of bytes that can be read or written.
///
/// Size limits are an incredibly important part of both encoding and decoding.
///
/// In order to prevent DOS attacks on a decoder, it is important to limit the
/// amount of bytes that a single encoded message can be; otherwise, if you
/// are decoding bytes right off of a TCP stream for example, it would be
@@ -71,9 +63,8 @@ pub mod serde;
/// encoding function, the encoder will verify that the structure can be encoded
/// within that limit. This verification occurs before any bytes are written to
/// the Writer, so recovering from an error is easy.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum SizeLimit {
Infinite,
Bounded(u64)
}
-
--- a/third_party/rust/bincode/src/refbox.rs
+++ b/third_party/rust/bincode/src/refbox.rs
@@ -1,15 +1,11 @@
use std::boxed::Box;
use std::ops::Deref;
-#[cfg(feature = "rustc-serialize")]
-use rustc_serialize_crate::{Encodable, Encoder, Decodable, Decoder};
-
-#[cfg(feature = "serde")]
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.
@@ -136,45 +132,28 @@ impl <T> RefBox<'static, T> {
pub fn try_take(self) -> Result<Box<T>, RefBox<'static, T>> {
match self.inner {
RefBoxInner::Box(b) => Ok(b),
o => Err(RefBox{ inner: o})
}
}
}
-#[cfg(feature = "rustc-serialize")]
-impl <'a, T: Encodable> Encodable for RefBox<'a, T> {
- fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- self.inner.encode(s)
- }
-}
-
-#[cfg(feature = "rustc-serialize")]
-impl <T: Decodable> Decodable for RefBox<'static, T> {
- fn decode<D: Decoder>(d: &mut D) -> Result<RefBox<'static, T>, D::Error> {
- let inner = try!(Decodable::decode(d));
- Ok(RefBox{inner: inner})
- }
-}
-
-#[cfg(feature = "serde")]
impl<'a, T> serde::Serialize for RefBox<'a, T>
where T: serde::Serialize,
{
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer
{
serde::Serialize::serialize(&self.inner, serializer)
}
}
-#[cfg(feature = "serde")]
impl<'a, T: serde::Deserialize> serde::Deserialize for RefBox<'a, T> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ 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> {
@@ -234,43 +213,27 @@ impl StrBox<'static> {
pub fn try_take(self) -> Result<String, StrBox<'static>> {
match self.inner {
RefBoxInner::Box(b) => Ok(b),
o => Err(StrBox{ inner: o})
}
}
}
-#[cfg(feature = "rustc-serialize")]
-impl <'a> Encodable for StrBox<'a> {
- fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- self.inner.encode(s)
- }
-}
-#[cfg(feature = "rustc-serialize")]
-impl Decodable for StrBox<'static> {
- fn decode<D: Decoder>(d: &mut D) -> Result<StrBox<'static>, D::Error> {
- let inner: RefBoxInner<'static, str, String> = try!(Decodable::decode(d));
- Ok(StrBox{inner: inner})
- }
-}
-
-#[cfg(feature = "serde")]
impl<'a> serde::Serialize for StrBox<'a> {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer
{
serde::Serialize::serialize(&self.inner, serializer)
}
}
-#[cfg(feature = "serde")]
impl serde::Deserialize for StrBox<'static> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::Deserializer
{
let inner = try!(serde::Deserialize::deserialize(deserializer));
Ok(StrBox{ inner: inner })
}
}
//
@@ -325,90 +288,56 @@ impl <T> SliceBox<'static, T> {
pub fn try_take(self) -> Result<Vec<T>, SliceBox<'static, T>> {
match self.inner {
RefBoxInner::Box(b) => Ok(b),
o => Err(SliceBox{ inner: o})
}
}
}
-#[cfg(feature = "rustc-serialize")]
-impl <'a, T: Encodable> Encodable for SliceBox<'a, T> {
- fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- self.inner.encode(s)
- }
-}
-#[cfg(feature = "rustc-serialize")]
-impl <T: Decodable> Decodable for SliceBox<'static, T> {
- fn decode<D: Decoder>(d: &mut D) -> Result<SliceBox<'static, T>, D::Error> {
- let inner: RefBoxInner<'static, [T], Vec<T>> = try!(Decodable::decode(d));
- Ok(SliceBox{inner: inner})
- }
-}
-
-#[cfg(feature = "serde")]
impl<'a, T> serde::Serialize for SliceBox<'a, T>
where T: serde::Serialize,
{
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer
{
serde::Serialize::serialize(&self.inner, serializer)
}
}
-#[cfg(feature = "serde")]
impl<'a, T: serde::Deserialize> serde::Deserialize for SliceBox<'a, T> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::Deserializer
{
let inner = try!(serde::Deserialize::deserialize(deserializer));
Ok(SliceBox{ inner: inner })
}
}
-#[cfg(feature = "rustc-serialize")]
-impl <'a, A: Encodable + ?Sized, B: Encodable> Encodable for RefBoxInner<'a, A, B> {
- fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- match self {
- &RefBoxInner::Ref(ref r) => r.encode(s),
- &RefBoxInner::Box(ref b) => b.encode(s)
- }
- }
-}
-#[cfg(feature = "serde")]
impl<'a, A: ?Sized, B> serde::Serialize for RefBoxInner<'a, A, B>
where A: serde::Serialize,
B: serde::Serialize,
{
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ 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),
}
}
}
-#[cfg(feature = "rustc-serialize")]
-impl <A: ?Sized, B: Decodable> Decodable for RefBoxInner<'static, A, B> {
- fn decode<D: Decoder>(d: &mut D) -> Result<RefBoxInner<'static, A, B>, D::Error> {
- let decoded = try!(Decodable::decode(d));
- Ok(RefBoxInner::Box(decoded))
- }
-}
-#[cfg(feature = "serde")]
impl<'a, A: ?Sized, B> serde::Deserialize for RefBoxInner<'a, A, B>
where B: serde::Deserialize,
{
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ 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> {
deleted file mode 100644
--- a/third_party/rust/bincode/src/rustc_serialize/mod.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-//! A collection of serialization and deserialization functions
-//! that use the `rustc_serialize` crate for the encodable and decodable
-//! implementation.
-
-use rustc_serialize_crate::{Encodable, Decodable};
-use std::io::{Write, Read};
-use ::SizeLimit;
-
-pub use self::writer::{SizeChecker, EncoderWriter, EncodingResult, EncodingError};
-pub use self::reader::{DecoderReader, DecodingResult, DecodingError, InvalidEncoding};
-
-mod reader;
-mod writer;
-
-/// Encodes an encodable object into a `Vec` of bytes.
-///
-/// If the encoding would take more bytes than allowed by `size_limit`,
-/// an error is returned.
-pub fn encode<T: Encodable>(t: &T, size_limit: SizeLimit) -> EncodingResult<Vec<u8>> {
- // 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 w = if let SizeLimit::Bounded(l) = size_limit {
- let actual_size = encoded_size_bounded(t, l);
- let actual_size = try!(actual_size.ok_or(EncodingError::SizeLimit));
- Vec::with_capacity(actual_size as usize)
- } else {
- vec![]
- };
-
- match encode_into(t, &mut w, SizeLimit::Infinite) {
- Ok(()) => Ok(w),
- Err(e) => Err(e)
- }
-}
-
-/// Decodes 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 decode<T: Decodable>(b: &[u8]) -> DecodingResult<T> {
- let mut b = b;
- decode_from(&mut b, SizeLimit::Infinite)
-}
-
-/// Encodes an object directly into a `Writer`.
-///
-/// If the encoding would take more bytes than allowed by `size_limit`, an error
-/// is returned and *no bytes* will be written into the `Writer`.
-///
-/// If this returns an `EncodingError` (other than SizeLimit), assume that the
-/// writer is in an invalid state, as writing could bail out in the middle of
-/// encoding.
-pub fn encode_into<T: Encodable, W: Write>(t: &T,
- w: &mut W,
- size_limit: SizeLimit)
- -> EncodingResult<()> {
- try!(match size_limit {
- SizeLimit::Infinite => Ok(()),
- SizeLimit::Bounded(x) => {
- let mut size_checker = SizeChecker::new(x);
- t.encode(&mut size_checker)
- }
- });
-
- t.encode(&mut writer::EncoderWriter::new(w))
-}
-
-/// Decoes an object directly from a `Buffer`ed Reader.
-///
-/// If the provided `SizeLimit` is reached, the decode will bail immediately.
-/// A SizeLimit can help prevent an attacker from flooding your server with
-/// a neverending stream of values that runs your server out of memory.
-///
-/// If this returns an `DecodingError`, 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 decode_from<R: Read, T: Decodable>(r: &mut R, size_limit: SizeLimit) -> DecodingResult<T> {
- Decodable::decode(&mut reader::DecoderReader::new(r, size_limit))
-}
-
-
-/// Returns the size that an object would be if encoded using bincode.
-///
-/// This is used internally as part of the check for encode_into, but it can
-/// be useful for preallocating buffers if thats your style.
-pub fn encoded_size<T: Encodable>(t: &T) -> u64 {
- use std::u64::MAX;
- let mut size_checker = SizeChecker::new(MAX);
- t.encode(&mut size_checker).ok();
- size_checker.written
-}
-
-/// Given a maximum size limit, check how large an object would be if it
-/// were to be encoded.
-///
-/// If it can be encoded in `max` or fewer bytes, that number will be returned
-/// inside `Some`. If it goes over bounds, then None is returned.
-pub fn encoded_size_bounded<T: Encodable>(t: &T, max: u64) -> Option<u64> {
- let mut size_checker = SizeChecker::new(max);
- t.encode(&mut size_checker).ok().map(|_| size_checker.written)
-}
deleted file mode 100644
--- a/third_party/rust/bincode/src/rustc_serialize/reader.rs
+++ /dev/null
@@ -1,392 +0,0 @@
-use std::io::Read;
-use std::io::Error as IoError;
-use std::error::Error;
-use std::fmt;
-use std::convert::From;
-
-use rustc_serialize_crate::Decoder;
-
-use byteorder::{BigEndian, ReadBytesExt};
-use ::SizeLimit;
-
-#[derive(Eq, PartialEq, Clone, Debug)]
-pub struct InvalidEncoding {
- pub desc: &'static str,
- pub detail: Option<String>,
-}
-
-impl fmt::Display for InvalidEncoding {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- InvalidEncoding { detail: None, desc } =>
- write!(fmt, "{}", desc),
- InvalidEncoding { detail: Some(ref detail), desc } =>
- write!(fmt, "{} ({})", desc, detail)
- }
- }
-}
-
-/// An error that can be produced during decoding.
-///
-/// If decoding from a Buffer, assume that the buffer has been left
-/// in an invalid state.
-#[derive(Debug)]
-pub enum DecodingError {
- /// If the error stems from the reader that is being used
- /// during decoding, that error will be stored and returned here.
- IoError(IoError),
- /// If the bytes in the reader are not decodable because of an invalid
- /// 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(InvalidEncoding),
- /// If decoding a message takes more than the provided size limit, this
- /// error is returned.
- SizeLimit
-}
-
-impl fmt::Display for DecodingError {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- DecodingError::IoError(ref ioerr) =>
- write!(fmt, "IoError: {}", ioerr),
- DecodingError::InvalidEncoding(ref ib) =>
- write!(fmt, "InvalidEncoding: {}", ib),
- DecodingError::SizeLimit =>
- write!(fmt, "SizeLimit")
- }
- }
-}
-
-pub type DecodingResult<T> = Result<T, DecodingError>;
-
-fn wrap_io(err: IoError) -> DecodingError {
- DecodingError::IoError(err)
-}
-
-impl Error for DecodingError {
- fn description(&self) -> &str {
- match *self {
- DecodingError::IoError(ref err) => Error::description(err),
- DecodingError::InvalidEncoding(ref ib) => ib.desc,
- DecodingError::SizeLimit => "the size limit for decoding has been reached"
- }
- }
-
- fn cause(&self) -> Option<&Error> {
- match *self {
- DecodingError::IoError(ref err) => err.cause(),
- DecodingError::InvalidEncoding(_) => None,
- DecodingError::SizeLimit => None
- }
- }
-}
-
-impl From<IoError> for DecodingError {
- fn from(err: IoError) -> DecodingError {
- DecodingError::IoError(err)
- }
-}
-
-/// A Decoder that reads bytes from a buffer.
-///
-/// This struct should rarely be used.
-/// In most cases, prefer the `decode_from` function.
-///
-/// ```rust,ignore
-/// let dr = bincode::rustc_serialize::DecoderReader::new(&mut some_reader, SizeLimit::Infinite);
-/// let result: T = Decodable::decode(&mut dr);
-/// let bytes_read = dr.bytes_read();
-/// ```
-pub struct DecoderReader<'a, R: 'a> {
- reader: &'a mut R,
- size_limit: SizeLimit,
- read: u64
-}
-
-impl<'a, R: Read> DecoderReader<'a, R> {
- pub fn new(r: &'a mut R, size_limit: SizeLimit) -> DecoderReader<'a, R> {
- DecoderReader {
- reader: r,
- size_limit: size_limit,
- read: 0
- }
- }
-
- /// Returns the number of bytes read from the contained Reader.
- pub fn bytes_read(&self) -> u64 {
- self.read
- }
-}
-
-impl <'a, A> DecoderReader<'a, A> {
- fn read_bytes(&mut self, count: u64) -> Result<(), DecodingError> {
- self.read = match self.read.checked_add(count) {
- Some(read) => read,
- None => return Err(DecodingError::SizeLimit),
- };
- match self.size_limit {
- SizeLimit::Infinite => Ok(()),
- SizeLimit::Bounded(x) if self.read <= x => Ok(()),
- SizeLimit::Bounded(_) => Err(DecodingError::SizeLimit)
- }
- }
-
- fn read_type<T>(&mut self) -> Result<(), DecodingError> {
- use std::mem::size_of;
- self.read_bytes(size_of::<T>() as u64)
- }
-}
-
-impl<'a, R: Read> Decoder for DecoderReader<'a, R> {
- type Error = DecodingError;
-
- fn read_nil(&mut self) -> DecodingResult<()> {
- Ok(())
- }
- fn read_usize(&mut self) -> DecodingResult<usize> {
- Ok(try!(self.read_u64().map(|x| x as usize)))
- }
- fn read_u64(&mut self) -> DecodingResult<u64> {
- try!(self.read_type::<u64>());
- self.reader.read_u64::<BigEndian>().map_err(wrap_io)
- }
- fn read_u32(&mut self) -> DecodingResult<u32> {
- try!(self.read_type::<u32>());
- self.reader.read_u32::<BigEndian>().map_err(wrap_io)
- }
- fn read_u16(&mut self) -> DecodingResult<u16> {
- try!(self.read_type::<u16>());
- self.reader.read_u16::<BigEndian>().map_err(wrap_io)
- }
- fn read_u8(&mut self) -> DecodingResult<u8> {
- try!(self.read_type::<u8>());
- self.reader.read_u8().map_err(wrap_io)
- }
- fn read_isize(&mut self) -> DecodingResult<isize> {
- self.read_i64().map(|x| x as isize)
- }
- fn read_i64(&mut self) -> DecodingResult<i64> {
- try!(self.read_type::<i64>());
- self.reader.read_i64::<BigEndian>().map_err(wrap_io)
- }
- fn read_i32(&mut self) -> DecodingResult<i32> {
- try!(self.read_type::<i32>());
- self.reader.read_i32::<BigEndian>().map_err(wrap_io)
- }
- fn read_i16(&mut self) -> DecodingResult<i16> {
- try!(self.read_type::<i16>());
- self.reader.read_i16::<BigEndian>().map_err(wrap_io)
- }
- fn read_i8(&mut self) -> DecodingResult<i8> {
- try!(self.read_type::<i8>());
- self.reader.read_i8().map_err(wrap_io)
- }
- fn read_bool(&mut self) -> DecodingResult<bool> {
- let x = try!(self.read_i8());
- match x {
- 1 => Ok(true),
- 0 => Ok(false),
- _ => Err(DecodingError::InvalidEncoding(InvalidEncoding{
- desc: "invalid u8 when decoding bool",
- detail: Some(format!("Expected 0 or 1, got {}", x))
- })),
- }
- }
- fn read_f64(&mut self) -> DecodingResult<f64> {
- try!(self.read_type::<f64>());
- self.reader.read_f64::<BigEndian>().map_err(wrap_io)
- }
- fn read_f32(&mut self) -> DecodingResult<f32> {
- try!(self.read_type::<f32>());
- self.reader.read_f32::<BigEndian>().map_err(wrap_io)
- }
- fn read_char(&mut self) -> DecodingResult<char> {
- use std::str;
-
- let error = DecodingError::InvalidEncoding(InvalidEncoding {
- desc: "Invalid char encoding",
- detail: None
- });
-
- let mut buf = [0];
-
- let _ = try!(self.reader.read(&mut buf[..]));
- let first_byte = buf[0];
- let width = utf8_char_width(first_byte);
- if width == 1 { return Ok(first_byte as char) }
- if width == 0 { return Err(error)}
-
- let mut buf = [first_byte, 0, 0, 0];
- {
- let mut start = 1;
- while start < width {
- match try!(self.reader.read(&mut buf[start .. width])) {
- n if n == width - start => break,
- n if n < width - start => { start += n; }
- _ => return Err(error)
- }
- }
- }
-
- let res = try!(match str::from_utf8(&buf[..width]).ok() {
- Some(s) => Ok(s.chars().next().unwrap()),
- None => Err(error)
- });
-
- try!(self.read_bytes(res.len_utf8() as u64));
- Ok(res)
- }
-
- fn read_str(&mut self) -> DecodingResult<String> {
- let len = try!(self.read_usize());
- try!(self.read_bytes(len as u64));
-
- let mut buff = Vec::new();
- try!(self.reader.by_ref().take(len as u64).read_to_end(&mut buff));
- match String::from_utf8(buff) {
- Ok(s) => Ok(s),
- Err(err) => Err(DecodingError::InvalidEncoding(InvalidEncoding {
- desc: "error while decoding utf8 string",
- detail: Some(format!("Decoding error: {}", err))
- })),
- }
- }
- fn read_enum<T, F>(&mut self, _: &str, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodingResult<T>
- where F: FnMut(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
- {
- let id = try!(self.read_u32());
- let id = id as usize;
- if id >= names.len() {
- Err(DecodingError::InvalidEncoding(InvalidEncoding {
- desc: "out of bounds tag when reading enum variant",
- detail: Some(format!("Expected tag < {}, got {}", names.len(), id))
- }))
- } else {
- f(self, id)
- }
- }
- fn read_enum_variant_arg<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodingResult<T>
- where F: FnMut(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
- {
- self.read_enum_variant(names, f)
- }
- fn read_enum_struct_variant_field<T, F>(&mut self,
- _: &str,
- f_idx: usize,
- f: F)
- -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- self.read_enum_variant_arg(f_idx, f)
- }
- fn read_struct<T, F>(&mut self, _: &str, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_struct_field<T, F>(&mut self, _: &str, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_tuple<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_tuple_arg<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_tuple_struct<T, F>(&mut self, _: &str, len: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- self.read_tuple(len, f)
- }
- fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- self.read_tuple_arg(a_idx, f)
- }
- fn read_option<T, F>(&mut self, mut f: F) -> DecodingResult<T>
- where F: FnMut(&mut DecoderReader<'a, R>, bool) -> DecodingResult<T>
- {
- let x = try!(self.read_u8());
- match x {
- 1 => f(self, true),
- 0 => f(self, false),
- _ => Err(DecodingError::InvalidEncoding(InvalidEncoding {
- desc: "invalid tag when decoding Option",
- detail: Some(format!("Expected 0 or 1, got {}", x))
- })),
- }
- }
- fn read_seq<T, F>(&mut self, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
- {
- let len = try!(self.read_usize());
- f(self, len)
- }
- fn read_seq_elt<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_map<T, F>(&mut self, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
- {
- let len = try!(self.read_usize());
- f(self, len)
- }
- fn read_map_elt_key<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn read_map_elt_val<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
- where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
- {
- f(self)
- }
- fn error(&mut self, err: &str) -> DecodingError {
- DecodingError::InvalidEncoding(InvalidEncoding {
- desc: "user-induced error",
- detail: Some(err.to_string()),
- })
- }
-}
-
-static UTF8_CHAR_WIDTH: [u8; 256] = [
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
-0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
-2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
-4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
-];
-
-fn utf8_char_width(b: u8) -> usize {
- UTF8_CHAR_WIDTH[b as usize] as usize
-}
deleted file mode 100644
--- a/third_party/rust/bincode/src/rustc_serialize/writer.rs
+++ /dev/null
@@ -1,422 +0,0 @@
-use std::io::Write;
-use std::io::Error as IoError;
-use std::error::Error;
-use std::fmt;
-
-use rustc_serialize_crate::Encoder;
-
-use byteorder::{BigEndian, WriteBytesExt};
-
-pub type EncodingResult<T> = Result<T, EncodingError>;
-
-
-/// An error that can be produced during encoding.
-#[derive(Debug)]
-pub enum EncodingError {
- /// An error originating from the underlying `Writer`.
- IoError(IoError),
- /// An object could not be encoded with the given size limit.
- ///
- /// This error is returned before any bytes are written to the
- /// output `Writer`.
- SizeLimit,
-}
-
-/// An Encoder that encodes values directly into a Writer.
-///
-/// This struct should not be used often.
-/// For most cases, prefer the `encode_into` function.
-pub struct EncoderWriter<'a, W: 'a> {
- writer: &'a mut W,
-}
-
-pub struct SizeChecker {
- pub size_limit: u64,
- pub written: u64
-}
-
-fn wrap_io(err: IoError) -> EncodingError {
- EncodingError::IoError(err)
-}
-
-impl fmt::Display for EncodingError {
- fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- match *self {
- EncodingError::IoError(ref err) => write!(f, "IoError: {}", err),
- EncodingError::SizeLimit => write!(f, "SizeLimit")
- }
- }
-}
-
-impl Error for EncodingError {
- fn description(&self) -> &str {
- match *self {
- EncodingError::IoError(ref err) => Error::description(err),
- EncodingError::SizeLimit => "the size limit for decoding has been reached"
- }
- }
-
- fn cause(&self) -> Option<&Error> {
- match *self {
- EncodingError::IoError(ref err) => err.cause(),
- EncodingError::SizeLimit => None
- }
- }
-}
-
-impl <'a, W: Write> EncoderWriter<'a, W> {
- pub fn new(w: &'a mut W) -> EncoderWriter<'a, W> {
- EncoderWriter {
- writer: w,
- }
- }
-}
-
-impl SizeChecker {
- pub fn new(limit: u64) -> SizeChecker {
- SizeChecker {
- size_limit: limit,
- written: 0
- }
- }
-
- fn add_raw(&mut self, size: usize) -> EncodingResult<()> {
- self.written += size as u64;
- if self.written <= self.size_limit {
- Ok(())
- } else {
- Err(EncodingError::SizeLimit)
- }
- }
-
- fn add_value<T>(&mut self, t: T) -> EncodingResult<()> {
- use std::mem::size_of_val;
- self.add_raw(size_of_val(&t))
- }
-}
-
-impl<'a, W: Write> Encoder for EncoderWriter<'a, W> {
- type Error = EncodingError;
-
- fn emit_nil(&mut self) -> EncodingResult<()> {
- Ok(())
- }
- fn emit_usize(&mut self, v: usize) -> EncodingResult<()> {
- self.emit_u64(v as u64)
- }
- fn emit_u64(&mut self, v: u64) -> EncodingResult<()> {
- self.writer.write_u64::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_u32(&mut self, v: u32) -> EncodingResult<()> {
- self.writer.write_u32::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_u16(&mut self, v: u16) -> EncodingResult<()> {
- self.writer.write_u16::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_u8(&mut self, v: u8) -> EncodingResult<()> {
- self.writer.write_u8(v).map_err(wrap_io)
- }
- fn emit_isize(&mut self, v: isize) -> EncodingResult<()> {
- self.emit_i64(v as i64)
- }
- fn emit_i64(&mut self, v: i64) -> EncodingResult<()> {
- self.writer.write_i64::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_i32(&mut self, v: i32) -> EncodingResult<()> {
- self.writer.write_i32::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_i16(&mut self, v: i16) -> EncodingResult<()> {
- self.writer.write_i16::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_i8(&mut self, v: i8) -> EncodingResult<()> {
- self.writer.write_i8(v).map_err(wrap_io)
- }
- fn emit_bool(&mut self, v: bool) -> EncodingResult<()> {
- self.writer.write_u8(if v {1} else {0}).map_err(wrap_io)
- }
- fn emit_f64(&mut self, v: f64) -> EncodingResult<()> {
- self.writer.write_f64::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_f32(&mut self, v: f32) -> EncodingResult<()> {
- self.writer.write_f32::<BigEndian>(v).map_err(wrap_io)
- }
- fn emit_char(&mut self, v: char) -> EncodingResult<()> {
- // TODO: change this back once unicode works
- //let mut cbuf = [0; 4];
- //let sz = v.encode_utf8(&mut cbuf[..]).unwrap_or(0);
- //let ptr = &cbuf[..sz];
- //self.writer.write_all(ptr).map_err(EncodingError::IoError)
-
- let mut inter = String::with_capacity(1);
- inter.push(v);
- self.writer.write_all(inter.as_bytes()).map_err(EncodingError::IoError)
- }
- fn emit_str(&mut self, v: &str) -> EncodingResult<()> {
- try!(self.emit_usize(v.len()));
- self.writer.write_all(v.as_bytes()).map_err(EncodingError::IoError)
- }
- fn emit_enum<F>(&mut self, __: &str, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_enum_variant<F>(&mut self, _: &str, v_id: usize, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- let max_u32: u32 = ::std::u32::MAX;
- if v_id > (max_u32 as usize) {
- panic!("Variant tag doesn't fit in a u32")
- }
- try!(self.emit_u32(v_id as u32));
- f(self)
- }
- fn emit_enum_variant_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_enum_struct_variant<F>(&mut self,
- v_name: &str,
- v_id: usize,
- len: usize,
- f: F)
- -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- self.emit_enum_variant(v_name, v_id, len, f)
- }
- fn emit_enum_struct_variant_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_struct_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_tuple<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_tuple_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- self.emit_tuple(len, f)
- }
- fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- self.emit_tuple_arg(f_idx, f)
- }
- fn emit_option<F>(&mut self, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_option_none(&mut self) -> EncodingResult<()> {
- self.writer.write_u8(0).map_err(wrap_io)
- }
- fn emit_option_some<F>(&mut self, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- try!(self.writer.write_u8(1).map_err(wrap_io));
- f(self)
- }
- fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- try!(self.emit_usize(len));
- f(self)
- }
- fn emit_seq_elt<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_map<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- try!(self.emit_usize(len));
- f(self)
- }
- fn emit_map_elt_key<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_map_elt_val<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
- {
- f(self)
- }
-
-}
-
-impl Encoder for SizeChecker {
- type Error = EncodingError;
-
- fn emit_nil(&mut self) -> EncodingResult<()> {
- Ok(())
- }
- fn emit_usize(&mut self, v: usize) -> EncodingResult<()> {
- self.add_value(v as u64)
- }
- fn emit_u64(&mut self, v: u64) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_u32(&mut self, v: u32) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_u16(&mut self, v: u16) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_u8(&mut self, v: u8) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_isize(&mut self, v: isize) -> EncodingResult<()> {
- self.add_value(v as i64)
- }
- fn emit_i64(&mut self, v: i64) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_i32(&mut self, v: i32) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_i16(&mut self, v: i16) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_i8(&mut self, v: i8) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_bool(&mut self, _: bool) -> EncodingResult<()> {
- self.add_value(0 as u8)
- }
- fn emit_f64(&mut self, v: f64) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_f32(&mut self, v: f32) -> EncodingResult<()> {
- self.add_value(v)
- }
- fn emit_char(&mut self, v: char) -> EncodingResult<()> {
- self.add_raw(v.len_utf8())
- }
- fn emit_str(&mut self, v: &str) -> EncodingResult<()> {
- try!(self.add_value(0 as u64));
- self.add_raw(v.len())
- }
- fn emit_enum<F>(&mut self, __: &str, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_enum_variant<F>(&mut self, _: &str, v_id: usize, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- try!(self.add_value(v_id as u32));
- f(self)
- }
- fn emit_enum_variant_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_enum_struct_variant<F>(&mut self,
- _: &str,
- _: usize,
- _: usize,
- f: F)
- -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_enum_struct_variant_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_struct_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_tuple<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_tuple_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- self.emit_tuple(len, f)
- }
- fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- self.emit_tuple_arg(f_idx, f)
- }
- fn emit_option<F>(&mut self, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_option_none(&mut self) -> EncodingResult<()> {
- self.add_value(0 as u8)
- }
- fn emit_option_some<F>(&mut self, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- try!(self.add_value(1 as u8));
- f(self)
- }
- fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- try!(self.emit_usize(len));
- f(self)
- }
- fn emit_seq_elt<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_map<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- try!(self.emit_usize(len));
- f(self)
- }
- fn emit_map_elt_key<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
- fn emit_map_elt_val<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
- where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
- {
- f(self)
- }
-
-}
--- a/third_party/rust/bincode/src/serde/mod.rs
+++ b/third_party/rust/bincode/src/serde/mod.rs
@@ -1,45 +1,131 @@
//! A collection of serialization and deserialization functions
//! that use the `serde` crate for the serializable and deserializable
//! implementation.
use std::io::{Write, Read};
+use std::io::Error as IoError;
+use std::{error, fmt, result};
use ::SizeLimit;
pub use self::reader::{
Deserializer,
- DeserializeResult,
- DeserializeError,
- InvalidEncoding
};
pub use self::writer::{
Serializer,
- SerializeResult,
- SerializeError,
};
use self::writer::SizeChecker;
use serde_crate as serde;
mod reader;
mod writer;
+pub type Result<T> = result::Result<T, Error>;
+
+/// An error that can be produced during (de)serializing.
+///
+/// If decoding from a Buffer, assume that the buffer has been left
+/// in an invalid state.
+pub type Error = Box<ErrorKind>;
+
+#[derive(Debug)]
+pub enum ErrorKind {
+ /// If the error stems from the reader/writer that is being used
+ /// during (de)serialization, that error will be stored and returned here.
+ IoError(IoError),
+ /// If the bytes in the reader are not decodable because of an invalid
+ /// 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,
+ detail: Option<String>
+ },
+ /// If (de)serializing a message takes more than the provided size limit, this
+ /// error is returned.
+ SizeLimit,
+ SequenceMustHaveLength,
+ Custom(String)
+}
+
+impl error::Error for ErrorKind {
+ fn description(&self) -> &str {
+ match *self {
+ ErrorKind::IoError(ref err) => error::Error::description(err),
+ ErrorKind::InvalidEncoding{desc, ..} => desc,
+ ErrorKind::SequenceMustHaveLength => "bincode can't encode infinite sequences",
+ ErrorKind::SizeLimit => "the size limit for decoding has been reached",
+ ErrorKind::Custom(ref msg) => msg,
+
+ }
+ }
+
+ fn cause(&self) -> Option<&error::Error> {
+ match *self {
+ ErrorKind::IoError(ref err) => err.cause(),
+ ErrorKind::InvalidEncoding{..} => None,
+ ErrorKind::SequenceMustHaveLength => None,
+ ErrorKind::SizeLimit => None,
+ ErrorKind::Custom(_) => None,
+ }
+ }
+}
+
+impl From<IoError> for Error {
+ fn from(err: IoError) -> Error {
+ ErrorKind::IoError(err).into()
+ }
+}
+
+impl fmt::Display for ErrorKind {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ ErrorKind::IoError(ref ioerr) =>
+ write!(fmt, "IoError: {}", ioerr),
+ ErrorKind::InvalidEncoding{desc, detail: None}=>
+ write!(fmt, "InvalidEncoding: {}", desc),
+ ErrorKind::InvalidEncoding{desc, detail: Some(ref detail)}=>
+ write!(fmt, "InvalidEncoding: {} ({})", desc, detail),
+ ErrorKind::SequenceMustHaveLength =>
+ write!(fmt, "Bincode can only encode sequences and maps that have a knowable size ahead of time."),
+ ErrorKind::SizeLimit =>
+ write!(fmt, "SizeLimit"),
+ ErrorKind::Custom(ref s) =>
+ s.fmt(fmt),
+ }
+ }
+}
+
+impl serde::de::Error for Error {
+ fn custom<T: fmt::Display>(desc: T) -> Error {
+ ErrorKind::Custom(desc.to_string()).into()
+ }
+}
+
+impl serde::ser::Error for Error {
+ fn custom<T: fmt::Display>(msg: T) -> Self {
+ ErrorKind::Custom(msg.to_string()).into()
+ }
+}
+
/// Serializes an object directly into a `Writer`.
///
/// If the serialization would take more bytes than allowed by `size_limit`, an error
/// is returned and *no bytes* will be written into the `Writer`.
///
-/// If this returns an `SerializeError` (other than SizeLimit), assume that the
+/// 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, T>(writer: &mut W, value: &T, size_limit: SizeLimit) -> SerializeResult<()>
- where W: Write, T: serde::Serialize,
+pub fn serialize_into<W: ?Sized, T: ?Sized>(writer: &mut W, value: &T, size_limit: SizeLimit) -> Result<()>
+ where W: Write,
+ T: serde::Serialize,
{
match size_limit {
SizeLimit::Infinite => { }
SizeLimit::Bounded(x) => {
let mut size_checker = SizeChecker::new(x);
try!(value.serialize(&mut size_checker))
}
}
@@ -47,77 +133,78 @@ pub fn serialize_into<W, T>(writer: &mut
let mut serializer = Serializer::new(writer);
serde::Serialize::serialize(value, &mut serializer)
}
/// 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>(value: &T, size_limit: SizeLimit) -> SerializeResult<Vec<u8>>
- where T: serde::Serialize,
+pub fn serialize<T: ?Sized>(value: &T, size_limit: SizeLimit) -> Result<Vec<u8>>
+ where T: serde::Serialize
{
// 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 {
SizeLimit::Bounded(size_limit) => {
- let actual_size = match serialized_size_bounded(value, size_limit) {
- Some(actual_size) => actual_size,
- None => { return Err(SerializeError::SizeLimit); }
- };
+ let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(ErrorKind::SizeLimit));
Vec::with_capacity(actual_size as usize)
}
SizeLimit::Infinite => Vec::new()
};
try!(serialize_into(&mut writer, value, SizeLimit::Infinite));
Ok(writer)
}
/// Returns the size that an object would be if serialized using bincode.
///
/// This is used internally as part of the check for encode_into, but it can
/// be useful for preallocating buffers if thats your style.
-pub fn serialized_size<T: serde::Serialize>(value: &T) -> u64 {
+pub fn serialized_size<T: ?Sized>(value: &T) -> u64
+ where T: serde::Serialize
+{
use std::u64::MAX;
let mut size_checker = SizeChecker::new(MAX);
value.serialize(&mut size_checker).ok();
size_checker.written
}
/// Given a maximum size limit, check how large an object would be if it
/// were to be serialized.
///
/// 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: serde::Serialize>(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_checker = SizeChecker::new(max);
value.serialize(&mut size_checker).ok().map(|_| size_checker.written)
}
/// Deserializes an object directly from a `Buffer`ed Reader.
///
/// If the provided `SizeLimit` is reached, the deserialization will bail immediately.
/// A SizeLimit can help prevent an attacker from flooding your server with
/// a neverending stream of values that runs your server out of memory.
///
-/// If this returns an `DeserializeError`, assume that the buffer that you passed
+/// 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, T>(reader: &mut R, size_limit: SizeLimit) -> DeserializeResult<T>
+pub fn deserialize_from<R: ?Sized, T>(reader: &mut R, size_limit: SizeLimit) -> Result<T>
where R: Read,
T: serde::Deserialize,
{
let mut deserializer = Deserializer::new(reader, size_limit);
serde::Deserialize::deserialize(&mut deserializer)
}
/// 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]) -> DeserializeResult<T>
+pub fn deserialize<T>(bytes: &[u8]) -> Result<T>
where T: serde::Deserialize,
{
let mut reader = bytes;
deserialize_from(&mut reader, SizeLimit::Infinite)
}
--- a/third_party/rust/bincode/src/serde/reader.rs
+++ b/third_party/rust/bincode/src/serde/reader.rs
@@ -1,284 +1,158 @@
use std::io::Read;
-use std::io::Error as IoError;
-use std::error::Error;
-use std::fmt;
-use std::convert::From;
use byteorder::{BigEndian, ReadBytesExt};
-use num_traits;
use serde_crate as serde;
use serde_crate::de::value::ValueDeserializer;
-
+use serde_crate::de::Error as DeError;
use ::SizeLimit;
-
-#[derive(Eq, PartialEq, Clone, Debug)]
-pub struct InvalidEncoding {
- pub desc: &'static str,
- pub detail: Option<String>,
-}
-
-impl fmt::Display for InvalidEncoding {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- InvalidEncoding { detail: None, desc } =>
- write!(fmt, "{}", desc),
- InvalidEncoding { detail: Some(ref detail), desc } =>
- write!(fmt, "{} ({})", desc, detail)
- }
- }
-}
-
-/// An error that can be produced during decoding.
-///
-/// If decoding from a Buffer, assume that the buffer has been left
-/// in an invalid state.
-#[derive(Debug)]
-pub enum DeserializeError {
- /// If the error stems from the reader that is being used
- /// during decoding, that error will be stored and returned here.
- IoError(IoError),
- /// If the bytes in the reader are not decodable because of an invalid
- /// 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(InvalidEncoding),
- /// If decoding a message takes more than the provided size limit, this
- /// error is returned.
- SizeLimit,
- Serde(serde::de::value::Error)
-}
-
-impl Error for DeserializeError {
- fn description(&self) -> &str {
- match *self {
- DeserializeError::IoError(ref err) => Error::description(err),
- DeserializeError::InvalidEncoding(ref ib) => ib.desc,
- DeserializeError::SizeLimit => "the size limit for decoding has been reached",
- DeserializeError::Serde(ref s) => s.description(),
-
- }
- }
-
- fn cause(&self) -> Option<&Error> {
- match *self {
- DeserializeError::IoError(ref err) => err.cause(),
- DeserializeError::InvalidEncoding(_) => None,
- DeserializeError::SizeLimit => None,
- DeserializeError::Serde(ref s) => s.cause(),
- }
- }
-}
-
-impl From<IoError> for DeserializeError {
- fn from(err: IoError) -> DeserializeError {
- DeserializeError::IoError(err)
- }
-}
-
-impl From<serde::de::value::Error> for DeserializeError {
- fn from(err: serde::de::value::Error) -> DeserializeError {
- DeserializeError::Serde(err)
- }
-}
-
-impl fmt::Display for DeserializeError {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- DeserializeError::IoError(ref ioerr) =>
- write!(fmt, "IoError: {}", ioerr),
- DeserializeError::InvalidEncoding(ref ib) =>
- write!(fmt, "InvalidEncoding: {}", ib),
- DeserializeError::SizeLimit =>
- write!(fmt, "SizeLimit"),
- DeserializeError::Serde(ref s) =>
- s.fmt(fmt),
- }
- }
-}
-
-impl serde::de::Error for DeserializeError {
- fn custom<T: Into<String>>(desc: T) -> DeserializeError {
- DeserializeError::Serde(serde::de::value::Error::Custom(desc.into()))
- }
-
- fn end_of_stream() -> DeserializeError {
- DeserializeError::Serde(serde::de::value::Error::EndOfStream)
- }
-}
-
-pub type DeserializeResult<T> = Result<T, DeserializeError>;
-
+use super::{Result, Error, ErrorKind};
/// A Deserializer that reads bytes from a buffer.
///
/// This struct should rarely be used.
/// In most cases, prefer the `decode_from` function.
///
/// ```rust,ignore
/// let d = Deserializer::new(&mut some_reader, SizeLimit::new());
/// serde::Deserialize::deserialize(&mut deserializer);
/// let bytes_read = d.bytes_read();
/// ```
-pub struct Deserializer<'a, R: 'a> {
- reader: &'a mut R,
+pub struct Deserializer<R> {
+ reader: R,
size_limit: SizeLimit,
read: u64
}
-impl<'a, R: Read> Deserializer<'a, R> {
- pub fn new(r: &'a mut R, size_limit: SizeLimit) -> Deserializer<'a, R> {
+impl<R: Read> Deserializer<R> {
+ pub fn new(r: R, size_limit: SizeLimit) -> Deserializer<R> {
Deserializer {
reader: r,
size_limit: size_limit,
read: 0
}
}
/// 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<(), DeserializeError> {
+ fn read_bytes(&mut self, count: u64) -> Result<()> {
self.read += count;
match self.size_limit {
SizeLimit::Infinite => Ok(()),
SizeLimit::Bounded(x) if self.read <= x => Ok(()),
- SizeLimit::Bounded(_) => Err(DeserializeError::SizeLimit)
+ SizeLimit::Bounded(_) => Err(ErrorKind::SizeLimit.into())
}
}
- fn read_type<T>(&mut self) -> Result<(), DeserializeError> {
+ fn read_type<T>(&mut self) -> Result<()> {
use std::mem::size_of;
self.read_bytes(size_of::<T>() as u64)
}
- fn read_string(&mut self) -> DeserializeResult<String> {
- let len = try!(serde::Deserialize::deserialize(self));
+ fn read_string(&mut self) -> Result<String> {
+ let len = try!(serde::Deserialize::deserialize(&mut *self));
try!(self.read_bytes(len));
let mut buffer = Vec::new();
try!(self.reader.by_ref().take(len as u64).read_to_end(&mut buffer));
String::from_utf8(buffer).map_err(|err|
- DeserializeError::InvalidEncoding(InvalidEncoding {
+ ErrorKind::InvalidEncoding{
desc: "error while decoding utf8 string",
detail: Some(format!("Deserialize error: {}", err))
- }))
+ }.into())
}
}
macro_rules! impl_nums {
($ty:ty, $dser_method:ident, $visitor_method:ident, $reader_method:ident) => {
#[inline]
- fn $dser_method<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn $dser_method<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
try!(self.read_type::<$ty>());
let value = try!(self.reader.$reader_method::<BigEndian>());
visitor.$visitor_method(value)
}
}
}
-impl<'a, R: Read> serde::Deserializer for Deserializer<'a, R> {
- type Error = DeserializeError;
+impl<'a, R: Read> serde::Deserializer for &'a mut Deserializer<R> {
+ type Error = Error;
#[inline]
- fn deserialize<V>(&mut self, _visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize<V>(self, _visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
let message = "bincode does not support Deserializer::deserialize";
- Err(DeserializeError::Serde(serde::de::value::Error::Custom(message.into())))
+ Err(Error::custom(message))
}
- fn deserialize_bool<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
let value: u8 = try!(serde::Deserialize::deserialize(self));
match value {
1 => visitor.visit_bool(true),
0 => visitor.visit_bool(false),
value => {
- Err(DeserializeError::InvalidEncoding(InvalidEncoding {
+ Err(ErrorKind::InvalidEncoding{
desc: "invalid u8 when decoding bool",
detail: Some(format!("Expected 0 or 1, got {}", value))
- }))
+ }.into())
}
}
}
impl_nums!(u16, deserialize_u16, visit_u16, read_u16);
impl_nums!(u32, deserialize_u32, visit_u32, read_u32);
impl_nums!(u64, deserialize_u64, visit_u64, read_u64);
impl_nums!(i16, deserialize_i16, visit_i16, read_i16);
impl_nums!(i32, deserialize_i32, visit_i32, read_i32);
impl_nums!(i64, deserialize_i64, visit_i64, read_i64);
impl_nums!(f32, deserialize_f32, visit_f32, read_f32);
impl_nums!(f64, deserialize_f64, visit_f64, read_f64);
#[inline]
- fn deserialize_u8<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
try!(self.read_type::<u8>());
visitor.visit_u8(try!(self.reader.read_u8()))
}
#[inline]
- fn deserialize_usize<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
- where V: serde::de::Visitor,
- {
- try!(self.read_type::<u64>());
- let value = try!(self.reader.read_u64::<BigEndian>());
- match num_traits::cast(value) {
- Some(value) => visitor.visit_usize(value),
- None => Err(DeserializeError::Serde(serde::de::value::Error::Custom("expected usize".into())))
- }
- }
-
- #[inline]
- fn deserialize_i8<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
try!(self.read_type::<i8>());
visitor.visit_i8(try!(self.reader.read_i8()))
}
- #[inline]
- fn deserialize_isize<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
- where V: serde::de::Visitor,
- {
- try!(self.read_type::<i64>());
- let value = try!(self.reader.read_i64::<BigEndian>());
- match num_traits::cast(value) {
- Some(value) => visitor.visit_isize(value),
- None => Err(DeserializeError::Serde(serde::de::value::Error::Custom("expected isize".into()))),
- }
- }
-
- fn deserialize_unit<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
visitor.visit_unit()
}
- fn deserialize_char<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
use std::str;
- let error = DeserializeError::InvalidEncoding(InvalidEncoding {
+ let error = ErrorKind::InvalidEncoding{
desc: "Invalid char encoding",
detail: None
- });
+ }.into();
let mut buf = [0];
let _ = try!(self.reader.read(&mut buf[..]));
let first_byte = buf[0];
let width = utf8_char_width(first_byte);
if width == 1 { return visitor.visit_char(first_byte as char) }
if width == 0 { return Err(error)}
@@ -298,255 +172,245 @@ impl<'a, R: Read> serde::Deserializer fo
let res = try!(match str::from_utf8(&buf[..width]).ok() {
Some(s) => Ok(s.chars().next().unwrap()),
None => Err(error)
});
visitor.visit_char(res)
}
- fn deserialize_str<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
visitor.visit_str(&try!(self.read_string()))
}
- fn deserialize_string<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
visitor.visit_string(try!(self.read_string()))
}
- fn deserialize_bytes<V>(&mut self, visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
+ where V: serde::de::Visitor,
+ {
+ self.deserialize_seq(visitor)
+ }
+
+ fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
self.deserialize_seq(visitor)
}
- fn deserialize_enum<V>(&mut self,
+ fn deserialize_enum<V>(self,
_enum: &'static str,
_variants: &'static [&'static str],
- mut visitor: V) -> Result<V::Value, Self::Error>
- where V: serde::de::EnumVisitor,
- {
- visitor.visit(self)
- }
-
- fn deserialize_tuple<V>(&mut self,
- _len: usize,
- mut visitor: V) -> DeserializeResult<V::Value>
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
- struct TupleVisitor<'a, 'b: 'a, R: Read + 'b>(&'a mut Deserializer<'b, R>);
+ impl<'a, R: Read + 'a> serde::de::EnumVisitor for &'a mut Deserializer<R> {
+ type Error = Error;
+ type Variant = Self;
- impl<'a, 'b: 'a, R: Read + 'b> serde::de::SeqVisitor for TupleVisitor<'a, 'b, R> {
- type Error = DeserializeError;
+ fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
+ where V: serde::de::DeserializeSeed,
+ {
+ let idx: u32 = try!(serde::de::Deserialize::deserialize(&mut *self));
+ let val: Result<_> = seed.deserialize(idx.into_deserializer());
+ Ok((try!(val), self))
+ }
+ }
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: serde::de::Deserialize,
+ 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>(&'a mut Deserializer<R>);
+
+ impl<'a, 'b: 'a, R: Read + 'b> serde::de::SeqVisitor for TupleVisitor<'a, R> {
+ type Error = Error;
+
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
+ where T: serde::de::DeserializeSeed,
{
- let value = try!(serde::Deserialize::deserialize(self.0));
+ let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.0));
Ok(Some(value))
}
-
- fn end(&mut self) -> Result<(), Self::Error> {
- Ok(())
- }
}
visitor.visit_seq(TupleVisitor(self))
}
- fn deserialize_seq_fixed_size<V>(&mut self,
- _: usize,
- visitor: V) -> DeserializeResult<V::Value>
- where V: serde::de::Visitor,
- {
- self.deserialize_seq(visitor)
- }
-
- fn deserialize_option<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_seq_fixed_size<V>(self,
+ len: usize,
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
- let value: u8 = try!(serde::de::Deserialize::deserialize(self));
- match value {
- 0 => visitor.visit_none(),
- 1 => visitor.visit_some(self),
- _ => Err(DeserializeError::InvalidEncoding(InvalidEncoding {
- desc: "invalid tag when decoding Option",
- detail: Some(format!("Expected 0 or 1, got {}", value))
- })),
- }
- }
-
- fn deserialize_seq<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
- where V: serde::de::Visitor,
- {
- struct SeqVisitor<'a, 'b: 'a, R: Read + 'b> {
- deserializer: &'a mut Deserializer<'b, R>,
+ struct SeqVisitor<'a, R: Read + 'a> {
+ deserializer: &'a mut Deserializer<R>,
len: usize,
}
- impl<'a, 'b: 'a, R: Read + 'b> serde::de::SeqVisitor for SeqVisitor<'a, 'b, R> {
- type Error = DeserializeError;
+ impl<'a, 'b: 'a, R: Read + 'b> serde::de::SeqVisitor for SeqVisitor<'a, R> {
+ type Error = Error;
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: serde::de::Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
+ where T: serde::de::DeserializeSeed,
{
if self.len > 0 {
self.len -= 1;
- let value = try!(serde::Deserialize::deserialize(self.deserializer));
+ let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer));
Ok(Some(value))
} else {
Ok(None)
}
}
-
- fn end(&mut self) -> Result<(), Self::Error> {
- if self.len == 0 {
- Ok(())
- } else {
- Err(DeserializeError::Serde(serde::de::value::Error::Custom("expected end".into())))
- }
- }
}
- let len = try!(serde::Deserialize::deserialize(self));
-
visitor.visit_seq(SeqVisitor { deserializer: self, len: len })
}
- fn deserialize_map<V>(&mut self, mut visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
- struct MapVisitor<'a, 'b: 'a, R: Read + 'b> {
- deserializer: &'a mut Deserializer<'b, R>,
+ let value: u8 = try!(serde::de::Deserialize::deserialize(&mut *self));
+ match value {
+ 0 => visitor.visit_none(),
+ 1 => visitor.visit_some(&mut *self),
+ _ => Err(ErrorKind::InvalidEncoding{
+ desc: "invalid tag when decoding Option",
+ detail: Some(format!("Expected 0 or 1, got {}", value))
+ }.into()),
+ }
+ }
+
+ fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
+ where V: serde::de::Visitor,
+ {
+ let len = try!(serde::Deserialize::deserialize(&mut *self));
+
+ self.deserialize_seq_fixed_size(len, visitor)
+ }
+
+ fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
+ where V: serde::de::Visitor,
+ {
+ struct MapVisitor<'a, R: Read + 'a> {
+ deserializer: &'a mut Deserializer<R>,
len: usize,
}
- impl<'a, 'b: 'a, R: Read + 'b> serde::de::MapVisitor for MapVisitor<'a, 'b, R> {
- type Error = DeserializeError;
+ impl<'a, 'b: 'a, R: Read + 'b> serde::de::MapVisitor for MapVisitor<'a, R> {
+ type Error = Error;
- fn visit_key<K>(&mut self) -> Result<Option<K>, Self::Error>
- where K: serde::de::Deserialize,
+ fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
+ where K: serde::de::DeserializeSeed,
{
if self.len > 0 {
self.len -= 1;
- let key = try!(serde::Deserialize::deserialize(self.deserializer));
+ let key = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer));
Ok(Some(key))
} else {
Ok(None)
}
}
- fn visit_value<V>(&mut self) -> Result<V, Self::Error>
- where V: serde::de::Deserialize,
+ fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
+ where V: serde::de::DeserializeSeed,
{
- let value = try!(serde::Deserialize::deserialize(self.deserializer));
+ let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer));
Ok(value)
}
-
- fn end(&mut self) -> Result<(), Self::Error> {
- if self.len == 0 {
- Ok(())
- } else {
- Err(DeserializeError::Serde(serde::de::value::Error::Custom("expected end".into())))
- }
- }
}
- let len = try!(serde::Deserialize::deserialize(self));
+ let len = try!(serde::Deserialize::deserialize(&mut *self));
visitor.visit_map(MapVisitor { deserializer: self, len: len })
}
- fn deserialize_struct<V>(&mut self,
+ fn deserialize_struct<V>(self,
_name: &str,
fields: &'static [&'static str],
- visitor: V) -> DeserializeResult<V::Value>
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
self.deserialize_tuple(fields.len(), visitor)
}
- fn deserialize_struct_field<V>(&mut self,
- _visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_struct_field<V>(self,
+ _visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
let message = "bincode does not support Deserializer::deserialize_struct_field";
- Err(DeserializeError::Serde(serde::de::value::Error::Custom(message.into())))
+ Err(Error::custom(message))
}
- fn deserialize_newtype_struct<V>(&mut self,
+ fn deserialize_newtype_struct<V>(self,
_name: &str,
- mut visitor: V) -> DeserializeResult<V::Value>
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
visitor.visit_newtype_struct(self)
}
- fn deserialize_unit_struct<V>(&mut self,
+ fn deserialize_unit_struct<V>(self,
_name: &'static str,
- mut visitor: V) -> DeserializeResult<V::Value>
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
visitor.visit_unit()
}
- fn deserialize_tuple_struct<V>(&mut self,
+ fn deserialize_tuple_struct<V>(self,
_name: &'static str,
len: usize,
- visitor: V) -> DeserializeResult<V::Value>
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
self.deserialize_tuple(len, visitor)
}
- fn deserialize_ignored_any<V>(&mut self,
- _visitor: V) -> DeserializeResult<V::Value>
+ fn deserialize_ignored_any<V>(self,
+ _visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
let message = "bincode does not support Deserializer::deserialize_ignored_any";
- Err(DeserializeError::Serde(serde::de::value::Error::Custom(message.into())))
+ Err(Error::custom(message))
}
}
-impl<'a, R: Read> serde::de::VariantVisitor for Deserializer<'a, R> {
- type Error = DeserializeError;
+impl<'a, R: Read> serde::de::VariantVisitor for &'a mut Deserializer<R> {
+ type Error = Error;
- fn visit_variant<V>(&mut self) -> Result<V, Self::Error>
- where V: serde::Deserialize,
- {
- let index: u32 = try!(serde::Deserialize::deserialize(self));
- let mut deserializer = (index as usize).into_deserializer();
- let attempt: Result<V, serde::de::value::Error> = serde::Deserialize::deserialize(&mut deserializer);
- Ok(try!(attempt))
- }
-
- fn visit_unit(&mut self) -> Result<(), Self::Error> {
+ fn visit_unit(self) -> Result<()> {
Ok(())
}
- fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
- where T: serde::de::Deserialize,
+ fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value>
+ where T: serde::de::DeserializeSeed,
{
- serde::de::Deserialize::deserialize(self)
+ serde::de::DeserializeSeed::deserialize(seed, self)
}
- fn visit_tuple<V>(&mut self,
+ fn visit_tuple<V>(self,
len: usize,
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
serde::de::Deserializer::deserialize_tuple(self, len, visitor)
}
- fn visit_struct<V>(&mut self,
+ fn visit_struct<V>(self,
fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V) -> Result<V::Value>
where V: serde::de::Visitor,
{
serde::de::Deserializer::deserialize_tuple(self, fields.len(), visitor)
}
}
static UTF8_CHAR_WIDTH: [u8; 256] = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
--- a/third_party/rust/bincode/src/serde/writer.rs
+++ b/third_party/rust/bincode/src/serde/writer.rs
@@ -1,331 +1,196 @@
-use std::error::Error;
-use std::fmt;
-use std::io::Error as IoError;
use std::io::Write;
use std::u32;
use serde_crate as serde;
use byteorder::{BigEndian, WriteBytesExt};
-pub type SerializeResult<T> = Result<T, SerializeError>;
-
-
-/// An error that can be produced during encoding.
-#[derive(Debug)]
-pub enum SerializeError {
- /// An error originating from the underlying `Writer`.
- IoError(IoError),
- /// An object could not be encoded with the given size limit.
- ///
- /// This error is returned before any bytes are written to the
- /// output `Writer`.
- SizeLimit,
- /// A custom error message
- Custom(String)
-}
+use super::{Result, Error, ErrorKind};
/// An Serializer that encodes values directly into a Writer.
///
/// This struct should not be used often.
/// For most cases, prefer the `encode_into` function.
-pub struct Serializer<'a, W: 'a> {
- writer: &'a mut W,
-}
-
-fn wrap_io(err: IoError) -> SerializeError {
- SerializeError::IoError(err)
-}
-
-impl serde::ser::Error for SerializeError {
- fn custom<T: Into<String>>(msg: T) -> Self {
- SerializeError::Custom(msg.into())
- }
+pub struct Serializer<W> {
+ writer: W,
}
-impl fmt::Display for SerializeError {
- fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- match *self {
- SerializeError::IoError(ref err) => write!(f, "IoError: {}", err),
- SerializeError::Custom(ref s) => write!(f, "Custom Error {}", s),
- SerializeError::SizeLimit => write!(f, "SizeLimit"),
- }
- }
-}
-
-impl Error for SerializeError {
- fn description(&self) -> &str {
- match *self {
- SerializeError::IoError(ref err) => Error::description(err),
- SerializeError::SizeLimit => "the size limit for decoding has been reached",
- SerializeError::Custom(_) => "a custom serialization error was reported",
- }
- }
-
- fn cause(&self) -> Option<&Error> {
- match *self {
- SerializeError::IoError(ref err) => err.cause(),
- SerializeError::SizeLimit => None,
- SerializeError::Custom(_) => None,
- }
- }
-}
-
-impl<'a, W: Write> Serializer<'a, W> {
- pub fn new(w: &'a mut W) -> Serializer<'a, W> {
+impl<W: Write> Serializer<W> {
+ pub fn new(w: W) -> Serializer<W> {
Serializer {
writer: w,
}
}
- fn add_enum_tag(&mut self, tag: usize) -> SerializeResult<()> {
+ 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> serde::Serializer for Serializer<'a, W> {
- type Error = SerializeError;
- type SeqState = ();
- type TupleState = ();
- type TupleStructState = ();
- type TupleVariantState = ();
- type MapState = ();
- type StructState = ();
- type StructVariantState = ();
+impl<'a, W: Write> serde::Serializer for &'a mut Serializer<W> {
+ type Ok = ();
+ type Error = Error;
+ type SerializeSeq = Compound<'a, W>;
+ type SerializeTuple = Compound<'a, W>;
+ type SerializeTupleStruct = Compound<'a, W>;
+ type SerializeTupleVariant = Compound<'a, W>;
+ type SerializeMap = Compound<'a, W>;
+ type SerializeStruct = Compound<'a, W>;
+ type SerializeStructVariant = Compound<'a, W>;
- fn serialize_unit(&mut self) -> SerializeResult<()> { Ok(()) }
+ fn serialize_unit(self) -> Result<()> { Ok(()) }
- fn serialize_unit_struct(&mut self, _: &'static str) -> SerializeResult<()> { Ok(()) }
+ fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) }
- fn serialize_bool(&mut self, v: bool) -> SerializeResult<()> {
- self.writer.write_u8(if v {1} else {0}).map_err(wrap_io)
+ fn serialize_bool(self, v: bool) -> Result<()> {
+ self.writer.write_u8(if v {1} else {0}).map_err(Into::into)
}
- fn serialize_u8(&mut self, v: u8) -> SerializeResult<()> {
- self.writer.write_u8(v).map_err(wrap_io)
+ fn serialize_u8(self, v: u8) -> Result<()> {
+ self.writer.write_u8(v).map_err(Into::into)
}
- fn serialize_u16(&mut self, v: u16) -> SerializeResult<()> {
- self.writer.write_u16::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_u16(self, v: u16) -> Result<()> {
+ self.writer.write_u16::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_u32(&mut self, v: u32) -> SerializeResult<()> {
- self.writer.write_u32::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_u32(self, v: u32) -> Result<()> {
+ self.writer.write_u32::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_u64(&mut self, v: u64) -> SerializeResult<()> {
- self.writer.write_u64::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_u64(self, v: u64) -> Result<()> {
+ self.writer.write_u64::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_usize(&mut self, v: usize) -> SerializeResult<()> {
- self.serialize_u64(v as u64)
- }
-
- fn serialize_i8(&mut self, v: i8) -> SerializeResult<()> {
- self.writer.write_i8(v).map_err(wrap_io)
+ fn serialize_i8(self, v: i8) -> Result<()> {
+ self.writer.write_i8(v).map_err(Into::into)
}
- fn serialize_i16(&mut self, v: i16) -> SerializeResult<()> {
- self.writer.write_i16::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_i16(self, v: i16) -> Result<()> {
+ self.writer.write_i16::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_i32(&mut self, v: i32) -> SerializeResult<()> {
- self.writer.write_i32::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_i32(self, v: i32) -> Result<()> {
+ self.writer.write_i32::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_i64(&mut self, v: i64) -> SerializeResult<()> {
- self.writer.write_i64::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_i64(self, v: i64) -> Result<()> {
+ self.writer.write_i64::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_isize(&mut self, v: isize) -> SerializeResult<()> {
- self.serialize_i64(v as i64)
+ fn serialize_f32(self, v: f32) -> Result<()> {
+ self.writer.write_f32::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_f32(&mut self, v: f32) -> SerializeResult<()> {
- self.writer.write_f32::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_f64(self, v: f64) -> Result<()> {
+ self.writer.write_f64::<BigEndian>(v).map_err(Into::into)
}
- fn serialize_f64(&mut self, v: f64) -> SerializeResult<()> {
- self.writer.write_f64::<BigEndian>(v).map_err(wrap_io)
+ fn serialize_str(self, v: &str) -> Result<()> {
+ try!(self.serialize_u64(v.len() as u64));
+ self.writer.write_all(v.as_bytes()).map_err(Into::into)
}
- fn serialize_str(&mut self, v: &str) -> SerializeResult<()> {
- try!(self.serialize_usize(v.len()));
- self.writer.write_all(v.as_bytes()).map_err(SerializeError::IoError)
- }
-
- fn serialize_char(&mut self, c: char) -> SerializeResult<()> {
- self.writer.write_all(encode_utf8(c).as_slice()).map_err(SerializeError::IoError)
+ fn serialize_char(self, c: char) -> Result<()> {
+ self.writer.write_all(encode_utf8(c).as_slice()).map_err(Into::into)
}
- fn serialize_bytes(&mut self, v: &[u8]) -> SerializeResult<()> {
- try!(self.serialize_usize(v.len()));
- self.writer.write_all(v).map_err(SerializeError::IoError)
+ fn serialize_bytes(self, v: &[u8]) -> Result<()> {
+ try!(self.serialize_u64(v.len() as u64));
+ self.writer.write_all(v).map_err(Into::into)
}
- fn serialize_none(&mut self) -> SerializeResult<()> {
- self.writer.write_u8(0).map_err(wrap_io)
+ fn serialize_none(self) -> Result<()> {
+ self.writer.write_u8(0).map_err(Into::into)
}
- fn serialize_some<T>(&mut self, v: T) -> SerializeResult<()>
+ fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>
where T: serde::Serialize,
{
- try!(self.writer.write_u8(1).map_err(wrap_io));
+ try!(self.writer.write_u8(1));
v.serialize(self)
}
- fn serialize_seq(&mut self, len: Option<usize>) -> SerializeResult<()> {
- let len = len.expect("do not know how to serialize a sequence with no length");
- self.serialize_usize(len)
- }
-
- fn serialize_seq_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
+ fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
+ let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
+ try!(self.serialize_u64(len as u64));
+ Ok(Compound {ser: self})
}
- fn serialize_seq_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_seq_fixed_size(&mut self, len: usize) -> SerializeResult<()> {
- self.serialize_seq(Some(len))
- }
-
- fn serialize_tuple(&mut self, _len: usize) -> SerializeResult<()> {
- Ok(())
+ fn serialize_seq_fixed_size(self, _len: usize) -> Result<Self::SerializeSeq> {
+ Ok(Compound {ser: self})
}
- fn serialize_tuple_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_tuple_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
+ fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
+ Ok(Compound {ser: self})
}
- fn serialize_tuple_struct(&mut self, _name: &'static str, _len: usize) -> SerializeResult<()> {
- Ok(())
+ fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
+ Ok(Compound {ser: self})
}
- fn serialize_tuple_struct_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_tuple_struct_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_tuple_variant(&mut self,
+ fn serialize_tuple_variant(self,
_name: &'static str,
variant_index: usize,
_variant: &'static str,
- _len: usize) -> SerializeResult<()>
- {
- self.add_enum_tag(variant_index)
- }
-
- fn serialize_tuple_variant_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
+ _len: usize) -> Result<Self::SerializeTupleVariant>
{
- value.serialize(self)
- }
-
- fn serialize_tuple_variant_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_map(&mut self, len: Option<usize>) -> SerializeResult<()> {
- let len = len.expect("do not know how to serialize a map with no length");
- self.serialize_usize(len)
- }
-
- fn serialize_map_key<K>(&mut self, _: &mut (), key: K) -> SerializeResult<()>
- where K: serde::Serialize,
- {
- key.serialize(self)
+ try!(self.add_enum_tag(variant_index));
+ Ok(Compound {ser: self})
}
- fn serialize_map_value<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_map_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
+ fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
+ let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
+ try!(self.serialize_u64(len as u64));
+ Ok(Compound {ser: self})
}
- fn serialize_struct(&mut self, _name: &'static str, _len: usize) -> SerializeResult<()> {
- Ok(())
+ fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
+ Ok(Compound {ser: self})
}
- fn serialize_struct_elt<V>(&mut self, _: &mut (), _key: &'static str, value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_struct_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_struct_variant(&mut self,
+ fn serialize_struct_variant(self,
_name: &'static str,
variant_index: usize,
_variant: &'static str,
- _len: usize) -> SerializeResult<()>
+ _len: usize) -> Result<Self::SerializeStructVariant>
{
- self.add_enum_tag(variant_index)
+ try!(self.add_enum_tag(variant_index));
+ Ok(Compound {ser: self})
}
- fn serialize_struct_variant_elt<V>(&mut self, _: &mut (), _key: &'static str, value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_struct_variant_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_newtype_struct<T>(&mut self,
+ fn serialize_newtype_struct<T: ?Sized>(self,
_name: &'static str,
- value: T) -> SerializeResult<()>
+ value: &T) -> Result<()>
where T: serde::ser::Serialize,
{
value.serialize(self)
}
- fn serialize_newtype_variant<T>(&mut self,
+ fn serialize_newtype_variant<T: ?Sized>(self,
_name: &'static str,
variant_index: usize,
_variant: &'static str,
- value: T) -> SerializeResult<()>
+ value: &T) -> Result<()>
where T: serde::ser::Serialize,
{
try!(self.add_enum_tag(variant_index));
value.serialize(self)
}
- fn serialize_unit_variant(&mut self,
+ fn serialize_unit_variant(self,
_name: &'static str,
variant_index: usize,
- _variant: &'static str) -> SerializeResult<()> {
+ _variant: &'static str) -> Result<()> {
self.add_enum_tag(variant_index)
}
}
pub struct SizeChecker {
pub size_limit: u64,
pub written: u64
}
@@ -333,275 +198,479 @@ pub struct SizeChecker {
impl SizeChecker {
pub fn new(limit: u64) -> SizeChecker {
SizeChecker {
size_limit: limit,
written: 0
}
}
- fn add_raw(&mut self, size: usize) -> SerializeResult<()> {
+ fn add_raw(&mut self, size: usize) -> Result<()> {
self.written += size as u64;
if self.written <= self.size_limit {
Ok(())
} else {
- Err(SerializeError::SizeLimit)
+ Err(ErrorKind::SizeLimit.into())
}
}
- fn add_value<T>(&mut self, t: T) -> SerializeResult<()> {
+ fn add_value<T>(&mut self, t: T) -> Result<()> {
use std::mem::size_of_val;
self.add_raw(size_of_val(&t))
}
- fn add_enum_tag(&mut self, tag: usize) -> SerializeResult<()> {
+ 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 serde::Serializer for SizeChecker {
- type Error = SerializeError;
- type SeqState = ();
- type TupleState = ();
- type TupleStructState = ();
- type TupleVariantState = ();
- type MapState = ();
- type StructState = ();
- type StructVariantState = ();
+impl<'a> serde::Serializer for &'a mut SizeChecker {
+ type Ok = ();
+ type Error = Error;
+ type SerializeSeq = SizeCompound<'a>;
+ type SerializeTuple = SizeCompound<'a>;
+ type SerializeTupleStruct = SizeCompound<'a>;
+ type SerializeTupleVariant = SizeCompound<'a>;
+ type SerializeMap = SizeCompound<'a>;
+ type SerializeStruct = SizeCompound<'a>;
+ type SerializeStructVariant = SizeCompound<'a>;
- fn serialize_unit(&mut self) -> SerializeResult<()> { Ok(()) }
+ fn serialize_unit(self) -> Result<()> { Ok(()) }
- fn serialize_unit_struct(&mut self, _: &'static str) -> SerializeResult<()> { Ok(()) }
+ fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) }
- fn serialize_bool(&mut self, _: bool) -> SerializeResult<()> {
+ fn serialize_bool(self, _: bool) -> Result<()> {
self.add_value(0 as u8)
}
- fn serialize_u8(&mut self, v: u8) -> SerializeResult<()> {
+ fn serialize_u8(self, v: u8) -> Result<()> {
self.add_value(v)
}
- fn serialize_u16(&mut self, v: u16) -> SerializeResult<()> {
- self.add_value(v)
- }
-
- fn serialize_u32(&mut self, v: u32) -> SerializeResult<()> {
- self.add_value(v)
- }
-
- fn serialize_u64(&mut self, v: u64) -> SerializeResult<()> {
+ fn serialize_u16(self, v: u16) -> Result<()> {
self.add_value(v)
}
- fn serialize_usize(&mut self, v: usize) -> SerializeResult<()> {
- self.serialize_u64(v as u64)
- }
-
- fn serialize_i8(&mut self, v: i8) -> SerializeResult<()> {
+ fn serialize_u32(self, v: u32) -> Result<()> {
self.add_value(v)
}
- fn serialize_i16(&mut self, v: i16) -> SerializeResult<()> {
+ fn serialize_u64(self, v: u64) -> Result<()> {
self.add_value(v)
}
- fn serialize_i32(&mut self, v: i32) -> SerializeResult<()> {
+ fn serialize_i8(self, v: i8) -> Result<()> {
+ self.add_value(v)
+ }
+
+ fn serialize_i16(self, v: i16) -> Result<()> {
self.add_value(v)
}
- fn serialize_i64(&mut self, v: i64) -> SerializeResult<()> {
+ fn serialize_i32(self, v: i32) -> Result<()> {
+ self.add_value(v)
+ }
+
+ fn serialize_i64(self, v: i64) -> Result<()> {
self.add_value(v)
}
- fn serialize_isize(&mut self, v: isize) -> SerializeResult<()> {
- self.serialize_i64(v as i64)
- }
-
- fn serialize_f32(&mut self, v: f32) -> SerializeResult<()> {
+ fn serialize_f32(self, v: f32) -> Result<()> {
self.add_value(v)
}
- fn serialize_f64(&mut self, v: f64) -> SerializeResult<()> {
+ fn serialize_f64(self, v: f64) -> Result<()> {
self.add_value(v)
}
- fn serialize_str(&mut self, v: &str) -> SerializeResult<()> {
+ fn serialize_str(self, v: &str) -> Result<()> {
try!(self.add_value(0 as u64));
self.add_raw(v.len())
}
- fn serialize_char(&mut self, c: char) -> SerializeResult<()> {
+ fn serialize_char(self, c: char) -> Result<()> {
self.add_raw(encode_utf8(c).as_slice().len())
}
- fn serialize_bytes(&mut self, v: &[u8]) -> SerializeResult<()> {
+ fn serialize_bytes(self, v: &[u8]) -> Result<()> {
try!(self.add_value(0 as u64));
self.add_raw(v.len())
}
- fn serialize_none(&mut self) -> SerializeResult<()> {
+ fn serialize_none(self) -> Result<()> {
self.add_value(0 as u8)
}
- fn serialize_some<T>(&mut self, v: T) -> SerializeResult<()>
+ fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>
where T: serde::Serialize,
{
try!(self.add_value(1 as u8));
v.serialize(self)
}
- fn serialize_seq(&mut self, len: Option<usize>) -> SerializeResult<()> {
- let len = len.expect("do not know how to serialize a sequence with no length");
-
- self.serialize_usize(len)
- }
+ fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
+ let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
- fn serialize_seq_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_seq_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_seq_fixed_size(&mut self, len: usize) -> SerializeResult<()> {
- self.serialize_seq(Some(len))
- }
-
- fn serialize_tuple(&mut self, _len: usize) -> SerializeResult<()> {
- Ok(())
+ try!(self.serialize_u64(len as u64));
+ Ok(SizeCompound {ser: self})
}
- fn serialize_tuple_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_tuple_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
+ fn serialize_seq_fixed_size(self, _len: usize) -> Result<Self::SerializeSeq> {
+ Ok(SizeCompound {ser: self})
}
- fn serialize_tuple_struct(&mut self, _name: &'static str, _len: usize) -> SerializeResult<()> {
- Ok(())
+ fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
+ Ok(SizeCompound {ser: self})
}
- fn serialize_tuple_struct_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
+ fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
+ Ok(SizeCompound {ser: self})
}
- fn serialize_tuple_struct_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_tuple_variant(&mut self,
+ fn serialize_tuple_variant(self,
_name: &'static str,
variant_index: usize,
_variant: &'static str,
- _len: usize) -> SerializeResult<()>
+ _len: usize) -> Result<Self::SerializeTupleVariant>
+ {
+ try!(self.add_enum_tag(variant_index));
+ Ok(SizeCompound {ser: self})
+ }
+
+ fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap>
{
+ let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
+
+ try!(self.serialize_u64(len as u64));
+ Ok(SizeCompound {ser: self})
+ }
+
+ fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
+ Ok(SizeCompound {ser: self})
+ }
+
+ fn serialize_struct_variant(self,
+ _name: &'static str,
+ variant_index: usize,
+ _variant: &'static str,
+ _len: usize) -> Result<Self::SerializeStructVariant>
+ {
+ try!(self.add_enum_tag(variant_index));
+ Ok(SizeCompound {ser: self})
+ }
+
+ fn serialize_newtype_struct<V: serde::Serialize + ?Sized>(self, _name: &'static str, v: &V) -> Result<()> {
+ v.serialize(self)
+ }
+
+ fn serialize_unit_variant(self,
+ _name: &'static str,
+ variant_index: usize,
+ _variant: &'static str) -> Result<()> {
self.add_enum_tag(variant_index)
}
- fn serialize_tuple_variant_elt<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_tuple_variant_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_map(&mut self, len: Option<usize>) -> SerializeResult<()>
- {
- let len = len.expect("do not know how to serialize a map with no length");
-
- self.serialize_usize(len)
- }
-
- fn serialize_map_key<K>(&mut self, _: &mut (), key: K) -> SerializeResult<()>
- where K: serde::Serialize,
- {
- key.serialize(self)
- }
-
- fn serialize_map_value<V>(&mut self, _: &mut (), value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_map_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_struct(&mut self, _name: &'static str, _len: usize) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_struct_elt<V>(&mut self, _: &mut (), _key: &'static str, value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_struct_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_struct_variant(&mut self,
+ fn serialize_newtype_variant<V: serde::Serialize + ?Sized>(self,
_name: &'static str,
variant_index: usize,
_variant: &'static str,
- _len: usize) -> SerializeResult<()>
- {
- self.add_enum_tag(variant_index)
- }
-
- fn serialize_struct_variant_elt<V>(&mut self, _: &mut (), _field: &'static str, value: V) -> SerializeResult<()>
- where V: serde::Serialize,
- {
- value.serialize(self)
- }
-
- fn serialize_struct_variant_end(&mut self, _: ()) -> SerializeResult<()> {
- Ok(())
- }
-
- fn serialize_newtype_struct<V: serde::Serialize>(&mut self, _name: &'static str, v: V) -> SerializeResult<()> {
- v.serialize(self)
- }
-
- fn serialize_unit_variant(&mut self,
- _name: &'static str,
- variant_index: usize,
- _variant: &'static str) -> SerializeResult<()> {
- self.add_enum_tag(variant_index)
- }
-
- fn serialize_newtype_variant<V: serde::Serialize>(&mut self,
- _name: &'static str,
- variant_index: usize,
- _variant: &'static str,
- value: V) -> SerializeResult<()>
+ value: &V) -> Result<()>
{
try!(self.add_enum_tag(variant_index));
value.serialize(self)
}
}
+#[doc(hidden)]
+pub struct Compound<'a, W: 'a> {
+ ser: &'a mut Serializer<W>,
+}
+
+impl<'a, W> serde::ser::SerializeSeq for Compound<'a, W>
+ where W: Write
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a, W> serde::ser::SerializeTuple for Compound<'a, W>
+ where W: Write
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a, W> serde::ser::SerializeTupleStruct for Compound<'a, W>
+ where W: Write
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a, W> serde::ser::SerializeTupleVariant for Compound<'a, W>
+ where W: Write
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a, W> serde::ser::SerializeMap for Compound<'a, W>
+ where W: Write
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ 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
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a, W> serde::ser::SerializeStruct for Compound<'a, W>
+ where W: Write
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a, W> serde::ser::SerializeStructVariant for Compound<'a, W>
+ where W: Write
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+#[doc(hidden)]
+pub struct SizeCompound<'a> {
+ ser: &'a mut SizeChecker,
+}
+
+impl<'a> serde::ser::SerializeSeq for SizeCompound<'a>
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> serde::ser::SerializeTuple for SizeCompound<'a>
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> serde::ser::SerializeTupleStruct for SizeCompound<'a>
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> serde::ser::SerializeTupleVariant for SizeCompound<'a>
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> serde::ser::SerializeMap for SizeCompound<'a>
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ 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
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> serde::ser::SerializeStruct for SizeCompound<'a>
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> serde::ser::SerializeStructVariant for SizeCompound<'a>
+{
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
+ where T: serde::ser::Serialize
+ {
+ value.serialize(&mut *self.ser)
+ }
+
+ #[inline]
+ fn end(self) -> Result<()> {
+ Ok(())
+ }
+}
+
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;
--- a/third_party/rust/bincode/tests/test.rs
+++ b/third_party/rust/bincode/tests/test.rs
@@ -1,69 +1,54 @@
-#![feature(proc_macro)]
-
#[macro_use]
extern crate serde_derive;
extern crate bincode;
-extern crate rustc_serialize;
extern crate serde;
use std::fmt::Debug;
use std::collections::HashMap;
use std::ops::Deref;
-use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
-
-use bincode::{RefBox, StrBox, SliceBox};
+use bincode::refbox::{RefBox, StrBox, SliceBox};
use bincode::SizeLimit::{self, Infinite, Bounded};
-use bincode::rustc_serialize::{encode, decode, decode_from, DecodingError};
-use bincode::serde::{serialize, deserialize, deserialize_from, DeserializeError, DeserializeResult};
+use bincode::{serialize, serialized_size, deserialize, deserialize_from, ErrorKind, Result};
fn proxy_encode<V>(element: &V, size_limit: SizeLimit) -> Vec<u8>
- where V: Encodable + Decodable + serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
+ where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
{
- let v1 = bincode::rustc_serialize::encode(element, size_limit).unwrap();
- let v2 = bincode::serde::serialize(element, size_limit).unwrap();
- assert_eq!(v1, v2);
-
- v1
+ let v2 = serialize(element, size_limit).unwrap();
+ v2
}
fn proxy_decode<V>(slice: &[u8]) -> V
- where V: Encodable + Decodable + serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
+ where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
{
- let e1 = bincode::rustc_serialize::decode(slice).unwrap();
- let e2 = bincode::serde::deserialize(slice).unwrap();
-
- assert_eq!(e1, e2);
-
- e1
+ let e2 = deserialize(slice).unwrap();
+ e2
}
fn proxy_encoded_size<V>(element: &V) -> u64
- where V: Encodable + serde::Serialize + PartialEq + Debug + 'static
+ where V: serde::Serialize + PartialEq + Debug + 'static
{
- let ser_size = bincode::rustc_serialize::encoded_size(element);
- let serde_size = bincode::serde::serialized_size(element);
- assert_eq!(ser_size, serde_size);
- ser_size
+ let serde_size = serialized_size(element);
+ serde_size
}
fn the_same<V>(element: V)
- where V: Encodable+Decodable+serde::Serialize+serde::Deserialize+PartialEq+Debug+'static
+ where V: serde::Serialize+serde::Deserialize+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: Encodable + Decodable + PartialEq + Debug + 'static
+ where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
{
let rf = RefBox::new(v);
- let encoded = bincode::rustc_serialize::encode(&rf, Infinite).unwrap();
- let decoded: RefBox<'static, V> = bincode::rustc_serialize::decode(&encoded[..]).unwrap();
+ let encoded = serialize(&rf, Infinite).unwrap();
+ let decoded: RefBox<'static, V> = deserialize(&encoded[..]).unwrap();
decoded.take().deref() == v
}
let size = proxy_encoded_size(&element);
let encoded = proxy_encode(&element, Infinite);
let decoded = proxy_decode(&encoded[..]);
@@ -111,83 +96,83 @@ fn test_string() {
fn test_tuple() {
the_same((1isize,));
the_same((1isize,2isize,3isize));
the_same((1isize,"foo".to_string(),()));
}
#[test]
fn test_basic_struct() {
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Easy {
x: isize,
s: String,
y: usize
}
the_same(Easy{x: -4, s: "foo".to_string(), y: 10});
}
#[test]
fn test_nested_struct() {
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Easy {
x: isize,
s: String,
y: usize
}
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Nest {
f: Easy,
b: usize,
s: Easy
}
the_same(Nest {
f: Easy {x: -1, s: "foo".to_string(), y: 20},
b: 100,
s: Easy {x: -100, s: "bar".to_string(), y: 20}
});
}
#[test]
fn test_struct_newtype() {
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
struct NewtypeStr(usize);
the_same(NewtypeStr(5));
}
#[test]
fn test_struct_tuple() {
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
struct TubStr(usize, String, f32);
the_same(TubStr(5, "hello".to_string(), 3.2));
}
#[test]
fn test_option() {
the_same(Some(5usize));
the_same(Some("foo bar".to_string()));
the_same(None::<usize>);
}
#[test]
fn test_enum() {
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
enum TestEnum {
NoArg,
OneArg(usize),
Args(usize, usize),
AnotherNoArg,
StructLike{x: usize, y: f32}
}
the_same(TestEnum::NoArg);
the_same(TestEnum::OneArg(4));
- the_same(TestEnum::Args(4, 5));
+ //the_same(TestEnum::Args(4, 5));
the_same(TestEnum::AnotherNoArg);
the_same(TestEnum::StructLike{x: 4, y: 3.14159});
the_same(vec![TestEnum::NoArg, TestEnum::OneArg(5), TestEnum::AnotherNoArg,
TestEnum::StructLike{x: 4, y:1.4}]);
}
#[test]
fn test_vec() {
@@ -220,119 +205,68 @@ fn test_unicode() {
#[test]
fn test_fixed_size_array() {
the_same([24u32; 32]);
the_same([1u64, 2, 3, 4, 5, 6, 7, 8]);
the_same([0u8; 19]);
}
#[test]
-fn decoding_errors() {
- fn isize_invalid_encoding<T>(res: bincode::rustc_serialize::DecodingResult<T>) {
- match res {
- Ok(_) => panic!("Expecting error"),
- Err(DecodingError::IoError(_)) => panic!("Expecting InvalidEncoding"),
- Err(DecodingError::SizeLimit) => panic!("Expecting InvalidEncoding"),
- Err(DecodingError::InvalidEncoding(_)) => {},
- }
- }
-
- isize_invalid_encoding(decode::<bool>(&vec![0xA][..]));
- isize_invalid_encoding(decode::<String>(&vec![0, 0, 0, 0, 0, 0, 0, 1, 0xFF][..]));
- // Out-of-bounds variant
- #[derive(RustcEncodable, RustcDecodable, Serialize)]
- enum Test {
- One,
- Two,
- };
- isize_invalid_encoding(decode::<Test>(&vec![0, 0, 0, 5][..]));
- isize_invalid_encoding(decode::<Option<u8>>(&vec![5, 0][..]));
-}
-
-#[test]
fn deserializing_errors() {
- fn isize_invalid_deserialize<T: Debug>(res: DeserializeResult<T>) {
- match res {
- Err(DeserializeError::InvalidEncoding(_)) => {},
- Err(DeserializeError::Serde(serde::de::value::Error::UnknownVariant(_))) => {},
- Err(DeserializeError::Serde(serde::de::value::Error::InvalidValue(_))) => {},
- _ => panic!("Expecting InvalidEncoding, got {:?}", res),
+ fn isize_invalid_deserialize<T: Debug>(res: Result<T>) {
+ match res.map_err(|e| *e) {
+ Err(ErrorKind::InvalidEncoding{..}) => {},
+ Err(ErrorKind::Custom(ref s)) if s.contains("invalid encoding") => {},
+ Err(ErrorKind::Custom(ref s)) if s.contains("invalid value") => {},
+ other => panic!("Expecting InvalidEncoding, got {:?}", other),
}
}
isize_invalid_deserialize(deserialize::<bool>(&vec![0xA][..]));
isize_invalid_deserialize(deserialize::<String>(&vec![0, 0, 0, 0, 0, 0, 0, 1, 0xFF][..]));
// Out-of-bounds variant
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, Debug)]
+ #[derive(Serialize, Deserialize, Debug)]
enum Test {
One,
Two,
};
isize_invalid_deserialize(deserialize::<Test>(&vec![0, 0, 0, 5][..]));
isize_invalid_deserialize(deserialize::<Option<u8>>(&vec![5, 0][..]));
}
#[test]
-fn too_big_decode() {
- let encoded = vec![0,0,0,3];
- let decoded: Result<u32, _> = decode_from(&mut &encoded[..], Bounded(3));
- assert!(decoded.is_err());
-
- let encoded = vec![0,0,0,3];
- let decoded: Result<u32, _> = decode_from(&mut &encoded[..], Bounded(4));
- assert!(decoded.is_ok());
-}
-
-#[test]
fn too_big_deserialize() {
let serialized = vec![0,0,0,3];
- let deserialized: Result<u32, _> = deserialize_from(&mut &serialized[..], Bounded(3));
+ let deserialized: Result<u32> = deserialize_from(&mut &serialized[..], Bounded(3));
assert!(deserialized.is_err());
let serialized = vec![0,0,0,3];
- let deserialized: Result<u32, _> = deserialize_from(&mut &serialized[..], Bounded(4));
+ let deserialized: Result<u32> = deserialize_from(&mut &serialized[..], Bounded(4));
assert!(deserialized.is_ok());
}
#[test]
fn char_serialization() {
let chars = "Aa\0☺♪";
for c in chars.chars() {
let encoded = serialize(&c, Bounded(4)).expect("serializing char failed");
let decoded: char = deserialize(&encoded).expect("deserializing failed");
assert_eq!(decoded, c);
}
}
#[test]
-fn too_big_char_decode() {
- let encoded = vec![0x41];
- let decoded: Result<char, _> = decode_from(&mut &encoded[..], Bounded(1));
- assert!(decoded.is_ok());
- assert_eq!(decoded.unwrap(), 'A');
-}
-
-#[test]
fn too_big_char_deserialize() {
let serialized = vec![0x41];
- let deserialized: Result<char, _> = deserialize_from(&mut &serialized[..], Bounded(1));
+ let deserialized: Result<char> = deserialize_from(&mut &serialized[..], Bounded(1));
assert!(deserialized.is_ok());
assert_eq!(deserialized.unwrap(), 'A');
}
#[test]
-fn too_big_encode() {
- assert!(encode(&0u32, Bounded(3)).is_err());
- assert!(encode(&0u32, Bounded(4)).is_ok());
-
- assert!(encode(&"abcde", Bounded(8 + 4)).is_err());
- assert!(encode(&"abcde", Bounded(8 + 5)).is_ok());
-}
-
-#[test]
fn too_big_serialize() {
assert!(serialize(&0u32, Bounded(3)).is_err());
assert!(serialize(&0u32, Bounded(4)).is_ok());
assert!(serialize(&"abcde", Bounded(8 + 4)).is_err());
assert!(serialize(&"abcde", Bounded(8 + 5)).is_ok());
}
@@ -366,59 +300,23 @@ fn test_serialized_size() {
}
#[test]
fn encode_box() {
the_same(Box::new(5));
}
#[test]
-fn test_refbox_encode() {
- let large_object = vec![1u32,2,3,4,5,6];
- let mut large_map = HashMap::new();
- large_map.insert(1, 2);
-
-
- #[derive(RustcEncodable, RustcDecodable, Debug)]
- enum Message<'a> {
- M1(RefBox<'a, Vec<u32>>),
- M2(RefBox<'a, HashMap<u32, u32>>)
- }
-
- // Test 1
- {
- let encoded = encode(&Message::M1(RefBox::new(&large_object)), Infinite).unwrap();
- let decoded: Message<'static> = decode(&encoded[..]).unwrap();
-
- match decoded {
- Message::M1(b) => assert!(b.take().deref() == &large_object),
- _ => assert!(false)
- }
- }
-
- // Test 2
- {
- let encoded = encode(&Message::M2(RefBox::new(&large_map)), Infinite).unwrap();
- let decoded: Message<'static> = decode(&encoded[..]).unwrap();
-
- match decoded {
- Message::M2(b) => assert!(b.take().deref() == &large_map),
- _ => assert!(false)
- }
- }
-}
-
-#[test]
fn test_refbox_serialize() {
let large_object = vec![1u32,2,3,4,5,6];
let mut large_map = HashMap::new();
large_map.insert(1, 2);
- #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, Debug)]
+ #[derive(Serialize, Deserialize, Debug)]
enum Message<'a> {
M1(RefBox<'a, Vec<u32>>),
M2(RefBox<'a, HashMap<u32, u32>>)
}
// Test 1
{
let serialized = serialize(&Message::M1(RefBox::new(&large_object)), Infinite).unwrap();
@@ -438,142 +336,66 @@ fn test_refbox_serialize() {
match deserialized {
Message::M2(b) => assert!(b.take().deref() == &large_map),
_ => assert!(false)
}
}
}
#[test]
-fn test_strbox_encode() {
- let strx: &'static str = "hello world";
- let encoded = encode(&StrBox::new(strx), Infinite).unwrap();
- let decoded: StrBox<'static> = decode(&encoded[..]).unwrap();
- let stringx: String = decoded.take();
- assert!(strx == &stringx[..]);
-}
-
-#[test]
fn test_strbox_serialize() {
let strx: &'static str = "hello world";
let serialized = serialize(&StrBox::new(strx), Infinite).unwrap();
let deserialized: StrBox<'static> = deserialize_from(&mut &serialized[..], Infinite).unwrap();
let stringx: String = deserialized.take();
assert!(strx == &stringx[..]);
}
#[test]
-fn test_slicebox_encode() {
- let slice = [1u32, 2, 3 ,4, 5];
- let encoded = encode(&SliceBox::new(&slice), Infinite).unwrap();
- let decoded: SliceBox<'static, u32> = decode(&encoded[..]).unwrap();
- {
- let sb: &[u32] = &decoded;
- assert!(slice == sb);
- }
- let vecx: Vec<u32> = decoded.take();
- assert!(slice == &vecx[..]);
-}
-
-#[test]
fn test_slicebox_serialize() {
let slice = [1u32, 2, 3 ,4, 5];
let serialized = serialize(&SliceBox::new(&slice), Infinite).unwrap();
let deserialized: SliceBox<'static, u32> = deserialize_from(&mut &serialized[..], Infinite).unwrap();
{
let sb: &[u32] = &deserialized;
assert!(slice == sb);
}
let vecx: Vec<u32> = deserialized.take();
assert!(slice == &vecx[..]);
}
#[test]
-fn test_multi_strings_encode() {
- assert!(encode(&("foo", "bar", "baz"), Infinite).is_ok());
-}
-
-#[test]
fn test_multi_strings_serialize() {
assert!(serialize(&("foo", "bar", "baz"), Infinite).is_ok());
}
+/*
#[test]
fn test_oom_protection() {
use std::io::Cursor;
- #[derive(RustcEncodable, RustcDecodable)]
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));
assert!(y.is_err());
-}
+}*/
#[test]
fn path_buf() {
use std::path::{Path, PathBuf};
let path = Path::new("foo").to_path_buf();
- let serde_encoded = bincode::serde::serialize(&path, Infinite).unwrap();
- let decoded: PathBuf = bincode::serde::deserialize(&serde_encoded).unwrap();
+ let serde_encoded = serialize(&path, Infinite).unwrap();
+ let decoded: PathBuf = deserialize(&serde_encoded).unwrap();
assert!(path.to_str() == decoded.to_str());
}
#[test]
fn bytes() {
+ use serde::bytes::Bytes;
+
let data = b"abc\0123";
- let b = bincode::rustc_serialize::encode(&data, Infinite).unwrap();
- let s = bincode::serde::serialize(&data, Infinite).unwrap();
- assert_eq!(b, s);
-
- use serde::bytes::Bytes;
- let s2 = bincode::serde::serialize(&Bytes::new(data), Infinite).unwrap();
- assert_eq!(s, s2);
+ let s = serialize(&data, Infinite).unwrap();
+ let s2 = serialize(&Bytes::new(data), Infinite).unwrap();
+ assert_eq!(s[..], s2[8..]);
}
-#[test]
-fn test_manual_enum_encoding() {
- #[derive(PartialEq)]
- enum Enumeration {
- Variant1,
- Variant2 { val: u64 }
- }
-
- impl Encodable for Enumeration {
- fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- s.emit_enum("Enumeration", |s| {
- match *self {
- Enumeration::Variant1 => {
- s.emit_enum_variant("Variant1", 0, 0, |_| Ok(()))
- },
- Enumeration::Variant2 { val } => {
- s.emit_enum_struct_variant("Variant2", 1, 1, |s| {
- s.emit_enum_struct_variant_field("val", 0, |s| s.emit_u64(val))
- })
- }
- }
- })
- }
- }
-
- impl Decodable for Enumeration {
- fn decode<D: Decoder>(s: &mut D) -> Result<Self, D::Error> {
- s.read_enum("Enumeration", |s| {
- s.read_enum_struct_variant(&["Variant1", "Variant2"], |s, num| {
- match num {
- 0 => Ok(Enumeration::Variant1),
- 1 => Ok(Enumeration::Variant2 { val: try!(s.read_u64()) }),
- _ => Err(s.error("Unknown enum variant"))
- }
- })
- })
- }
- }
-
- let encoded = bincode::rustc_serialize::encode(&Enumeration::Variant1, Infinite).unwrap();
- let decoded: Enumeration = decode(&encoded[..]).unwrap();
- assert!(decoded == Enumeration::Variant1);
-
- let encoded = bincode::rustc_serialize::encode(&Enumeration::Variant2 { val: 42 }, Infinite).unwrap();
- let decoded: Enumeration = decode(&encoded[..]).unwrap();
- assert!(decoded == Enumeration::Variant2 { val: 42 });
-}
--- a/third_party/rust/core-graphics/.cargo-checksum.json
+++ b/third_party/rust/core-graphics/.cargo-checksum.json
@@ -1,1 +1,1 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"b71b9a6f84b9263b2b89be6ec90dff5920ee68cf9e5768d73ed71957de2d0670","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"101ff1c674aad746f5a9cc0aec36b7bb7da61df7b621ade9f3c4052ab0901ec6","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":"635ee3d1039c807e00fe93b974c9e375c532f09c99322dd93b9496783a662c0a","src/geometry.rs":"9f59dcf55f393a3fa001afe8aea68a85a3c9a06239aeafe6da5d2823ed37b271","src/lib.rs":"efed3638b05e6a806a6fa0c544893afeec931f6c6889bd4a69d8fd2f9838967f","src/private.rs":"87c96ed2002bd567bf02535b4c6e8e3f22827afb2dd92ee17d91cfb45bc6072c"},"package":"7b205856aba54bfd36e69a1058f45fbe0d3c37be7375309dcff4a22a2a631fea"}
\ No newline at end of file
+{"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"}
\ No newline at end of file
--- a/third_party/rust/core-graphics/Cargo.toml
+++ b/third_party/rust/core-graphics/Cargo.toml
@@ -1,17 +1,17 @@
[package]
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.6.0"
+version = "0.7.0"
authors = ["The Servo Project Developers"]
license = "MIT / Apache-2.0"
[features]
default = []
elcapitan = []
[dependencies]
libc = "0.2"
core-foundation = "0.3"
-serde = "0.8"
+serde = "0.9"
--- a/third_party/rust/core-graphics/src/font.rs
+++ b/third_party/rust/core-graphics/src/font.rs
@@ -27,27 +27,27 @@ pub type CGFontRef = *const __CGFont;
pub struct CGFont {
obj: CGFontRef,
}
unsafe impl Send for CGFont {}
unsafe impl Sync for CGFont {}
impl Serialize for CGFont {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
+ 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: &mut D) -> Result<Self, D::Error> where D: Deserializer {
+ 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::invalid_value("Couldn't find a font with that PostScript name!")
+ de::Error::custom("Couldn't find a font with that PostScript name!")
})
}
}
impl Clone for CGFont {
#[inline]
fn clone(&self) -> CGFont {
unsafe {
--- a/third_party/rust/core-text/.cargo-checksum.json
+++ b/third_party/rust/core-text/.cargo-checksum.json
@@ -1,1 +1,1 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"6aad961651169d31d79c0595624d1777b5c4cbb4cf2bed9a126c7e72d29411fd","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"fd225e94253c22c5a1ad569e5e2db7e0219ed9b0bc30d8a2d4f3a5e55fa2d533","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":"9703f459a41e622b15ca612dbc5fa4b30b6545a32864a83e0fdc538cfa08969c"}
\ No newline at end of file
+{"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"}
\ No newline at end of file
--- a/third_party/rust/core-text/Cargo.toml
+++ b/third_party/rust/core-text/Cargo.toml
@@ -1,14 +1,14 @@
[package]
name = "core-text"
-version = "3.0.0"
+version = "4.0.0"
authors = ["The Servo Project Developers"]
description = "Bindings to the Core Text framework."
license = "MIT/Apache-2.0"
repository = "https://github.com/servo/core-text-rs"
[dependencies]
libc = "0.2"
[target.x86_64-apple-darwin.dependencies]
core-foundation = "0.3"
-core-graphics = "0.6"
+core-graphics = "0.7"
deleted file mode 100644
--- a/third_party/rust/dwrote/.cargo-checksum.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"172610b244a5ee8a8e2f1f045058b8abf9291d84bb76bf8779d2fd420419c2d6","Cargo.toml":"81966f2284a9e3d1a08d4dd846ae4a0e65a97c90d11d4d859ad13b00e56108f4","README.md":"d69d75705e2582721cbfb2d3b4b2af052c71679057a0b2ac53a22c03f1755bba","build.rs":"b40ce243f62825724b4a45092a8e658d71fa952a6840b83f3bee58e719a56d3b","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":"77255bb083c75139180c7ba775e2d2b4d73a0d07b342aad3e8fff56b7927e1ca","src/rendering_params.rs":"be1d1c433f76926c285d8ecdb747c5d9cc6a6c10c1a1890c0760cd99755ed471","src/test.rs":"d77e45f8866abeea070cbbafd4cbde62d875292e8d191310a04c70091978547c","src/types.rs":"784235c15d61fb0d001373575169aa473c92af18dcbc1709a5b2bbaa3a7ceb22"},"package":"5998238340a4625b5e1cf52341bd330c5ad91a39a41527ed8af20f95a258a96c"}
\ No newline at end of file
deleted file mode 100644
--- a/third_party/rust/dwrote/Cargo.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-[package]
-name = "dwrote"
-description = "Lightweight binding to DirectWrite."
-repository = "https://github.com/vvuk/dwrote-rs"
-license = "MPL-2.0"
-version = "0.1.7"
-authors = ["Vladimir Vukicevic <vladimir@pobox.com>"]
-build = "build.rs"
-
-[lib]
-name = "dwrote"
-
-[features]
-default = ["codegen"]
-nightly = ["serde/unstable"]
-codegen = ["serde_codegen", "serde_codegen/with-syntex"]
-
-[dependencies]
-libc = "0.2"
-lazy_static = "0.2"
-winapi = "0.2"
-kernel32-sys = "0.2"
-gdi32-sys = "0.2"
-serde = "0.8"
-serde_derive = {version = "0.8", optional = true}
-
-[build-dependencies.serde_codegen]
-version = "0.8"
-default_features = false
-optional = true
deleted file mode 100644
--- a/third_party/rust/dwrote/src/lib.rs
+++ /dev/null
@@ -1,141 +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/. */
-
-#![cfg_attr(feature = "serde_derive", feature(proc_macro, rustc_attrs, structural_match))]
-#![allow(non_upper_case_globals)]
-
-#[cfg(feature = "serde_derive")]
-#[macro_use]
-extern crate serde_derive;
-
-#[macro_use]
-extern crate lazy_static;
-#[macro_use(DEFINE_GUID)]
-extern crate winapi;
-extern crate gdi32;
-extern crate kernel32;
-extern crate libc;
-extern crate serde;
-
-#[cfg(feature = "serde_codegen")]
-include!(concat!(env!("OUT_DIR"), "/types.rs"));
-
-#[cfg(feature = "serde_derive")]
-include!("types.rs");
-
-use winapi::DWRITE_FACTORY_TYPE_SHARED;
-use winapi::IDWriteFactory;
-use winapi::IDWriteRenderingParams;
-use std::ffi::CString;
-
-use comptr::ComPtr;
-use winapi::S_OK;
-
-mod comptr;
-mod helpers;
-use helpers::ToWide;
-use std::os::raw::c_void;
-
-#[cfg(test)]
-mod test;
-
-// We still use the DWrite structs for things like metrics; re-export them
-// here
-pub use winapi::DWRITE_FONT_METRICS as FontMetrics;
-pub use winapi::DWRITE_GLYPH_OFFSET as GlyphOffset;
-pub use winapi::{DWRITE_MATRIX, DWRITE_GLYPH_RUN};
-pub use winapi::{DWRITE_RENDERING_MODE_DEFAULT,
- DWRITE_RENDERING_MODE_ALIASED,
- DWRITE_RENDERING_MODE_GDI_CLASSIC,
- DWRITE_RENDERING_MODE_GDI_NATURAL,
- DWRITE_RENDERING_MODE_NATURAL,
- DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC,
- DWRITE_RENDERING_MODE_OUTLINE,
- DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC,
- DWRITE_RENDERING_MODE_CLEARTYPE_GDI_NATURAL,
- DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL,
- DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC};
-pub use winapi::{DWRITE_MEASURING_MODE_NATURAL,
- DWRITE_MEASURING_MODE_GDI_CLASSIC,
- DWRITE_MEASURING_MODE_GDI_NATURAL};
-pub use winapi::{DWRITE_FONT_SIMULATIONS_NONE,
- DWRITE_FONT_SIMULATIONS_BOLD,
- DWRITE_FONT_SIMULATIONS_OBLIQUE};
-pub use winapi::{DWRITE_TEXTURE_ALIASED_1x1, DWRITE_TEXTURE_CLEARTYPE_3x1};
-pub use winapi::{DWRITE_RENDERING_MODE};
-pub use winapi::{DWRITE_MEASURING_MODE};
-pub use winapi::{DWRITE_TEXTURE_TYPE};
-
-#[macro_use] mod com_helpers;
-
-mod bitmap_render_target; pub use bitmap_render_target::BitmapRenderTarget;
-mod font; pub use font::Font;
-mod font_collection; pub use font_collection::FontCollection;
-mod font_face; pub use font_face::FontFace;
-mod font_family; pub use font_family::FontFamily;
-mod font_file; pub use font_file::FontFile;
-mod gdi_interop; pub use gdi_interop::GdiInterop;
-mod rendering_params; pub use rendering_params::RenderingParams;
-mod glyph_run_analysis; pub use glyph_run_analysis::GlyphRunAnalysis;
-
-// This is an internal implementation of FontFileLoader, for our utility
-// functions. We don't wrap the DWriteFontFileLoader interface and
-// related things.
-mod font_file_loader_impl;
-
-DEFINE_GUID!{UuidOfIDWriteFactory, 0xb859ee5a, 0xd838, 0x4b5b, 0xa2, 0xe8, 0x1a, 0xdc, 0x7d, 0x93, 0xdb, 0x48}
-
-unsafe impl Sync for ComPtr<IDWriteFactory> { }
-unsafe impl Sync for ComPtr<IDWriteRenderingParams> {}
-
-lazy_static! {
- static ref DWRITE_FACTORY_RAW_PTR: usize = {
- unsafe {
- type DWriteCreateFactoryType = extern "system" fn(winapi::DWRITE_FACTORY_TYPE, winapi::REFIID, *mut *mut winapi::IUnknown) -> winapi::HRESULT;
-
- let dwrite_dll = kernel32::LoadLibraryW("dwrite.dll".to_wide_null().as_ptr());
- assert!(!dwrite_dll.is_null());
- let create_factory_name = CString::new("DWriteCreateFactory").unwrap();
- let dwrite_create_factory_ptr =
- kernel32::GetProcAddress(dwrite_dll, create_factory_name.as_ptr() as winapi::LPCSTR);
- assert!(!dwrite_create_factory_ptr.is_null());
-
- let dwrite_create_factory =
- mem::transmute::<*const c_void, DWriteCreateFactoryType>(dwrite_create_factory_ptr);
-
- let mut factory: ComPtr<IDWriteFactory> = ComPtr::new();
- let hr = dwrite_create_factory(
- DWRITE_FACTORY_TYPE_SHARED,
- &UuidOfIDWriteFactory,
- factory.getter_addrefs());
- assert!(hr == S_OK);
- factory.forget() as usize
- }
- };
-
- static ref DEFAULT_DWRITE_RENDERING_PARAMS_RAW_PTR: usize = {
- unsafe {
- let mut default_rendering_params: ComPtr<IDWriteRenderingParams> = ComPtr::new();
- let hr = (*DWriteFactory()).CreateRenderingParams(default_rendering_params.getter_addrefs());
- assert!(hr == S_OK);
-
- default_rendering_params.forget() as usize
- }
- };
-
-} // end lazy static
-
-// FIXME vlad would be nice to return, say, FactoryPtr<IDWriteFactory>
-// that has a DerefMut impl, so that we can write
-// DWriteFactory().SomeOperation() as opposed to
-// (*DWriteFactory()).SomeOperation()
-#[allow(non_snake_case)]
-fn DWriteFactory() -> *mut IDWriteFactory {
- (*DWRITE_FACTORY_RAW_PTR) as *mut IDWriteFactory
-}
-
-#[allow(non_snake_case)]
-fn DefaultDWriteRenderParams() -> *mut IDWriteRenderingParams {
- (*DEFAULT_DWRITE_RENDERING_PARAMS_RAW_PTR) as *mut IDWriteRenderingParams
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/.cargo-checksum.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"118514fd9c4958df0d25584cda4917186c46011569f55ef350530c1ad3fbdb48",".travis.yml":"13d3e5a7bf83b04c8e8cfa14f0297bd8366d68391d977dd547f64707dffc275a","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"34d79e1ddea3e2169c03b1f8ad4c3d863d2029b59423030112b2853fced70498","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"7a5648f52b09d3213348177860171d4f19b0fdda55e8fed7c04dafcb0ed9c215","src/approxeq.rs":"2987e046c90d948b6c7d7ddba52d10c8b7520d71dc0a50dbe7665de128d7410e","src/length.rs":"6e30abd125304985a7ae95dfb7dd92631053152a589b89df6e5c1879e91ecafa","src/lib.rs":"3ad04d3c1a18f697c8d28a1fbe871a4c75e0e957008745c6a4990e8fb07663d1","src/macros.rs":"1e999b322c2093c9c945386d15c3e95bd657c06b02e78235556db0bdbd162318","src/matrix2d.rs":"78d3b44e46be2b9c0ed1d98473cbbed78941cbf8cc76266be9f420966f1c1607","src/matrix4d.rs":"c3325f30a7a35575104a6b02fd0740d5be22e032881808550f28d22ea8eef625","src/num.rs":"62286aa642ce3afa7ebd950f50bf2197d8722907f2e23a2e2ea6690484d8b250","src/point.rs":"a585ad405a69505792efb624f0c0e6345b92b27a2c77e9a4366d6192ac914ef0","src/rect.rs":"d9bc96b8a3bc52ab2d49b53c4687e13230ab5d2920ea60e4070dea153489a633","src/scale_factor.rs":"3cffe0e88f035b8b5c9b27b105fb2825db5f317d7e067c88ee5d51cac4e6e583","src/side_offsets.rs":"f85526a421ffda63ff01a3478d4162c8717eef68e942acfa2fd9a1adee02ebb2","src/size.rs":"ef95a114f389a357ef940f42789e2cdbdbbdf4ae6993a80a74cc2c9d10c891c9","src/trig.rs":"6b207980052d13c625272f2a70a22f7741b59513c2a4882385926f497c763a63"},"package":"f93a556290e09f379cbfaa4f75ac52a72a3d2deb7d04076f312cdb2e6acba28e"}
\ No newline at end of file
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Cargo.lock
-/target/
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/.travis.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-language: rust
-
-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"
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/COPYRIGHT
+++ /dev/null
@@ -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.
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/Cargo.toml
+++ /dev/null
@@ -1,22 +0,0 @@
-[package]
-name = "euclid"
-version = "0.10.5"
-authors = ["The Servo Project Developers"]
-description = "Geometry primitives"
-documentation = "http://doc.servo.org/euclid/"
-repository = "https://github.com/servo/euclid"
-license = "MIT / Apache-2.0"
-
-[features]
-unstable = []
-
-[dependencies]
-heapsize = "0.3"
-rustc-serialize = "0.3.2"
-num-traits = {version = "0.1.32", default-features = false}
-log = "0.3.1"
-serde = "0.8"
-
-[dev-dependencies]
-rand = "0.3.7"
-serde_test = "0.8"
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/LICENSE-APACHE
+++ /dev/null
@@ -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.
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/LICENSE-MIT
+++ /dev/null
@@ -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.
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# euclid
-
-This is a small library for geometric types.
-
-[Documentation](http://doc.servo.org/euclid/)
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/approxeq.rs
+++ /dev/null
@@ -1,47 +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;
-}
-
-impl ApproxEq<f32> for f32 {
- #[inline]
- fn approx_epsilon() -> f32 { 1.0e-6 }
-
- #[inline]
- fn approx_eq(&self, other: &f32) -> bool {
- self.approx_eq_eps(other, &1.0e-6)
- }
-
- #[inline]
- fn approx_eq_eps(&self, other: &f32, approx_epsilon: &f32) -> bool {
- (*self - *other).abs() < *approx_epsilon
- }
-}
-
-
-impl ApproxEq<f64> for f64 {
- #[inline]
- fn approx_epsilon() -> f64 { 1.0e-6 }
-
- #[inline]
- fn approx_eq(&self, other: &f64) -> bool {
- self.approx_eq_eps(other, &1.0e-6)
- }
-
- #[inline]
- fn approx_eq_eps(&self, other: &f64, approx_epsilon: &f64) -> bool {
- (*self - *other).abs() < *approx_epsilon
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/length.rs
+++ /dev/null
@@ -1,448 +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 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.
-#[derive(RustcDecodable, RustcEncodable)]
-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: &mut D) -> Result<Length<T, Unit>,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: &mut S) -> Result<(),S::Error> where S: Serializer {
- self.0.serialize(serializer)
- }
-}
-
-impl<T, Unit> Length<T, Unit> {
- pub fn new(x: T) -> Length<T, Unit> {
- 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: &Length<T, Unit>) -> bool { self.get().eq(&other.get()) }
-}
-
-impl<Unit, T: Clone + PartialOrd> PartialOrd for Length<T, Unit> {
- fn partial_cmp(&self, other: &Length<T, Unit>) -> 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: &Length<T, Unit>) -> Ordering { self.get().cmp(&other.get()) }
-}
-
-impl<Unit, T: Zero> Zero for Length<T, Unit> {
- fn zero() -> Length<T, Unit> {
- Length::new(Zero::zero())
- }
-}
-
-#[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);
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/lib.rs
+++ /dev/null
@@ -1,110 +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 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:
-//!
-//! ```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;
-
-#[macro_use]
-extern crate log;
-extern crate rustc_serialize;
-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 matrix2d::{Matrix2D, TypedMatrix2D};
-pub use matrix4d::{Matrix4D, TypedMatrix4D};
-pub use point::{
- Point2D, TypedPoint2D,
- Point3D, TypedPoint3D,
- Point4D, TypedPoint4D,
-};
-pub use rect::{Rect, TypedRect};
-pub use side_offsets::{SideOffsets2D, TypedSideOffsets2D};
-#[cfg(feature = "unstable")] pub use side_offsets::SideOffsets2DSimdI32;
-pub use size::{Size2D, TypedSize2D};
-
-pub mod approxeq;
-pub mod length;
-#[macro_use]
-mod macros;
-pub mod matrix2d;
-pub mod matrix4d;
-pub mod num;
-pub mod point;
-pub mod rect;
-pub mod scale_factor;
-pub mod side_offsets;
-pub mod size;
-mod trig;
-
-/// The default unit.
-#[derive(Clone, Copy, RustcDecodable, RustcEncodable)]
-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>;
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/macros.rs
+++ /dev/null
@@ -1,86 +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,)+
- }
- ) => (
- $(#[$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: &mut 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: &mut S) -> Result<(), 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);)+
- }
- }
- )
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/matrix2d.rs
+++ /dev/null
@@ -1,404 +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 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,
- /// useful to represent 2d transformations.
- ///
- /// Matrices can be parametrized over the source and destination units, to describe a
- /// transformation from a space to another.
- /// For example, TypedMatrix2D<f32, WordSpace, ScreenSpace>::transform_point4d
- /// takes a TypedPoint2D<f32, WordSpace> and returns a TypedPoint2D<f32, ScreenSpace>.
- ///
- /// Matrices 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 appled after.
- pub struct TypedMatrix2D<T, Src, Dst> {
- pub m11: T, pub m12: T,
- pub m21: T, pub m22: T,
- pub m31: T, pub m32: T,
- }
-}
-
-/// The default 2d matrix type with no units.
-pub type Matrix2D<T> = TypedMatrix2D<T, UnknownUnit, UnknownUnit>;
-
-impl<T: Copy, Src, Dst> TypedMatrix2D<T, Src, Dst> {
- /// Create a matrix specifying its components in row-major order.
- pub fn row_major(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> TypedMatrix2D<T, Src, Dst> {
- TypedMatrix2D {
- m11: m11, m12: m12,
- m21: m21, m22: m22,
- m31: m31, m32: m32,
- _unit: PhantomData,
- }
- }
-
- /// Create a matrix specifying its components in column-major order.
- pub fn column_major(m11: T, m21: T, m31: T, m12: T, m22: T, m32: T) -> TypedMatrix2D<T, Src, Dst> {
- TypedMatrix2D {
- m11: m11, m12: m12,
- m21: m21, m22: m22,
- m31: m31, m32: m32,
- _unit: PhantomData,
- }
- }
-
- /// Returns an array containing this matrix's terms in row-major order (the order
- /// in which the matrix 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 matrix'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
- ]
- }
-
- /// Drop the units, preserving only the numeric value.
- pub fn to_untyped(&self) -> Matrix2D<T> {
- Matrix2D::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: &Matrix2D<T>) -> TypedMatrix2D<T, Src, Dst> {
- TypedMatrix2D::row_major(
- p.m11, p.m12,
- p.m21, p.m22,
- p.m31, p.m32
- )
- }
-}
-
-impl<T, Src, Dst> TypedMatrix2D<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 {
-
- pub fn identity() -> TypedMatrix2D<T, Src, Dst> {
- let (_0, _1) = (Zero::zero(), One::one());
- TypedMatrix2D::row_major(
- _1, _0,
- _0, _1,
- _0, _0
- )
- }
-
- /// Returns the multiplication of the two matrices such that mat's transformation
- /// applies after self's transformation.
- pub fn post_mul<NewDst>(&self, mat: &TypedMatrix2D<T, Dst, NewDst>) -> TypedMatrix2D<T, Src, NewDst> {
- TypedMatrix2D::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.
- pub fn pre_mul<NewSrc>(&self, mat: &TypedMatrix2D<T, NewSrc, Src>) -> TypedMatrix2D<T, NewSrc, Dst> {
- mat.post_mul(self)
- }
-
- /// Returns a translation matrix.
- pub fn create_translation(x: T, y: T) -> TypedMatrix2D<T, Src, Dst> {
- let (_0, _1): (T, T) = (Zero::zero(), One::one());
- TypedMatrix2D::row_major(
- _1, _0,
- _0, _1,
- x, y
- )
- }
-
- /// Applies a translation after self's transformation and returns the resulting matrix.
- pub fn post_translated(&self, x: T, y: T) -> TypedMatrix2D<T, Src, Dst> {
- self.post_mul(&TypedMatrix2D::create_translation(x, y))
- }
-
- /// Applies a translation before self's transformation and returns the resulting matrix.
- pub fn pre_translated(&self, x: T, y: T) -> TypedMatrix2D<T, Src, Dst> {
- self.pre_mul(&TypedMatrix2D::create_translation(x, y))
- }
-
- /// Returns a scale matrix.
- pub fn create_scale(x: T, y: T) -> TypedMatrix2D<T, Src, Dst> {
- let _0 = Zero::zero();
- TypedMatrix2D::row_major(
- x, _0,
- _0, y,
- _0, _0
- )
- }
-
- /// Applies a scale after self's transformation and returns the resulting matrix.
- pub fn post_scaled(&self, x: T, y: T) -> TypedMatrix2D<T, Src, Dst> {
- self.post_mul(&TypedMatrix2D::create_scale(x, y))
- }
-
- /// Applies a scale before self's transformation and returns the resulting matrix.
- pub fn pre_scaled(&self, x: T, y: T) -> TypedMatrix2D<T, Src, Dst> {
- TypedMatrix2D::row_major(
- self.m11 * x, self.m12,
- self.m21, self.m22 * y,
- self.m31, self.m32
- )
- }
-
- /// Returns a rotation matrix.
- pub fn create_rotation(theta: Radians<T>) -> TypedMatrix2D<T, Src, Dst> {
- let _0 = Zero::zero();
- let cos = theta.get().cos();
- let sin = theta.get().sin();
- TypedMatrix2D::row_major(
- cos, _0 - sin,
- sin, cos,
- _0, _0
- )
- }
-
- /// Applies a rotation after self's transformation and returns the resulting matrix.
- pub fn post_rotated(&self, theta: Radians<T>) -> TypedMatrix2D<T, Src, Dst> {
- self.post_mul(&TypedMatrix2D::create_rotation(theta))
- }
-
- /// Applies a rotation after self's transformation and returns the resulting matrix.
- pub fn pre_rotated(&self, theta: Radians<T>) -> TypedMatrix2D<T, Src, Dst> {
- self.pre_mul(&TypedMatrix2D::create_rotation(theta))
- }
-
- /// Returns the given point transformed by this matrix.
- #[inline]
- 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 a rectangle that encompasses the result of transforming the given rectangle by this
- /// matrix.
- #[inline]
- 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 matrix.
- pub fn determinant(&self) -> T {
- self.m11 * self.m22 - self.m12 * self.m21
- }
-
- /// Returns the inverse matrix if possible.
- pub fn inverse(&self) -> Option<TypedMatrix2D<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(TypedMatrix2D::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 matrix with a different destination unit.
- #[inline]
- pub fn with_destination<NewDst>(&self) -> TypedMatrix2D<T, Src, NewDst> {
- TypedMatrix2D::row_major(
- self.m11, self.m12,
- self.m21, self.m22,
- self.m31, self.m32,
- )
- }
-
- /// Returns the same matrix with a different source unit.
- #[inline]
- pub fn with_source<NewSrc>(&self) -> TypedMatrix2D<T, NewSrc, Dst> {
- TypedMatrix2D::row_major(
- self.m11, self.m12,
- self.m21, self.m22,
- self.m31, self.m32,
- )
- }
-}
-
-impl<T: ApproxEq<T>, Src, Dst> TypedMatrix2D<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 TypedMatrix2D<T, Src, Dst> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- 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 = Matrix2D<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_translated(1.0, 2.0);
- let t3 = Mat::identity().post_translated(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_rotated(rad(FRAC_PI_2));
- let r3 = Mat::identity().post_rotated(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_scaled(2.0, 3.0);
- let s3 = Mat::identity().post_scaled(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 = Matrix2D::identity().post_scaled(1.0, 2.0).post_translated(1.0, 2.0);
- let m2 = Matrix2D::identity().pre_translated(1.0, 2.0).pre_scaled(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::<Matrix2D<f32>>(), 6*size_of::<f32>());
- assert_eq!(size_of::<Matrix2D<f64>>(), 6*size_of::<f64>());
- }
-}
\ No newline at end of file
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/matrix4d.rs
+++ /dev/null
@@ -1,797 +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, TypedPoint4D};
-use rect::TypedRect;
-use matrix2d::TypedMatrix2D;
-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 4 by 4 matrix stored in row-major order in memory, useful to represent
- /// 3d transformations.
- ///
- /// Matrices can be parametrized over the source and destination units, to describe a
- /// transformation from a space to another.
- /// For example, TypedMatrix4D<f32, WordSpace, ScreenSpace>::transform_point4d
- /// takes a TypedPoint4D<f32, WordSpace> and returns a TypedPoint4D<f32, ScreenSpace>.
- ///
- /// Matrices 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 appled after.
- pub struct TypedMatrix4D<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 matrix type with no units.
-pub type Matrix4D<T> = TypedMatrix4D<T, UnknownUnit, UnknownUnit>;
-
-impl<T, Src, Dst> TypedMatrix4D<T, Src, Dst> {
- /// Create a matrix 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)
- -> TypedMatrix4D<T, Src, Dst> {
- TypedMatrix4D {
- 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 matrix 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)
- -> TypedMatrix4D<T, Src, Dst> {
- TypedMatrix4D {
- 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> TypedMatrix4D<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 matrix 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) -> TypedMatrix4D<T, Src, Dst> {
- let (_0, _1): (T, T) = (Zero::zero(), One::one());
- TypedMatrix4D::row_major(
- m11, m12, _0, _0,
- m21, m22, _0, _0,
- _0, _0, _1, _0,
- m41, m42, _0, _1
- )
- }
-
- /// Create an orthogonal projection matrix.
- pub fn ortho(left: T, right: T,
- bottom: T, top: T,
- near: T, far: T) -> TypedMatrix4D<T, Src, Dst> {
- 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;
- TypedMatrix4D::row_major(
- _2 / (right - left), _0 , _0 , _0,
- _0 , _2 / (top - bottom), _0 , _0,
- _0 , _0 , -_2 / (far - near), _0,
- tx , ty , tz , _1
- )
- }
-
- #[inline]
- pub fn identity() -> TypedMatrix4D<T, Src, Dst> {
- let (_0, _1): (T, T) = (Zero::zero(), One::one());
- TypedMatrix4D::row_major(
- _1, _0, _0, _0,
- _0, _1, _0, _0,
- _0, _0, _1, _0,
- _0, _0, _0, _1
- )
- }
-
- /// Returns true if this matrix can be represented with a TypedMatrix2D.
- ///
- /// See https://drafts.csswg.org/css-transforms/#2d-matrix
- #[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 matrix picking the relevent terms from this matrix.
- ///
- /// This method assumes that self represents a 2d transformation, callers
- /// should check that self.is_2d() returns true beforehand.
- pub fn to_2d(&self) -> TypedMatrix2D<T, Src, Dst> {
- TypedMatrix2D::row_major(
- self.m11, self.m12,
- self.m21, self.m22,
- self.m41, self.m42
- )
- }
-
- pub fn approx_eq(&self, other: &TypedMatrix4D<T, Src, Dst>) -> 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 matrix with a different destination unit.
- #[inline]
- pub fn with_destination<NewDst>(&self) -> TypedMatrix4D<T, Src, NewDst> {
- TypedMatrix4D::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 matrix with a different source unit.
- #[inline]
- pub fn with_source<NewSrc>(&self) -> TypedMatrix4D<T, NewSrc, Dst> {
- TypedMatrix4D::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) -> Matrix4D<T> {
- Matrix4D::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: &Matrix4D<T>) -> Self {
- TypedMatrix4D::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: &TypedMatrix4D<T, Dst, NewDst>) -> TypedMatrix4D<T, Src, NewDst> {
- TypedMatrix4D::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: &TypedMatrix4D<T, NewSrc, Src>) -> TypedMatrix4D<T, NewSrc, Dst> {
- mat.post_mul(self)
- }
-
- /// Returns the inverse matrix if possible.
- pub fn inverse(&self) -> Option<TypedMatrix4D<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 matrix types.
- let m = TypedMatrix4D::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 matrix.
- 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 matrix's component by a scalar and returns the result.
- pub fn mul_s(&self, x: T) -> TypedMatrix4D<T, Src, Dst> {
- TypedMatrix4D::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 matrix from a ScaleFactor.
- pub fn from_scale_factor(scale: ScaleFactor<T, Src, Dst>) -> TypedMatrix4D<T, Src, Dst> {
- TypedMatrix4D::create_scale(scale.get(), scale.get(), scale.get())
- }
-
- /// Returns the given 2d point 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_point(&self, p: &TypedPoint2D<T, Src>) -> TypedPoint2D<T, Dst> {
- self.transform_point4d(&TypedPoint4D::new(p.x, p.y, Zero::zero(), One::one())).to_2d()
- }
-
- /// Returns the given 3d point 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_point3d(&self, p: &TypedPoint3D<T, Src>) -> TypedPoint3D<T, Dst> {
- self.transform_point4d(&TypedPoint4D::new(p.x, p.y, p.z, One::one())).to_3d()
- }
-
- /// Returns the given 4d point 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_point4d(&self, p: &TypedPoint4D<T, Src>) -> TypedPoint4D<T, Dst> {
- let x = p.x * self.m11 + p.y * self.m21 + p.z * self.m31 + p.w * self.m41;
- let y = p.x * self.m12 + p.y * self.m22 + p.z * self.m32 + p.w * self.m42;
- let z = p.x * self.m13 + p.y * self.m23 + p.z * self.m33 + p.w * self.m43;
- let w = p.x * self.m14 + p.y * self.m24 + p.z * self.m34 + p.w * self.m44;
- TypedPoint4D::new(x, y, z, w)
- }
-
- /// Returns a rectangle that encompasses the result of transforming the given rectangle by this
- /// matrix.
- 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()),
- ])
- }
-
- /// Create a 3d translation matrix
- pub fn create_translation(x: T, y: T, z: T) -> TypedMatrix4D<T, Src, Dst> {
- let (_0, _1): (T, T) = (Zero::zero(), One::one());
- TypedMatrix4D::row_major(
- _1, _0, _0, _0,
- _0, _1, _0, _0,
- _0, _0, _1, _0,
- x, y, z, _1
- )
- }
-
- /// Returns a matrix with a translation applied before self's transformation.
- pub fn pre_translated(&self, x: T, y: T, z: T) -> TypedMatrix4D<T, Src, Dst> {
- self.pre_mul(&TypedMatrix4D::create_translation(x, y, z))
- }
-
- /// Returns a matrix with a translation applied after self's transformation.
- pub fn post_translated(&self, x: T, y: T, z: T) -> TypedMatrix4D<T, Src, Dst> {
- self.post_mul(&TypedMatrix4D::create_translation(x, y, z))
- }
-
- /// Create a 3d scale matrix
- pub fn create_scale(x: T, y: T, z: T) -> TypedMatrix4D<T, Src, Dst> {
- let (_0, _1): (T, T) = (Zero::zero(), One::one());
- TypedMatrix4D::row_major(
- x, _0, _0, _0,
- _0, y, _0, _0,
- _0, _0, z, _0,
- _0, _0, _0, _1
- )
- }
-
- /// Returns a matrix with a scale applied before self's transformation.
- pub fn pre_scaled(&self, x: T, y: T, z: T) -> TypedMatrix4D<T, Src, Dst> {
- TypedMatrix4D::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 matrix with a scale applied after self's transformation.
- pub fn post_scaled(&self, x: T, y: T, z: T) -> TypedMatrix4D<T, Src, Dst> {
- self.post_mul(&TypedMatrix4D::create_scale(x, y, z))
- }
-
- /// Create a 3d rotation matrix from an angle / axis.
- /// The supplied axis must be normalized.
- pub fn create_rotation(x: T, y: T, z: T, theta: Radians<T>) -> TypedMatrix4D<T, Src, Dst> {
- 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();
-
- TypedMatrix4D::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 matrix with a rotation applied after self's transformation.
- pub fn post_rotated(&self, x: T, y: T, z: T, theta: Radians<T>) -> TypedMatrix4D<T, Src, Dst> {
- self.post_mul(&TypedMatrix4D::create_rotation(x, y, z, theta))
- }
-
- /// Returns a matrix with a rotation applied before self's transformation.
- pub fn pre_rotated(&self, x: T, y: T, z: T, theta: Radians<T>) -> TypedMatrix4D<T, Src, Dst> {
- self.pre_mul(&TypedMatrix4D::create_rotation(x, y, z, theta))
- }
-
- /// Create a 2d skew matrix.
- ///
- /// See https://drafts.csswg.org/css-transforms/#funcdef-skew
- pub fn create_skew(alpha: Radians<T>, beta: Radians<T>) -> TypedMatrix4D<T, Src, Dst> {
- let (_0, _1): (T, T) = (Zero::zero(), One::one());
- let (sx, sy) = (beta.get().tan(), alpha.get().tan());
- TypedMatrix4D::row_major(
- _1, sx, _0, _0,
- sy, _1, _0, _0,
- _0, _0, _1, _0,
- _0, _0, _0, _1
- )
- }
-
- /// Create a simple perspective projection matrix
- pub fn create_perspective(d: T) -> TypedMatrix4D<T, Src, Dst> {
- let (_0, _1): (T, T) = (Zero::zero(), One::one());
- TypedMatrix4D::row_major(
- _1, _0, _0, _0,
- _0, _1, _0, _0,
- _0, _0, _1, -_1 / d,
- _0, _0, _0, _1
- )
- }
-}
-
-impl<T: Copy, Src, Dst> TypedMatrix4D<T, Src, Dst> {
- /// Returns an array containing this matrix's terms in row-major order (the order
- /// in which the matrix 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 matrix'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 matrix'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 matrix'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]
- ]
- }
-}
-
-impl<T: Copy + fmt::Debug, Src, Dst> fmt::Debug for TypedMatrix4D<T, Src, Dst> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.to_row_major_array().fmt(f)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use approxeq::ApproxEq;
- use matrix2d::Matrix2D;
- use point::{Point2D, Point3D, Point4D};
- use Radians;
- use super::*;
-
- use std::f32::consts::FRAC_PI_2;
-
- type Mf32 = Matrix4D<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_translated(1.0, 2.0, 3.0);
- let t3 = Mf32::identity().post_translated(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_point(&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(), Matrix2D::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_rotated(0.0, 0.0, 1.0, rad(FRAC_PI_2));
- let r3 = Mf32::identity().post_rotated(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_point(&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(&Matrix2D::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_scaled(2.0, 3.0, 4.0);
- let s3 = Mf32::identity().post_scaled(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_point(&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(), Matrix2D::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_point(&p1);
- assert!(p2.eq(&Point2D::new(1100.0, 2200.0)));
-
- let p3 = m2.transform_point(&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 = Matrix4D::identity().post_scaled(1.0, 2.0, 3.0).post_translated(1.0, 2.0, 3.0);
- let m2 = Matrix4D::identity().pre_translated(1.0, 2.0, 3.0).pre_scaled(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::<Matrix4D<f32>>(), 16*size_of::<f32>());
- assert_eq!(size_of::<Matrix4D<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 = Point4D::new(1.0, 3.0, 5.0, 1.0);
- let p1 = m2.pre_mul(&m1).transform_point4d(&p);
- let p2 = m2.transform_point4d(&m1.transform_point4d(&p));
- assert!(p1.approx_eq(&p2));
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/num.rs
+++ /dev/null
@@ -1,66 +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; }
-
-impl Round for f32 { fn round(self) -> Self { self.round() } }
-impl Round for f64 { fn round(self) -> Self { self.round() } }
-impl Round for i16 { fn round(self) -> Self { self } }
-impl Round for u16 { fn round(self) -> Self { self } }
-impl Round for i32 { fn round(self) -> Self { self } }
-impl Round for i64 { fn round(self) -> Self { self } }
-impl Round for u32 { fn round(self) -> Self { self } }
-impl Round for u64 { fn round(self) -> Self { self } }
-impl Round for usize { fn round(self) -> Self { self } }
-impl Round for isize { fn round(self) -> Self { self } }
-
-impl Floor for f32 { fn floor(self) -> Self { self.floor() } }
-impl Floor for f64 { fn floor(self) -> Self { self.floor() } }
-impl Floor for i16 { fn floor(self) -> Self { self } }
-impl Floor for u16 { fn floor(self) -> Self { self } }
-impl Floor for i32 { fn floor(self) -> Self { self } }
-impl Floor for i64 { fn floor(self) -> Self { self } }
-impl Floor for u32 { fn floor(self) -> Self { self } }
-impl Floor for u64 { fn floor(self) -> Self { self } }
-impl Floor for usize { fn floor(self) -> Self { self } }
-impl Floor for isize { fn floor(self) -> Self { self } }
-
-impl Ceil for f32 { fn ceil(self) -> Self { self.ceil() } }
-impl Ceil for f64 { fn ceil(self) -> Self { self.ceil() } }
-impl Ceil for i16 { fn ceil(self) -> Self { self } }
-impl Ceil for u16 { fn ceil(self) -> Self { self } }
-impl Ceil for i32 { fn ceil(self) -> Self { self } }
-impl Ceil for i64 { fn ceil(self) -> Self { self } }
-impl Ceil for u32 { fn ceil(self) -> Self { self } }
-impl Ceil for u64 { fn ceil(self) -> Self { self } }
-impl Ceil for usize { fn ceil(self) -> Self { self } }
-impl Ceil for isize { fn ceil(self) -> Self { self } }
-
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/point.rs
+++ /dev/null
@@ -1,939 +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 std::fmt;
-use std::ops::{Add, Neg, Mul, Sub, Div};
-use std::marker::PhantomData;
-
-define_matrix! {
- /// A 2d Point tagged with a unit.
- #[derive(RustcDecodable, RustcEncodable)]
- 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 zero() -> TypedPoint2D<T, U> {
- TypedPoint2D::new(Zero::zero(), Zero::zero())
- }
-
- /// Convert into a 3d point.
- #[inline]
- pub fn to_3d(&self) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(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) -> TypedPoint2D<T, U> {
- 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>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(x.0, y.0)
- }
-
- /// 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> {
- TypedPoint2D::new(self.x, self.y)
- }
-
- /// Tag a unitless value with units.
- #[inline]
- pub fn from_untyped(p: &Point2D<T>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(p.x, p.y)
- }
-
- #[inline]
- pub fn to_array(&self) -> [T; 2] {
- [self.x, self.y]
- }
-}
-
-impl<T, U> TypedPoint2D<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: TypedPoint2D<T, U>) -> 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: TypedPoint2D<T, U>) -> T {
- self.x * other.y - self.y * other.x
- }
-}
-
-impl<T: Copy + Add<T, Output=T>, U> Add for TypedPoint2D<T, U> {
- type Output = TypedPoint2D<T, U>;
- fn add(self, other: TypedPoint2D<T, U>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x + other.x, self.y + other.y)
- }
-}
-
-impl<T: Copy + Add<T, Output=T>, U> Add<TypedSize2D<T, U>> for TypedPoint2D<T, U> {
- type Output = TypedPoint2D<T, U>;
- fn add(self, other: TypedSize2D<T, U>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x + other.width, self.y + other.height)
- }
-}
-
-impl<T: Copy + Add<T, Output=T>, U> TypedPoint2D<T, U> {
- pub fn add_size(&self, other: &TypedSize2D<T, U>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x + other.width, self.y + other.height)
- }
-}
-
-impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedPoint2D<T, U> {
- type Output = TypedPoint2D<T, U>;
- fn sub(self, other: TypedPoint2D<T, U>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x - other.x, self.y - other.y)
- }
-}
-
-impl <T: Copy + Neg<Output=T>, U> Neg for TypedPoint2D<T, U> {
- type Output = TypedPoint2D<T, U>;
- #[inline]
- fn neg(self) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(-self.x, -self.y)
- }
-}
-
-impl<T: Float, U> TypedPoint2D<T, U> {
- pub fn min(self, other: TypedPoint2D<T, U>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x.min(other.x), self.y.min(other.y))
- }
-
- pub fn max(self, other: TypedPoint2D<T, U>) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(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 = TypedPoint2D<T, U>;
- #[inline]
- fn mul(self, scale: T) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x * scale, self.y * scale)
- }
-}
-
-impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedPoint2D<T, U> {
- type Output = TypedPoint2D<T, U>;
- #[inline]
- fn div(self, scale: T) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x / scale, self.y / 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> {
- TypedPoint2D::new(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> {
- TypedPoint2D::new(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 }
- pub fn round(&self) -> Self {
- TypedPoint2D::new(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 orginal value.
- ///
- /// This behavior is preserved for negative values (unlike the basic cast).
- /// For example { -0.1, -0.8 }.ceil() == { 0.0, 0.0 }.
- pub fn ceil(&self) -> Self {
- TypedPoint2D::new(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 orginal value.
- ///
- /// This behavior is preserved for negative values (unlike the basic cast).
- /// For example { -0.1, -0.8 }.floor() == { -1.0, -1.0 }.
- pub fn floor(&self) -> Self {
- TypedPoint2D::new(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.
- 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(TypedPoint2D::new(x, y)),
- _ => None
- }
- }
-
- // Convenience functions for common casts
-
- /// Cast into an f32 vector.
- 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 vectors, it is worth considering whether
- /// to round(), ceil() or floor() before the cast in order to obtain the desired
- /// conversion behavior.
- pub fn to_uint(&self) -> TypedPoint2D<usize, U> {
- self.cast().unwrap()
- }
-
- /// Cast into an i32 point, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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) -> TypedPoint2D<i32, U> {
- self.cast().unwrap()
- }
-
- /// Cast into an i64 point, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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) -> TypedPoint2D<i64, U> {
- self.cast().unwrap()
- }
-}
-
-impl<T: Copy+ApproxEq<T>, U> ApproxEq<TypedPoint2D<T, U>> for TypedPoint2D<T, U> {
- #[inline]
- fn approx_epsilon() -> Self {
- TypedPoint2D::new(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)
- }
-}
-
-define_matrix! {
- /// A 3d Point tagged with a unit.
- #[derive(RustcDecodable, RustcEncodable)]
- 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 zero() -> TypedPoint3D<T, U> {
- TypedPoint3D::new(Zero::zero(), Zero::zero(), Zero::zero())
- }
-}
-
-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) -> TypedPoint3D<T, U> {
- 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>) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(x.0, y.0, z.0)
- }
-
- /// 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> {
- TypedPoint3D::new(self.x, self.y, self.z)
- }
-
- /// Tag a unitless value with units.
- #[inline]
- pub fn from_untyped(p: &Point3D<T>) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(p.x, p.y, p.z)
- }
-
- /// Convert into a 2d point.
- #[inline]
- pub fn to_2d(&self) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x, self.y)
- }
-}
-
-impl<T: Mul<T, Output=T> +
- Add<T, Output=T> +
- Sub<T, Output=T> +
- Copy, U> TypedPoint3D<T, U> {
-
- // Dot product.
- #[inline]
- pub fn dot(self, other: TypedPoint3D<T, U>) -> T {
- self.x * other.x +
- self.y * other.y +
- self.z * other.z
- }
-
- // Cross product.
- #[inline]
- pub fn cross(self, other: TypedPoint3D<T, U>) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(self.y * other.z - self.z * other.y,
- self.z * other.x - self.x * other.z,
- self.x * other.y - self.y * other.x)
- }
-}
-
-impl<T: Copy + Add<T, Output=T>, U> Add for TypedPoint3D<T, U> {
- type Output = TypedPoint3D<T, U>;
- fn add(self, other: TypedPoint3D<T, U>) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(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 = TypedPoint3D<T, U>;
- fn sub(self, other: TypedPoint3D<T, U>) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(self.x - other.x,
- self.y - other.y,
- self.z - other.z)
- }
-}
-
-impl <T: Copy + Neg<Output=T>, U> Neg for TypedPoint3D<T, U> {
- type Output = TypedPoint3D<T, U>;
- #[inline]
- fn neg(self) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(-self.x, -self.y, -self.z)
- }
-}
-
-impl<T: Float, U> TypedPoint3D<T, U> {
- pub fn min(self, other: TypedPoint3D<T, U>) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(self.x.min(other.x),
- self.y.min(other.y),
- self.z.min(other.z))
- }
-
- pub fn max(self, other: TypedPoint3D<T, U>) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(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).
- pub fn round(&self) -> Self {
- TypedPoint3D::new(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 orginal value.
- ///
- /// This behavior is preserved for negative values (unlike the basic cast).
- pub fn ceil(&self) -> Self {
- TypedPoint3D::new(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 orginal value.
- ///
- /// This behavior is preserved for negative values (unlike the basic cast).
- pub fn floor(&self) -> Self {
- TypedPoint3D::new(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.
- 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(TypedPoint3D::new(x, y, z)),
- _ => None
- }
- }
-
- // Convenience functions for common casts
-
- /// Cast into an f32 vector.
- 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 vectors, it is worth considering whether
- /// to round(), ceil() or floor() before the cast in order to obtain the desired
- /// conversion behavior.
- pub fn to_uint(&self) -> TypedPoint3D<usize, U> {
- self.cast().unwrap()
- }
-
- /// Cast into an i32 point, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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) -> TypedPoint3D<i32, U> {
- self.cast().unwrap()
- }
-
- /// Cast into an i64 point, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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) -> 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 {
- TypedPoint3D::new(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)
- }
-}
-
-define_matrix! {
- /// A 4d Point tagged with a unit.
- #[derive(RustcDecodable, RustcEncodable)]
- pub struct TypedPoint4D<T, U> {
- pub x: T,
- pub y: T,
- pub z: T,
- pub w: T,
- }
-}
-
-/// Default 4d point with no unit.
-///
-/// `Point4D` provides the same methods as `TypedPoint4D`.
-pub type Point4D<T> = TypedPoint4D<T, UnknownUnit>;
-
-impl<T: Copy + Zero, U> TypedPoint4D<T, U> {
- /// Constructor, setting all copmonents to zero.
- #[inline]
- pub fn zero() -> TypedPoint4D<T, U> {
- TypedPoint4D::new(Zero::zero(), Zero::zero(), Zero::zero(), Zero::zero())
- }
-}
-
-impl<T: fmt::Debug, U> fmt::Debug for TypedPoint4D<T, U> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "({:?},{:?},{:?},{:?})", self.x, self.y, self.z, self.w)
- }
-}
-
-impl<T: fmt::Display, U> fmt::Display for TypedPoint4D<T, U> {
- fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- write!(formatter, "({},{},{},{})", self.x, self.y, self.z, self.w)
- }
-}
-
-impl<T: Copy, U> TypedPoint4D<T, U> {
- /// Constructor taking scalar values directly.
- #[inline]
- pub fn new(x: T, y: T, z: T, w: T) -> TypedPoint4D<T, U> {
- TypedPoint4D { x: x, y: y, z: z, w: w, _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>,
- w: Length<T, U>) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(x.0, y.0, z.0, w.0)
- }
-
- /// 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) }
-
- /// Returns self.w as a Length carrying the unit.
- #[inline]
- pub fn w_typed(&self) -> Length<T, U> { Length::new(self.w) }
-
- /// Drop the units, preserving only the numeric value.
- #[inline]
- pub fn to_untyped(&self) -> Point4D<T> {
- TypedPoint4D::new(self.x, self.y, self.z, self.w)
- }
-
- /// Tag a unitless value with units.
- #[inline]
- pub fn from_untyped(p: &Point4D<T>) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(p.x, p.y, p.z, p.w)
- }
-
- #[inline]
- pub fn to_array(&self) -> [T; 4] {
- [self.x, self.y, self.z, self.w]
- }
-}
-
-impl<T: Copy + Div<T, Output=T>, U> TypedPoint4D<T, U> {
- /// Convert into a 2d point.
- #[inline]
- pub fn to_2d(self) -> TypedPoint2D<T, U> {
- TypedPoint2D::new(self.x / self.w, self.y / self.w)
- }
-
- /// Convert into a 3d point.
- #[inline]
- pub fn to_3d(self) -> TypedPoint3D<T, U> {
- TypedPoint3D::new(self.x / self.w, self.y / self.w, self.z / self.w)
- }
-}
-
-impl<T: Copy + Add<T, Output=T>, U> Add for TypedPoint4D<T, U> {
- type Output = TypedPoint4D<T, U>;
- fn add(self, other: TypedPoint4D<T, U>) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(self.x + other.x,
- self.y + other.y,
- self.z + other.z,
- self.w + other.w)
- }
-}
-
-impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedPoint4D<T, U> {
- type Output = TypedPoint4D<T, U>;
- fn sub(self, other: TypedPoint4D<T, U>) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(self.x - other.x,
- self.y - other.y,
- self.z - other.z,
- self.w - other.w)
- }
-}
-
-impl <T: Copy + Neg<Output=T>, U> Neg for TypedPoint4D<T, U> {
- type Output = TypedPoint4D<T, U>;
- #[inline]
- fn neg(self) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(-self.x, -self.y, -self.z, -self.w)
- }
-}
-
-impl<T: Float, U> TypedPoint4D<T, U> {
- pub fn min(self, other: TypedPoint4D<T, U>) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(self.x.min(other.x), self.y.min(other.y),
- self.z.min(other.z), self.w.min(other.w))
- }
-
- pub fn max(self, other: TypedPoint4D<T, U>) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(self.x.max(other.x), self.y.max(other.y),
- self.z.max(other.z), self.w.max(other.w))
- }
-}
-
-impl<T: Round, U> TypedPoint4D<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 {
- TypedPoint4D::new(self.x.round(), self.y.round(), self.z.round(), self.w.round())
- }
-}
-
-impl<T: Ceil, U> TypedPoint4D<T, U> {
- /// Rounds each component to the smallest integer equal or greater than the orginal value.
- ///
- /// This behavior is preserved for negative values (unlike the basic cast).
- pub fn ceil(&self) -> Self {
- TypedPoint4D::new(self.x.ceil(), self.y.ceil(), self.z.ceil(), self.w.ceil())
- }
-}
-
-impl<T: Floor, U> TypedPoint4D<T, U> {
- /// Rounds each component to the biggest integer equal or lower than the orginal value.
- ///
- /// This behavior is preserved for negative values (unlike the basic cast).
- pub fn floor(&self) -> Self {
- TypedPoint4D::new(self.x.floor(), self.y.floor(), self.z.floor(), self.w.floor())
- }
-}
-
-impl<T: NumCast + Copy, U> TypedPoint4D<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.
- pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedPoint4D<NewT, U>> {
- match (NumCast::from(self.x),
- NumCast::from(self.y),
- NumCast::from(self.z),
- NumCast::from(self.w)) {
- (Some(x), Some(y), Some(z), Some(w)) => Some(TypedPoint4D::new(x, y, z, w)),
- _ => None
- }
- }
-
- // Convenience functions for common casts
-
- /// Cast into an f32 vector.
- pub fn to_f32(&self) -> TypedPoint4D<f32, U> {
- self.cast().unwrap()
- }
-
- /// Cast into an usize point, truncating decimals if any.
- ///
- /// When casting from floating point vectors, it is worth considering whether
- /// to round(), ceil() or floor() before the cast in order to obtain the desired
- /// conversion behavior.
- pub fn to_uint(&self) -> TypedPoint4D<usize, U> {
- self.cast().unwrap()
- }
-
- /// Cast into an i32 point, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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) -> TypedPoint4D<i32, U> {
- self.cast().unwrap()
- }
-
- /// Cast into an i64 point, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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) -> TypedPoint4D<i64, U> {
- self.cast().unwrap()
- }
-}
-
-impl<T: ApproxEq<T>, U> ApproxEq<T> for TypedPoint4D<T, U> {
- fn approx_epsilon() -> T {
- T::approx_epsilon()
- }
-
- fn approx_eq_eps(&self, other: &Self, approx_epsilon: &T) -> bool {
- self.x.approx_eq_eps(&other.x, approx_epsilon)
- && self.y.approx_eq_eps(&other.y, approx_epsilon)
- && self.z.approx_eq_eps(&other.z, approx_epsilon)
- && self.w.approx_eq_eps(&other.w, approx_epsilon)
- }
-
- fn approx_eq(&self, other: &Self) -> bool {
- self.approx_eq_eps(&other, &Self::approx_epsilon())
- }
-}
-
-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)
-}
-
-pub fn point4<T: Copy, U>(x: T, y: T, z: T, w: T) -> TypedPoint4D<T, U> {
- TypedPoint4D::new(x, y, z, w)
-}
-
-#[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_dot() {
- let p1: Point2D<f32> = Point2D::new(2.0, 7.0);
- let p2: Point2D<f32> = Point2D::new(13.0, 11.0);
- assert_eq!(p1.dot(p2), 103.0);
- }
-
- #[test]
- pub fn test_cross() {
- let p1: Point2D<f32> = Point2D::new(4.0, 7.0);
- let p2: Point2D<f32> = Point2D::new(13.0, 8.0);
- let r = p1.cross(p2);
- assert_eq!(r, -59.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;
-
- 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 = Point2DMm::new(3.0, 4.0);
-
- let result = p1 + p2;
-
- assert_eq!(result, 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));
- }
-}
-
-#[cfg(test)]
-mod point3d {
- use super::Point3D;
-
- #[test]
- pub fn test_dot() {
- let p1 = Point3D::new(7.0, 21.0, 32.0);
- let p2 = Point3D::new(43.0, 5.0, 16.0);
- assert_eq!(p1.dot(p2), 918.0);
- }
-
- #[test]
- pub fn test_cross() {
- let p1 = Point3D::new(4.0, 7.0, 9.0);
- let p2 = Point3D::new(13.0, 8.0, 3.0);
- let p3 = p1.cross(p2);
- assert_eq!(p3, Point3D::new(-51.0, 105.0, -59.0));
- }
-
- #[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));
- }
-}
-
-#[cfg(test)]
-mod point4d {
- use super::Point4D;
-
- #[test]
- pub fn test_add() {
- let p1 = Point4D::new(7.0, 21.0, 32.0, 1.0);
- let p2 = Point4D::new(43.0, 5.0, 16.0, 2.0);
-
- let result = p1 + p2;
-
- assert_eq!(result, Point4D::new(50.0, 26.0, 48.0, 3.0));
- }
-
- #[test]
- pub fn test_sub() {
- let p1 = Point4D::new(7.0, 21.0, 32.0, 1.0);
- let p2 = Point4D::new(43.0, 5.0, 16.0, 2.0);
-
- let result = p1 - p2;
-
- assert_eq!(result, Point4D::new(-36.0, 16.0, 16.0, -1.0));
- }
-
- #[test]
- pub fn test_min() {
- let p1 = Point4D::new(1.0, 3.0, 5.0, 7.0);
- let p2 = Point4D::new(2.0, 2.0, -1.0, 10.0);
-
- let result = p1.min(p2);
-
- assert_eq!(result, Point4D::new(1.0, 2.0, -1.0, 7.0));
- }
-
- #[test]
- pub fn test_max() {
- let p1 = Point4D::new(1.0, 3.0, 5.0, 7.0);
- let p2 = Point4D::new(2.0, 2.0, -1.0, 10.0);
-
- let result = p1.max(p2);
-
- assert_eq!(result, Point4D::new(2.0, 3.0, 5.0, 10.0));
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/rect.rs
+++ /dev/null
@@ -1,671 +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 size::TypedSize2D;
-
-use heapsize::HeapSizeOf;
-use num_traits::NumCast;
-use serde::{Deserialize, Deserializer, Serialize, Serializer};
-use std::cmp::PartialOrd;
-use std::fmt;
-use std::ops::{Add, Sub, Mul, Div};
-
-/// A 2d Rectangle optionally tagged with a unit.
-#[derive(RustcDecodable, RustcEncodable)]
-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: &mut 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: &mut S) -> Result<(), S::Error>
- where S: Serializer
- {
- (&self.origin, &self.size).serialize(serializer)
- }
-}
-
-impl<T: Copy, U> Copy for TypedRect<T, U> {}
-
-impl<T: Copy, U> Clone for TypedRect<T, U> {
- fn clone(&self) -> TypedRect<T, U> { *self }
-}
-
-impl<T: PartialEq, U> PartialEq<TypedRect<T, U>> for TypedRect<T, U> {
- fn eq(&self, other: &TypedRect<T, U>) -> 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>) -> TypedRect<T, U> {
- 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: &TypedRect<T, U>) -> 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: &TypedRect<T, U>) -> Option<TypedRect<T, U>> {
- 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)))
- }
-
- /// Translates the rect by a vector.
- #[inline]
- pub fn translate(&self, other: &TypedPoint2D<T, U>) -> TypedRect<T, U> {
- TypedRect::new(
- TypedPoint2D::new(self.origin.x + other.x, self.origin.y + other.y),
- 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: &TypedRect<T, U>) -> 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]
- pub fn inflate(&self, width: T, height: T) -> TypedRect<T, U> {
- 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]
- pub fn inflate_typed(&self, width: Length<T, U>, height: Length<T, U>) -> TypedRect<T, U> {
- 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]
- pub fn translate_by_size(&self, size: &TypedSize2D<T, U>) -> TypedRect<T, U> {
- self.translate(&TypedPoint2D::new(size.width, size.height))
- }
-
- /// 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 + Clone + PartialOrd + Add<T, Output=T> + Sub<T, Output=T> + Zero {
- #[inline]
- pub fn union(&self, other: &TypedRect<T, U>) -> TypedRect<T, U> {
- 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) -> TypedRect<T, U>
- 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() -> TypedRect<T, U> {
- TypedRect::new(
- TypedPoint2D::zero(),
- 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 = TypedRect<T, U>;
- #[inline]
- fn mul(self, scale: T) -> TypedRect<T, U> {
- TypedRect::new(self.origin * scale, self.size * scale)
- }
-}
-
-impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedRect<T, U> {
- type Output = TypedRect<T, U>;
- #[inline]
- fn div(self, scale: T) -> TypedRect<T, U> {
- 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).
- 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.
- 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.
- 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 vector.
- pub fn to_f32(&self) -> TypedRect<f32, Unit> {
- self.cast().unwrap()
- }
-
- /// Cast into an usize vector, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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_uint(&self) -> TypedRect<usize, Unit> {
- self.cast().unwrap()
- }
-
- /// Cast into an i32 vector, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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 vector, truncating decimals if any.
- ///
- /// When casting from floating point vectors, 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 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(&Point2D::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(&Point2D::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_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(&Point2D::new( 0.1, 0.0))));
- assert!(!r.contains_rect(&r.translate(&Point2D::new(-0.1, 0.0))));
- assert!(!r.contains_rect(&r.translate(&Point2D::new( 0.0, 0.1))));
- assert!(!r.contains_rect(&r.translate(&Point2D::new( 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
- }
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/scale_factor.rs
+++ /dev/null
@@ -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::scale_factor::ScaleFactor;
-/// use euclid::length::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;
-/// ```
-#[derive(RustcDecodable, RustcEncodable)]
-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: &mut 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: &mut S) -> Result<(),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));
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/side_offsets.rs
+++ /dev/null
@@ -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) -> TypedSideOffsets2D<T, U> {
- 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>) -> TypedSideOffsets2D<T, U> {
- 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) -> TypedSideOffsets2D<T, U> {
- 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>) -> TypedSideOffsets2D<T, U> {
- 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 = TypedSideOffsets2D<T, U>;
- fn add(self, other: TypedSideOffsets2D<T, U>) -> TypedSideOffsets2D<T, U> {
- 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() -> TypedSideOffsets2D<T, U> {
- 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>())
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/size.rs
+++ /dev/null
@@ -1,276 +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 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! {
- #[derive(RustcDecodable, RustcEncodable)]
- 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) -> TypedSize2D<T, U> {
- TypedSize2D {
- width: width,
- height: height,
- _unit: PhantomData,
- }
- }
-}
-
-impl<T: Clone, U> TypedSize2D<T, U> {
- /// Constructor taking scalar stronlgy typed lengths.
- pub fn from_lengths(width: Length<T, U>, height: Length<T, U>) -> TypedSize2D<T, U> {
- 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 orginal 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 orginal 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 = TypedSize2D<T, U>;
- fn add(self, other: TypedSize2D<T, U>) -> TypedSize2D<T, U> {
- 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 = TypedSize2D<T, U>;
- fn sub(self, other: TypedSize2D<T, U>) -> TypedSize2D<T, U> {
- 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: Zero, U> TypedSize2D<T, U> {
- pub fn zero() -> TypedSize2D<T, U> {
- TypedSize2D::new(
- Zero::zero(),
- Zero::zero(),
- )
- }
-}
-
-impl<T: Zero, U> Zero for TypedSize2D<T, U> {
- fn zero() -> TypedSize2D<T, U> {
- TypedSize2D::new(
- Zero::zero(),
- Zero::zero(),
- )
- }
-}
-
-impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedSize2D<T, U> {
- type Output = TypedSize2D<T, U>;
- #[inline]
- fn mul(self, scale: T) -> TypedSize2D<T, U> {
- TypedSize2D::new(self.width * scale, self.height * scale)
- }
-}
-
-impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedSize2D<T, U> {
- type Output = TypedSize2D<T, U>;
- #[inline]
- fn div(self, scale: T) -> TypedSize2D<T, U> {
- 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] }
-
- /// 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>) -> TypedSize2D<T, U> {
- 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 marke 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 usize 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_uint(&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));
- }
-}
deleted file mode 100644
--- a/third_party/rust/euclid-0.10.5/src/trig.rs
+++ /dev/null
@@ -1,50 +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;
-}
-
-impl Trig for f32 {
- #[inline]
- fn sin(self) -> f32 {
- self.sin()
- }
-
- #[inline]
- fn cos(self) -> f32 {
- self.cos()
- }
-
- #[inline]
- fn tan(self) -> f32 {
- self.tan()
- }
-}
-
-impl Trig for f64 {
- #[inline]
- fn sin(self) -> f64 {
- self.sin()
- }
-
- #[inline]
- fn cos(self) -> f64 {
- self.cos()
- }
-
- #[inline]
- fn tan(self) -> f64 {
- self.tan()
- }
-}
--- a/third_party/rust/offscreen_gl_context/.cargo-checksum.json
+++ b/third_party/rust/offscreen_gl_context/.cargo-checksum.json
@@ -1,1 +1,1 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"7150ee9391a955b2ef7e0762fc61c0c1aab167620ca36d88d78062d93b8334ba",".travis.yml":"9b8376fc479996f32f8a690e6009fc2f7e9f6dc1b1224e0180a92ad65b0b2183","Cargo.toml":"50ad80c8c43d09fbf1360736cfb7a9ba122c9ab080facebc83788313dfefce72","Makefile":"85b6d903eecac170ac97f10d9d89b8366cd91f5ea2f7c6212704bc590b64cf50","README.md":"614cf0c6242be3e62e45a3d60ce9a2a1581bdc46b28b25d5f40caba558e4d615","build.rs":"86776b47fac1d9368e3c3c5d57c62731729ed859bb1c4e4db0fe219251812cab","src/draw_buffer.rs":"52bef86972f40e0dd13a6e81f3aa76d4d0c28ea0b63f5f9da9650a34d75488c0","src/gl_context.rs":"28953e3752ea7fd2b19327f98c06fe53f7618efc4d3f0cb2262eba403756df2a","src/gl_context_attributes.rs":"c76ef02996d0daac313b666d1991878bbf7812932a0f9feac9e62c89ba7bf669","src/gl_context_capabilities.rs":"9f665ad04d42d47d15ecbd430639d95da526ec5951f0b7abe2434adc1415c85d","src/gl_feature.rs":"b826884900c0e8d6317a41ebb6c30bdb468601bf1c030c376749bdb2ecd2f15a","src/gl_formats.rs":"99087345b4e9a12c86605c0d091bfaf1b4ed4b2475a3b6f91d2127a2bb85fe1b","src/gl_limits.rs":"02e41619518daae5895929db00d073b5ad0d9daf9319a61abb7012c2e59fb6c7","src/lib.rs":"daaf4e26504dbb97f3803de4337f601d616adf0633e5c4415c2c172fb257ebd6","src/platform/mod.rs":"f6ec310e5b8fb519607b8e4d5ca71a0c07c83737a83c3785b5b44e7902498c8a","src/platform/not_implemented/mod.rs":"d576e9fc3164f9e2a8ff9460a60eaa8ecada44c600de1a4d1bb5513ab93569af","src/platform/not_implemented/native_gl_context.rs":"fe018722b8bebbd59b6fae759dd78b0175d10bf110205b113ff155fd06d0f75d","src/platform/with_cgl/mod.rs":"b05dc146c9ba82d62410d9b0566a8aa70c77e7ec583ad4881c531d7118454543","src/platform/with_cgl/native_gl_context.rs":"c6271cfa96836d8f833f5efbc90352852557d582db41d2c513cc36c3f966ae88","src/platform/with_egl/mod.rs":"c52ac147eb051733070c36b2c62be8c57427f80999507f62a9ce801f4aac284c","src/platform/with_egl/native_gl_context.rs":"3a8342d53de9525a5478cc96b323dbad2b3628aa6655fe5f092834cc72256116","src/platform/with_egl/utils.rs":"508521e2bf3809ffe0dfea4fa4a358903f49c77a33aa42cc6c0e7458d992a2a7","src/platform/with_glx/mod.rs":"0e497f38b2071ed189995c91b27b0b199d31bfcc10836e2d26b55023d7aff503","src/platform/with_glx/native_gl_context.rs":"2c648ae18baac14290b2eca3581d474adfea00a29a7ad47a1100e564e74b9152","src/platform/with_glx/utils.rs":"eb81e0a4c62947fa5099c241cfe2e4dd075376d30b22864e042c0f536ac6be58","src/platform/with_osmesa/mod.rs":"9f6d69878125185f16740f52ba5cdd8a45e8812af1a3561482c9b43edaf4514a","src/platform/with_wgl/mod.rs":"38f9b44b54c8a1bd4d25ae77a4ea6a2e5454a00b816764d7d74152c1f3c1b126","src/platform/with_wgl/native_gl_context.rs":"4aecd40a811cf38607b17db9724f79bb934e056f85c90c987b2aa82d637b7bb4","src/platform/with_wgl/utils.rs":"d9640c000dcb513cf0a13c4a0d35c423366b7d0894deff299affe0202bdeb770","src/platform/with_wgl/wgl_attributes.rs":"73b75da18519e048011e9c303e402cf7961e3652aa8f4d4ebf507b4ab83d06a3","src/tests.rs":"780d4211a02c09abebb2b8be85a87ed98bee374999bd333c29efb3a8c7d2b281"},"package":"171f74d51d4c94dae19d13c502dbf09afab328a5517f8bfeee2f2a33ced3bca9"}
\ No newline at end of file
+{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"7150ee9391a955b2ef7e0762fc61c0c1aab167620ca36d88d78062d93b8334ba",".travis.yml":"9b8376fc479996f32f8a690e6009fc2f7e9f6dc1b1224e0180a92ad65b0b2183","Cargo.toml":"2377d25abb4a8cd857355e101af61480e9e5718e1d5fcfb12e41993b8ec211c9","Makefile":"85b6d903eecac170ac97f10d9d89b8366cd91f5ea2f7c6212704bc590b64cf50","README.md":"614cf0c6242be3e62e45a3d60ce9a2a1581bdc46b28b25d5f40caba558e4d615","build.rs":"86776b47fac1d9368e3c3c5d57c62731729ed859bb1c4e4db0fe219251812cab","src/draw_buffer.rs":"52bef86972f40e0dd13a6e81f3aa76d4d0c28ea0b63f5f9da9650a34d75488c0","src/gl_context.rs":"28953e3752ea7fd2b19327f98c06fe53f7618efc4d3f0cb2262eba403756df2a","src/gl_context_attributes.rs":"8ddf99864f838ba847783d824e85eb71c8eea7d5dfb9950737dfb1472a33a4f6","src/gl_context_capabilities.rs":"9f665ad04d42d47d15ecbd430639d95da526ec5951f0b7abe2434adc1415c85d","src/gl_feature.rs":"b826884900c0e8d6317a41ebb6c30bdb468601bf1c030c376749bdb2ecd2f15a","src/gl_formats.rs":"d15a8e102ebac82c166be4ba2a6e6702a82d509ac61102157c26a0ae25f54ac7","src/gl_limits.rs":"ccecc941207f1f27d9eaf96f0ffadb03d991ab5e6ad2ef73a5af1b9dbbbd7cad","src/lib.rs":"daaf4e26504dbb97f3803de4337f601d616adf0633e5c4415c2c172fb257ebd6","src/platform/mod.rs":"f6ec310e5b8fb519607b8e4d5ca71a0c07c83737a83c3785b5b44e7902498c8a","src/platform/not_implemented/mod.rs":"d576e9fc3164f9e2a8ff9460a60eaa8ecada44c600de1a4d1bb5513ab93569af","src/platform/not_implemented/native_gl_context.rs":"fe018722b8bebbd59b6fae759dd78b0175d10bf110205b113ff155fd06d0f75d","src/platform/with_cgl/mod.rs":"b05dc146c9ba82d62410d9b0566a8aa70c77e7ec583ad4881c531d7118454543","src/platform/with_cgl/native_gl_context.rs":"c6271cfa96836d8f833f5efbc90352852557d582db41d2c513cc36c3f966ae88","src/platform/with_egl/mod.rs":"c52ac147eb051733070c36b2c62be8c57427f80999507f62a9ce801f4aac284c","src/platform/with_egl/native_gl_context.rs":"3a8342d53de9525a5478cc96b323dbad2b3628aa6655fe5f092834cc72256116","src/platform/with_egl/utils.rs":"508521e2bf3809ffe0dfea4fa4a358903f49c77a33aa42cc6c0e7458d992a2a7","src/platform/with_glx/mod.rs":"0e497f38b2071ed189995c91b27b0b199d31bfcc10836e2d26b55023d7aff503","src/platform/with_glx/native_gl_context.rs":"2c648ae18baac14290b2eca3581d474adfea00a29a7ad47a1100e564e74b9152","src/platform/with_glx/utils.rs":"eb81e0a4c62947fa5099c241cfe2e4dd075376d30b22864e042c0f536ac6be58","src/platform/with_osmesa/mod.rs":"9f6d69878125185f16740f52ba5cdd8a45e8812af1a3561482c9b43edaf4514a","src/platform/with_wgl/mod.rs":"38f9b44b54c8a1bd4d25ae77a4ea6a2e5454a00b816764d7d74152c1f3c1b126","src/platform/with_wgl/native_gl_context.rs":"4aecd40a811cf38607b17db9724f79bb934e056f85c90c987b2aa82d637b7bb4","src/platform/with_wgl/utils.rs":"d9640c000dcb513cf0a13c4a0d35c423366b7d0894deff299affe0202bdeb770","src/platform/with_wgl/wgl_attributes.rs":"73b75da18519e048011e9c303e402cf7961e3652aa8f4d4ebf507b4ab83d06a3","src/tests.rs":"a2e5ceecd6b12def2f66a5c576b4ad8ca0dce1834aebe69ebc8474a5c06ec798"},"package":"4ac875ea951d7d695a1cc8c370777d6a0e2b7355ca49506034683df09b24b1bc"}
\ No newline at end of file
--- a/third_party/rust/offscreen_gl_context/Cargo.toml
+++ b/third_party/rust/offscreen_gl_context/Cargo.toml
@@ -1,33 +1,32 @@
[package]
name = "offscreen_gl_context"
license = "MIT / Apache-2.0"
-version = "0.5.5"
+version = "0.6.1"
authors = ["Emilio Cobos Álvarez <emilio@crisal.io>", "The Servo Project Developers"]
description = "Creation and manipulation of HW accelerated offscreen rendering contexts in multiple platforms. Originally intended for the Servo project's WebGL implementation."
repository = "https://github.com/emilio/rust-offscreen-rendering-context"
build = "build.rs"
[build-dependencies]
gl_generator = "0.5"
[features]
default = []
osmesa = ["osmesa-sys"]
-serde_serialization = ["serde"]
# NOTE: Just for testing use, there are no other changes
test_egl_in_linux = []
test_osmesa = []
[dependencies]
log = "0.3"
gleam = "0.2.31"
-euclid = "0.10"
-serde = { version = "0.8", optional = true }
+euclid = "0.11"
+serde = { version = "0.9", optional = true }
osmesa-sys = { version = "0.1", optional = true }
[target.x86_64-apple-darwin.dependencies]
core-foundation = "0.3.0"
cgl = "0.1"
[target.'cfg(target_os = "linux")'.dependencies.x11]
version = "2.3.0"
--- a/third_party/rust/offscreen_gl_context/src/gl_context_attributes.rs
+++ b/third_party/rust/offscreen_gl_context/src/gl_context_attributes.rs
@@ -10,34 +10,34 @@ pub struct GLContextAttributes {
pub stencil: bool,
pub antialias: bool,
pub premultiplied_alpha: bool,
pub preserve_drawing_buffer: bool,
}
#[cfg(feature = "serde")]
impl Deserialize for GLContextAttributes {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer
{
let values = try!(<[_; 6]>::deserialize(deserializer));
Ok(GLContextAttributes {
alpha: values[0],
depth: values[1],
stencil: values[2],
antialias: values[3],
premultiplied_alpha: values[4],
preserve_drawing_buffer: values[5],
})
}
}
#[cfg(feature = "serde")]
impl Serialize for GLContextAttributes {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
let values = [
self.alpha, self.depth, self.stencil,
self.antialias, self.premultiplied_alpha, self.preserve_drawing_buffer,
];
values.serialize(serializer)
}
--- a/third_party/rust/offscreen_gl_context/src/gl_formats.rs
+++ b/third_party/rust/offscreen_gl_context/src/gl_formats.rs
@@ -39,30 +39,37 @@ impl GLFormats {
depth: gl::DEPTH_COMPONENT24,
stencil: gl::STENCIL_INDEX8,
}
}
}
#[cfg(target_os="android")]
pub fn detect(attrs: &GLContextAttributes) -> GLFormats {
+ // detect if the GPU supports RGB8 and RGBA8 renderbuffer/texture storage formats.
+ // GL_ARM_rgba8 extension is similar to OES_rgb8_rgba8, but only exposes RGBA8.
+ let extensions = gl::get_string(gl::EXTENSIONS);
+ let extensions: Vec<&str> = extensions.split(&[',',' '][..]).collect();
+ let has_rgb8 = extensions.contains(&"GL_OES_rgb8_rgba8");
+ let has_rgba8 = has_rgb8 || extensions.contains(&"GL_ARM_rgba8");
+
if attrs.alpha {
GLFormats {
- color_renderbuffer: gl::RGBA4,
+ color_renderbuffer: if has_rgba8 { gl::RGBA8 } else { gl::RGBA4 },
texture_internal: gl::RGBA,
texture: gl::RGBA,
- texture_type: gl::UNSIGNED_SHORT_4_4_4_4,
+ texture_type: if has_rgba8 { gl::UNSIGNED_BYTE } else { gl::UNSIGNED_SHORT_4_4_4_4 },
depth: gl::DEPTH_COMPONENT16,
stencil: gl::STENCIL_INDEX8,
}
} else {
GLFormats {
- color_renderbuffer: gl::RGB565,
+ color_renderbuffer: if has_rgb8 { gl::RGB8 } else { gl::RGB565 },
texture_internal: gl::RGB,
texture: gl::RGB,
- texture_type: gl::UNSIGNED_SHORT_4_4_4_4,
+ texture_type: if has_rgb8 { gl::UNSIGNED_BYTE } else { gl::UNSIGNED_SHORT_4_4_4_4 },
depth: gl::DEPTH_COMPONENT16,
stencil: gl::STENCIL_INDEX8,
}
}
}
}
--- a/third_party/rust/offscreen_gl_context/src/gl_limits.rs
+++ b/third_party/rust/offscreen_gl_context/src/gl_limits.rs
@@ -6,31 +6,31 @@ use serde::{Deserialize, Deserializer, S
pub struct GLLimits {
pub max_vertex_attribs: u32,
pub max_tex_size: u32,
pub max_cube_map_tex_size: u32
}
#[cfg(feature = "serde")]
impl Deserialize for GLLimits {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer
{
let values = try!(<[_; 3]>::deserialize(deserializer));
Ok(GLLimits {
max_vertex_attribs: values[0],
max_tex_size: values[1],
max_cube_map_tex_size: values[2],
})
}
}
#[cfg(feature = "serde")]
impl Serialize for GLLimits {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
[self.max_vertex_attribs, self.max_tex_size, self.max_cube_map_tex_size]
.serialize(serializer)
}
}
impl GLLimits {
--- a/third_party/rust/offscreen_gl_context/src/tests.rs
+++ b/third_party/rust/offscreen_gl_context/src/tests.rs
@@ -18,23 +18,28 @@ use std::sync::mpsc;
#[cfg(target_os="macos")]
#[link(name="OpenGL", kind="framework")]
extern {}
#[cfg(target_os="linux")]
#[link(name="GL")]
extern {}
+#[cfg(not(target_os="android"))]
static LOAD_GL: Once = ONCE_INIT;
+#[cfg(not(target_os="android"))]
fn load_gl() {
LOAD_GL.call_once(|| {
gl::load_with(|s| GLContext::<NativeGLContext>::get_proc_address(s) as *const _);
});
}
+#[cfg(target_os="android")]
+fn load_gl() {
+}
fn test_gl_context<T: NativeGLContextMethods>(context: &GLContext<T>) {
context.make_current().unwrap();
gl::clear_color(1.0, 0.0, 0.0, 1.0);
gl::clear(gl::COLOR_BUFFER_BIT);
let size = context.draw_buffer_size().unwrap();
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/.cargo-checksum.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"37cf6256c6eb377c59bac3c48ca9ac70b100173c1114de357084edf2a5381044","src/bytes.rs":"ec2fb40df6a1e1233462d85145a57eb33a1df0140ed921e9fe0a0ca35c7c1064","src/de/from_primitive.rs":"b1bd165e343a4380965551709119ef9ed895e4b025045a810dabd671511ba3ab","src/de/impls.rs":"3e27049398fc000ae0ec89f0358e5cd8fe55d6ddf0bc5a0a9ae9de936ce0935b","src/de/mod.rs":"62291b6b7c29d411b9ff212cab480982e535e7aee21c1729b4bb592d681ab807","src/de/value.rs":"6dd878ce762799048c0ebc8f834932871e1bdf24953ea69415a2b2148e0d3dbc","src/error.rs":"da31d3881930f0e787d75191984f71fe2e1419d9331c68baa0fc0ce2d561766b","src/iter.rs":"30090fe6ab49bb1d8c7fec362cace52981b2c4e1a1a8e3fad4117eab558cdde6","src/lib.rs":"67f62df097e3b55a90a566af56d6e3c641f719300db8bfd5603ed5a2bff1aa8e","src/macros.rs":"e81e421815fac10d6a7bfb727bbe7b4f24e99b03cd8739efc806e4b704ac7b4e","src/ser/impls.rs":"36d372af1dae11444f85e497eefb98449bae70260348cdfb098c508439be7952","src/ser/mod.rs":"626e8ef5b1ddaf00fe84905e936046c40217e31609d5a56ca658f4eb23983fd5","src/utils.rs":"b0d1a54af90e3620abd66479d757a2eb442449788c4ece93161916da0838affa"},"package":"9dad3f759919b92c3068c696c15c3d17238234498bbdcc80f2c469606f948ac8"}
\ No newline at end of file
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/Cargo.toml
+++ /dev/null
@@ -1,25 +0,0 @@
-[package]
-name = "serde"
-version = "0.8.23"
-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/"
-readme = "../README.md"
-keywords = ["serde", "serialization"]
-categories = ["encoding"]
-include = ["Cargo.toml", "src/**/*.rs"]
-
-[features]
-default = ["std"]
-
-std = []
-unstable = []
-alloc = ["unstable"]
-collections = ["alloc"]
-unstable-testing = ["clippy", "unstable", "std"]
-
-[dependencies]
-clippy = { version = "^0.*", optional = true }
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/bytes.rs
+++ /dev/null
@@ -1,252 +0,0 @@
-//! Helper module to enable serializing bytes more efficiently
-
-use core::{ops, fmt, char, iter, slice};
-use core::fmt::Write;
-
-use ser;
-
-#[cfg(any(feature = "std", feature = "collections"))]
-pub use self::bytebuf::{ByteBuf, ByteBufVisitor};
-
-#[cfg(feature = "collections")]
-use collections::Vec;
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `Bytes` wraps a `&[u8]` in order to serialize into a byte array.
-#[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: &mut S) -> Result<(), S::Error>
- where S: ser::Serializer
- {
- serializer.serialize_bytes(self.bytes)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(any(feature = "std", feature = "collections"))]
-mod bytebuf {
- use core::ops;
- use core::fmt;
- use core::fmt::Write;
-
- use ser;
- use de;
-
- #[cfg(feature = "collections")]
- use collections::{String, Vec};
-
- /// `ByteBuf` wraps a `Vec<u8>` and serializes as a byte array.
- #[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: &mut S) -> Result<(), 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;
-
- #[inline]
- fn visit_unit<E>(&mut self) -> Result<ByteBuf, E>
- where E: de::Error,
- {
- Ok(ByteBuf::new())
- }
-
- #[inline]
- fn visit_seq<V>(&mut self, mut visitor: V) -> Result<ByteBuf, V::Error>
- where V: de::SeqVisitor,
- {
- let (len, _) = visitor.size_hint();
- let mut values = Vec::with_capacity(len);
-
- while let Some(value) = try!(visitor.visit()) {
- values.push(value);
- }
-
- try!(visitor.end());
-
- Ok(ByteBuf::from(values))
- }
-
- #[inline]
- fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<ByteBuf, E>
- where E: de::Error,
- {
- Ok(ByteBuf::from(v))
- }
-
- #[inline]
- fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<ByteBuf, E>
- where E: de::Error,
- {
- Ok(ByteBuf::from(v))
- }
-
- fn visit_str<E>(&mut self, v: &str) -> Result<ByteBuf, E>
- where E: de::Error,
- {
- Ok(ByteBuf::from(v))
- }
-
- fn visit_string<E>(&mut self, v: String) -> Result<ByteBuf, E>
- where E: de::Error,
- {
- Ok(ByteBuf::from(v))
- }
- }
-
- impl de::Deserialize for ByteBuf {
- #[inline]
- fn deserialize<D>(deserializer: &mut D) -> Result<ByteBuf, D::Error>
- where D: de::Deserializer
- {
- deserializer.deserialize_bytes(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)
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/de/from_primitive.rs
+++ /dev/null
@@ -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 }
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/de/impls.rs
+++ /dev/null
@@ -1,1306 +0,0 @@
-//! This module contains `Deserialize` and `Visitor` implementations.
-
-#[cfg(feature = "std")]
-use std::borrow::Cow;
-#[cfg(all(feature = "unstable", feature = "collections", not(feature = "std")))]
-use collections::borrow::Cow;
-
-#[cfg(all(feature = "collections", not(feature = "std")))]
-use collections::{
- BinaryHeap,
- BTreeMap,
- BTreeSet,
- LinkedList,
- VecDeque,
- Vec,
- String,
-};
-
-#[cfg(feature = "std")]
-use std::collections::{
- HashMap,
- HashSet,
- BinaryHeap,
- BTreeMap,
- BTreeSet,
- LinkedList,
- VecDeque,
-};
-
-#[cfg(all(feature = "unstable", feature = "collections"))]
-use collections::enum_set::{CLike, EnumSet};
-#[cfg(all(feature = "unstable", feature = "collections"))]
-use collections::borrow::ToOwned;
-
-use core::hash::{Hash, BuildHasher};
-use core::marker::PhantomData;
-#[cfg(feature = "std")]
-use std::net;
-#[cfg(feature = "std")]
-use std::path;
-use core::str;
-
-#[cfg(feature = "std")]
-use std::rc::Rc;
-#[cfg(all(feature = "unstable", feature = "alloc", not(feature = "std")))]
-use alloc::rc::Rc;
-
-#[cfg(feature = "std")]
-use std::sync::Arc;
-#[cfg(all(feature = "unstable", feature = "alloc", not(feature = "std")))]
-use alloc::arc::Arc;
-
-#[cfg(all(feature = "unstable", feature = "alloc", not(feature = "std")))]
-use alloc::boxed::Box;
-
-#[cfg(feature = "std")]
-use std::time::Duration;
-
-#[cfg(feature = "unstable")]
-use core::nonzero::{NonZero, Zeroable};
-
-#[cfg(feature = "unstable")]
-use core::num::Zero;
-
-use de::{
- Deserialize,
- Deserializer,
- EnumVisitor,
- Error,
- MapVisitor,
- SeqVisitor,
- Type,
- VariantVisitor,
- Visitor,
-};
-use de::from_primitive::FromPrimitive;
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A visitor that produces a `()`.
-pub struct UnitVisitor;
-
-impl Visitor for UnitVisitor {
- type Value = ();
-
- fn visit_unit<E>(&mut self) -> Result<(), E>
- where E: Error,
- {
- Ok(())
- }
-
- fn visit_seq<V>(&mut self, mut visitor: V) -> Result<(), V::Error>
- where V: SeqVisitor,
- {
- visitor.end()
- }
-}
-
-impl Deserialize for () {
- fn deserialize<D>(deserializer: &mut D) -> Result<(), D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_unit(UnitVisitor)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A visitor that produces a `bool`.
-pub struct BoolVisitor;
-
-impl Visitor for BoolVisitor {
- type Value = bool;
-
- fn visit_bool<E>(&mut self, v: bool) -> Result<bool, E>
- where E: Error,
- {
- Ok(v)
- }
-
- fn visit_str<E>(&mut self, s: &str) -> Result<bool, E>
- where E: Error,
- {
- match s.trim_matches(::utils::Pattern_White_Space) {
- "true" => Ok(true),
- "false" => Ok(false),
- _ => Err(Error::invalid_type(Type::Bool)),
- }
- }
-}
-
-impl Deserialize for bool {
- fn deserialize<D>(deserializer: &mut D) -> Result<bool, D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_bool(BoolVisitor)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-macro_rules! impl_deserialize_num_method {
- ($src_ty:ty, $method:ident, $from_method:ident, $ty:expr) => {
- #[inline]
- fn $method<E>(&mut self, v: $src_ty) -> Result<T, E>
- where E: Error,
- {
- match FromPrimitive::$from_method(v) {
- Some(v) => Ok(v),
- None => Err(Error::invalid_type($ty)),
- }
- }
- }
-}
-
-/// A visitor that produces a primitive type.
-struct PrimitiveVisitor<T> {
- marker: PhantomData<T>,
-}
-
-impl<T> PrimitiveVisitor<T> {
- /// Construct a new `PrimitiveVisitor`.
- #[inline]
- fn new() -> Self {
- PrimitiveVisitor {
- marker: PhantomData,
- }
- }
-}
-
-impl<T> Visitor for PrimitiveVisitor<T>
- where T: Deserialize + FromPrimitive + str::FromStr
-{
- type Value = T;
-
- impl_deserialize_num_method!(isize, visit_isize, from_isize, Type::Isize);
- impl_deserialize_num_method!(i8, visit_i8, from_i8, Type::I8);
- impl_deserialize_num_method!(i16, visit_i16, from_i16, Type::I16);
- impl_deserialize_num_method!(i32, visit_i32, from_i32, Type::I32);
- impl_deserialize_num_method!(i64, visit_i64, from_i64, Type::I64);
- impl_deserialize_num_method!(usize, visit_usize, from_usize, Type::Usize);
- impl_deserialize_num_method!(u8, visit_u8, from_u8, Type::U8);
- impl_deserialize_num_method!(u16, visit_u16, from_u16, Type::U16);
- impl_deserialize_num_method!(u32, visit_u32, from_u32, Type::U32);
- impl_deserialize_num_method!(u64, visit_u64, from_u64, Type::U64);
- impl_deserialize_num_method!(f32, visit_f32, from_f32, Type::F32);
- impl_deserialize_num_method!(f64, visit_f64, from_f64, Type::F64);
-
- #[inline]
- fn visit_str<E>(&mut self, s: &str) -> Result<T, E>
- where E: Error,
- {
- str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| {
- Err(Error::invalid_type(Type::Str))
- })
- }
-}
-
-macro_rules! impl_deserialize_num {
- ($ty:ty, $method:ident) => {
- impl Deserialize for $ty {
- #[inline]
- fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
- where D: Deserializer,
- {
- deserializer.$method(PrimitiveVisitor::new())
- }
- }
- }
-}
-
-impl_deserialize_num!(isize, deserialize_isize);
-impl_deserialize_num!(i8, deserialize_i8);
-impl_deserialize_num!(i16, deserialize_i16);
-impl_deserialize_num!(i32, deserialize_i32);
-impl_deserialize_num!(i64, deserialize_i64);
-impl_deserialize_num!(usize, deserialize_usize);
-impl_deserialize_num!(u8, deserialize_u8);
-impl_deserialize_num!(u16, deserialize_u16);
-impl_deserialize_num!(u32, deserialize_u32);
-impl_deserialize_num!(u64, deserialize_u64);
-impl_deserialize_num!(f32, deserialize_f32);
-impl_deserialize_num!(f64, deserialize_f64);
-
-///////////////////////////////////////////////////////////////////////////////
-
-struct CharVisitor;
-
-impl Visitor for CharVisitor {
- type Value = char;
-
- #[inline]
- fn visit_char<E>(&mut self, v: char) -> Result<char, E>
- where E: Error,
- {
- Ok(v)
- }
-
- #[inline]
- fn visit_str<E>(&mut self, v: &str) -> Result<char, E>
- where E: Error,
- {
- let mut iter = v.chars();
- if let Some(v) = iter.next() {
- if iter.next().is_some() {
- Err(Error::invalid_type(Type::Char))
- } else {
- Ok(v)
- }
- } else {
- Err(Error::end_of_stream())
- }
- }
-}
-
-impl Deserialize for char {
- #[inline]
- fn deserialize<D>(deserializer: &mut D) -> Result<char, D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_char(CharVisitor)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(any(feature = "std", feature = "collections"))]
-struct StringVisitor;
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl Visitor for StringVisitor {
- type Value = String;
-
- fn visit_str<E>(&mut self, v: &str) -> Result<String, E>
- where E: Error,
- {
- Ok(v.to_owned())
- }
-
- fn visit_string<E>(&mut self, v: String) -> Result<String, E>
- where E: Error,
- {
- Ok(v)
- }
-
- fn visit_unit<E>(&mut self) -> Result<String, E>
- where E: Error,
- {
- Ok(String::new())
- }
-
- fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<String, E>
- where E: Error,
- {
- match str::from_utf8(v) {
- Ok(s) => Ok(s.to_owned()),
- Err(_) => Err(Error::invalid_type(Type::String)),
- }
- }
-
- fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<String, E>
- where E: Error,
- {
- match String::from_utf8(v) {
- Ok(s) => Ok(s),
- Err(_) => Err(Error::invalid_type(Type::String)),
- }
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl Deserialize for String {
- fn deserialize<D>(deserializer: &mut D) -> Result<String, D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_string(StringVisitor)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-struct OptionVisitor<T> {
- marker: PhantomData<T>,
-}
-
-impl<
- T: Deserialize,
-> Visitor for OptionVisitor<T> {
- type Value = Option<T>;
-
- #[inline]
- fn visit_unit<E>(&mut self) -> Result<Option<T>, E>
- where E: Error,
- {
- Ok(None)
- }
-
- #[inline]
- fn visit_none<E>(&mut self) -> Result<Option<T>, E>
- where E: Error,
- {
- Ok(None)
- }
-
- #[inline]
- fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Option<T>, D::Error>
- where D: Deserializer,
- {
- Ok(Some(try!(Deserialize::deserialize(deserializer))))
- }
-}
-
-impl<T> Deserialize for Option<T> where T: Deserialize {
- fn deserialize<D>(deserializer: &mut D) -> Result<Option<T>, D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_option(OptionVisitor { marker: PhantomData })
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A visitor that produces a `PhantomData`.
-pub struct PhantomDataVisitor<T> {
- marker: PhantomData<T>,
-}
-
-impl<T> Visitor for PhantomDataVisitor<T> {
- type Value = PhantomData<T>;
-
- #[inline]
- fn visit_unit<E>(&mut self) -> Result<PhantomData<T>, E>
- where E: Error,
- {
- Ok(PhantomData)
- }
-}
-
-impl<T> Deserialize for PhantomData<T> {
- fn deserialize<D>(deserializer: &mut D) -> Result<PhantomData<T>, D::Error>
- where D: Deserializer,
- {
- let visitor = PhantomDataVisitor { marker: PhantomData };
- deserializer.deserialize_unit_struct("PhantomData", visitor)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-macro_rules! seq_impl {
- (
- $ty:ty,
- $visitor_ty:ident < $($typaram:ident : $bound1:ident $(+ $bound2:ident)*),* >,
- $visitor:ident,
- $ctor:expr,
- $with_capacity:expr,
- $insert:expr
- ) => {
- /// A visitor that produces a sequence.
- pub struct $visitor_ty<$($typaram),*> {
- marker: PhantomData<$ty>,
- }
-
- impl<$($typaram),*> $visitor_ty<$($typaram),*>
- where $($typaram: $bound1 $(+ $bound2)*),*
- {
- /// Construct a new sequence visitor.
- pub fn new() -> Self {
- $visitor_ty {
- marker: PhantomData,
- }
- }
- }
-
- impl<$($typaram),*> Visitor for $visitor_ty<$($typaram),*>
- where $($typaram: $bound1 $(+ $bound2)*),*
- {
- type Value = $ty;
-
- #[inline]
- fn visit_unit<E>(&mut self) -> Result<$ty, E>
- where E: Error,
- {
- Ok($ctor)
- }
-
- #[inline]
- fn visit_seq<V>(&mut self, mut $visitor: V) -> Result<$ty, V::Error>
- where V: SeqVisitor,
- {
- let mut values = $with_capacity;
-
- while let Some(value) = try!($visitor.visit()) {
- $insert(&mut values, value);
- }
-
- try!($visitor.end());
-
- Ok(values)
- }
- }
-
- impl<$($typaram),*> Deserialize for $ty
- where $($typaram: $bound1 $(+ $bound2)*),*
- {
- fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_seq($visitor_ty::new())
- }
- }
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-seq_impl!(
- BinaryHeap<T>,
- BinaryHeapVisitor<T: Deserialize + Ord>,
- visitor,
- BinaryHeap::new(),
- BinaryHeap::with_capacity(visitor.size_hint().0),
- BinaryHeap::push);
-
-#[cfg(any(feature = "std", feature = "collections"))]
-seq_impl!(
- BTreeSet<T>,
- BTreeSetVisitor<T: Deserialize + Eq + Ord>,
- visitor,
- BTreeSet::new(),
- BTreeSet::new(),
- BTreeSet::insert);
-
-#[cfg(all(feature = "unstable", feature = "collections"))]
-seq_impl!(
- EnumSet<T>,
- EnumSetVisitor<T: Deserialize + CLike>,
- visitor,
- EnumSet::new(),
- EnumSet::new(),
- EnumSet::insert);
-
-#[cfg(any(feature = "std", feature = "collections"))]
-seq_impl!(
- LinkedList<T>,
- LinkedListVisitor<T: Deserialize>,
- visitor,
- LinkedList::new(),
- LinkedList::new(),
- LinkedList::push_back);
-
-#[cfg(feature = "std")]
-seq_impl!(
- HashSet<T, S>,
- HashSetVisitor<T: Deserialize + Eq + Hash,
- S: BuildHasher + Default>,
- visitor,
- HashSet::with_hasher(S::default()),
- HashSet::with_capacity_and_hasher(visitor.size_hint().0, S::default()),
- HashSet::insert);
-
-#[cfg(any(feature = "std", feature = "collections"))]
-seq_impl!(
- Vec<T>,
- VecVisitor<T: Deserialize>,
- visitor,
- Vec::new(),
- Vec::with_capacity(visitor.size_hint().0),
- Vec::push);
-
-#[cfg(any(feature = "std", feature = "collections"))]
-seq_impl!(
- VecDeque<T>,
- VecDequeVisitor<T: Deserialize>,
- visitor,
- VecDeque::new(),
- VecDeque::with_capacity(visitor.size_hint().0),
- VecDeque::push_back);
-
-///////////////////////////////////////////////////////////////////////////////
-
-struct ArrayVisitor<A> {
- marker: PhantomData<A>,
-}
-
-impl<A> ArrayVisitor<A> {
- pub fn new() -> Self {
- ArrayVisitor {
- marker: PhantomData,
- }
- }
-}
-
-impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
- type Value = [T; 0];
-
- #[inline]
- fn visit_unit<E>(&mut self) -> Result<[T; 0], E>
- where E: Error,
- {
- Ok([])
- }
-
- #[inline]
- fn visit_seq<V>(&mut self, mut visitor: V) -> Result<[T; 0], V::Error>
- where V: SeqVisitor,
- {
- try!(visitor.end());
- Ok([])
- }
-}
-
-impl<T> Deserialize for [T; 0]
- where T: Deserialize
-{
- fn deserialize<D>(deserializer: &mut D) -> Result<[T; 0], D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_seq_fixed_size(0, ArrayVisitor::<[T; 0]>::new())
- }
-}
-
-macro_rules! array_impls {
- ($($len:expr => ($($name:ident)+))+) => {
- $(
- impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize {
- type Value = [T; $len];
-
- #[inline]
- fn visit_seq<V>(&mut self, mut visitor: V) -> Result<[T; $len], V::Error>
- where V: SeqVisitor,
- {
- $(
- let $name = match try!(visitor.visit()) {
- Some(val) => val,
- None => return Err(Error::end_of_stream()),
- };
- )+
-
- try!(visitor.end());
-
- Ok([$($name),+])
- }
- }
-
- impl<T> Deserialize for [T; $len]
- where T: Deserialize,
- {
- fn deserialize<D>(deserializer: &mut D) -> Result<[T; $len], D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_seq_fixed_size($len, ArrayVisitor::<[T; $len]>::new())
- }
- }
- )+
- }
-}
-
-array_impls! {
- 1 => (a)
- 2 => (a b)
- 3 => (a b c)
- 4 => (a b c d)
- 5 => (a b c d e)
- 6 => (a b c d e f)
- 7 => (a b c d e f g)
- 8 => (a b c d e f g h)
- 9 => (a b c d e f g h i)
- 10 => (a b c d e f g h i j)
- 11 => (a b c d e f g h i j k)
- 12 => (a b c d e f g h i j k l)
- 13 => (a b c d e f g h i j k l m)
- 14 => (a b c d e f g h i j k l m n)
- 15 => (a b c d e f g h i j k l m n o)
- 16 => (a b c d e f g h i j k l m n o p)
- 17 => (a b c d e f g h i j k l m n o p q)
- 18 => (a b c d e f g h i j k l m n o p q r)
- 19 => (a b c d e f g h i j k l m n o p q r s)
- 20 => (a b c d e f g h i j k l m n o p q r s t)
- 21 => (a b c d e f g h i j k l m n o p q r s t u)
- 22 => (a b c d e f g h i j k l m n o p q r s t u v)
- 23 => (a b c d e f g h i j k l m n o p q r s t u v w)
- 24 => (a b c d e f g h i j k l m n o p q r s t u v w x)
- 25 => (a b c d e f g h i j k l m n o p q r s t u v w x y)
- 26 => (a b c d e f g h i j k l m n o p q r s t u v w x y z)
- 27 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
- 28 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab)
- 29 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac)
- 30 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad)
- 31 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae)
- 32 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af)
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-macro_rules! tuple_impls {
- ($($len:expr => $visitor:ident => ($($name:ident)+))+) => {
- $(
- /// Construct a tuple visitor.
- pub struct $visitor<$($name,)+> {
- marker: PhantomData<($($name,)+)>,
- }
-
- impl<$($name: Deserialize,)+> $visitor<$($name,)+> {
- /// Construct a `TupleVisitor*<T>`.
- pub fn new() -> Self {
- $visitor { marker: PhantomData }
- }
- }
-
- impl<$($name: Deserialize),+> Visitor for $visitor<$($name,)+> {
- type Value = ($($name,)+);
-
- #[inline]
- #[allow(non_snake_case)]
- fn visit_seq<V>(&mut self, mut visitor: V) -> Result<($($name,)+), V::Error>
- where V: SeqVisitor,
- {
- $(
- let $name = match try!(visitor.visit()) {
- Some(value) => value,
- None => return Err(Error::end_of_stream()),
- };
- )+
-
- try!(visitor.end());
-
- Ok(($($name,)+))
- }
- }
-
- impl<$($name: Deserialize),+> Deserialize for ($($name,)+) {
- #[inline]
- fn deserialize<D>(deserializer: &mut D) -> Result<($($name,)+), D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_tuple($len, $visitor::new())
- }
- }
- )+
- }
-}
-
-tuple_impls! {
- 1 => TupleVisitor1 => (T0)
- 2 => TupleVisitor2 => (T0 T1)
- 3 => TupleVisitor3 => (T0 T1 T2)
- 4 => TupleVisitor4 => (T0 T1 T2 T3)
- 5 => TupleVisitor5 => (T0 T1 T2 T3 T4)
- 6 => TupleVisitor6 => (T0 T1 T2 T3 T4 T5)
- 7 => TupleVisitor7 => (T0 T1 T2 T3 T4 T5 T6)
- 8 => TupleVisitor8 => (T0 T1 T2 T3 T4 T5 T6 T7)
- 9 => TupleVisitor9 => (T0 T1 T2 T3 T4 T5 T6 T7 T8)
- 10 => TupleVisitor10 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9)
- 11 => TupleVisitor11 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10)
- 12 => TupleVisitor12 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11)
- 13 => TupleVisitor13 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)
- 14 => TupleVisitor14 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13)
- 15 => TupleVisitor15 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14)
- 16 => TupleVisitor16 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15)
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-macro_rules! map_impl {
- (
- $ty:ty,
- $visitor_ty:ident < $($typaram:ident : $bound1:ident $(+ $bound2:ident)*),* >,
- $visitor:ident,
- $ctor:expr,
- $with_capacity:expr
- ) => {
- /// A visitor that produces a map.
- pub struct $visitor_ty<$($typaram),*> {
- marker: PhantomData<$ty>,
- }
-
- impl<$($typaram),*> $visitor_ty<$($typaram),*>
- where $($typaram: $bound1 $(+ $bound2)*),*
- {
- /// Construct a `MapVisitor*<T>`.
- pub fn new() -> Self {
- $visitor_ty {
- marker: PhantomData,
- }
- }
- }
-
- impl<$($typaram),*> Visitor for $visitor_ty<$($typaram),*>
- where $($typaram: $bound1 $(+ $bound2)*),*
- {
- type Value = $ty;
-
- #[inline]
- fn visit_unit<E>(&mut self) -> Result<$ty, E>
- where E: Error,
- {
- Ok($ctor)
- }
-
- #[inline]
- fn visit_map<Visitor>(&mut self, mut $visitor: Visitor) -> Result<$ty, Visitor::Error>
- where Visitor: MapVisitor,
- {
- let mut values = $with_capacity;
-
- while let Some((key, value)) = try!($visitor.visit()) {
- values.insert(key, value);
- }
-
- try!($visitor.end());
-
- Ok(values)
- }
- }
-
- impl<$($typaram),*> Deserialize for $ty
- where $($typaram: $bound1 $(+ $bound2)*),*
- {
- fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_map($visitor_ty::new())
- }
- }
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-map_impl!(
- BTreeMap<K, V>,
- BTreeMapVisitor<K: Deserialize + Ord,
- V: Deserialize>,
- visitor,
- BTreeMap::new(),
- BTreeMap::new());
-
-#[cfg(feature = "std")]
-map_impl!(
- HashMap<K, V, S>,
- HashMapVisitor<K: Deserialize + Eq + Hash,
- V: Deserialize,
- S: BuildHasher + Default>,
- visitor,
- HashMap::with_hasher(S::default()),
- HashMap::with_capacity_and_hasher(visitor.size_hint().0, S::default()));
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(feature = "std")]
-impl Deserialize for net::IpAddr {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer,
- {
- let s = try!(String::deserialize(deserializer));
- match s.parse() {
- Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl Deserialize for net::Ipv4Addr {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer,
- {
- let s = try!(String::deserialize(deserializer));
- match s.parse() {
- Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl Deserialize for net::Ipv6Addr {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer,
- {
- let s = try!(String::deserialize(deserializer));
- match s.parse() {
- Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
- }
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(feature = "std")]
-impl Deserialize for net::SocketAddr {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer,
- {
- let s = try!(String::deserialize(deserializer));
- match s.parse() {
- Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl Deserialize for net::SocketAddrV4 {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer,
- {
- let s = try!(String::deserialize(deserializer));
- match s.parse() {
- Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl Deserialize for net::SocketAddrV6 {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer,
- {
- let s = try!(String::deserialize(deserializer));
- match s.parse() {
- Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
- }
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(feature = "std")]
-struct PathBufVisitor;
-
-#[cfg(feature = "std")]
-impl Visitor for PathBufVisitor {
- type Value = path::PathBuf;
-
- fn visit_str<E>(&mut self, v: &str) -> Result<path::PathBuf, E>
- where E: Error,
- {
- Ok(From::from(v))
- }
-
- fn visit_string<E>(&mut self, v: String) -> Result<path::PathBuf, E>
- where E: Error,
- {
- self.visit_str(&v)
- }
-}
-
-#[cfg(feature = "std")]
-impl Deserialize for path::PathBuf {
- fn deserialize<D>(deserializer: &mut D) -> Result<path::PathBuf, D::Error>
- where D: Deserializer,
- {
- deserializer.deserialize_string(PathBufVisitor)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(any(feature = "std", feature = "alloc"))]
-impl<T: Deserialize> Deserialize for Box<T> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Box<T>, D::Error>
- where D: Deserializer,
- {
- let val = try!(Deserialize::deserialize(deserializer));
- Ok(Box::new(val))
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<T: Deserialize> Deserialize for Box<[T]> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Box<[T]>, D::Error>
- where D: Deserializer,
- {
- let v: Vec<T> = try!(Deserialize::deserialize(deserializer));
- Ok(v.into_boxed_slice())
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl Deserialize for Box<str> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer
- {
- let s = try!(String::deserialize(deserializer));
- Ok(s.into_boxed_str())
- }
-}
-
-#[cfg(any(feature = "std", feature = "alloc"))]
-impl<T: Deserialize> Deserialize for Arc<T> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Arc<T>, D::Error>
- where D: Deserializer,
- {
- let val = try!(Deserialize::deserialize(deserializer));
- Ok(Arc::new(val))
- }
-}
-
-#[cfg(any(feature = "std", feature = "alloc"))]
-impl<T: Deserialize> Deserialize for Rc<T> {
- fn deserialize<D>(deserializer: &mut D) -> Result<Rc<T>, D::Error>
- where D: Deserializer,
- {
- let val = try!(Deserialize::deserialize(deserializer));
- Ok(Rc::new(val))
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deserialize, {
- #[inline]
- fn deserialize<D>(deserializer: &mut D) -> Result<Cow<'a, T>, D::Error>
- where D: Deserializer,
- {
- let val = try!(Deserialize::deserialize(deserializer));
- Ok(Cow::Owned(val))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// This is a cleaned-up version of the impl generated by:
-//
-// #[derive(Deserialize)]
-// #[serde(deny_unknown_fields)]
-// struct Duration {
-// secs: u64,
-// nanos: u32,
-// }
-#[cfg(feature = "std")]
-impl Deserialize for Duration {
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer,
- {
- enum Field { Secs, Nanos };
-
- impl Deserialize for Field {
- fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
- where D: Deserializer,
- {
- struct FieldVisitor;
-
- impl Visitor for FieldVisitor {
- type Value = Field;
-
- fn visit_usize<E>(&mut self, value: usize) -> Result<Field, E>
- where E: Error,
- {
- match value {
- 0usize => Ok(Field::Secs),
- 1usize => Ok(Field::Nanos),
- _ => Err(Error::invalid_value("expected a field")),
- }
- }
-
- fn visit_str<E>(&mut self, value: &str) -> Result<Field, E>
- where E: Error,
- {
- match value {
- "secs" => Ok(Field::Secs),
- "nanos" => Ok(Field::Nanos),
- _ => Err(Error::unknown_field(value)),
- }
- }
-
- fn visit_bytes<E>(&mut self, value: &[u8]) -> Result<Field, E>
- where E: Error,
- {
- match value {
- b"secs" => Ok(Field::Secs),
- b"nanos" => Ok(Field::Nanos),
- _ => {
- let value = String::from_utf8_lossy(value);
- Err(Error::unknown_field(&value))
- }
- }
- }
- }
-
- deserializer.deserialize_struct_field(FieldVisitor)
- }
- }
-
- struct DurationVisitor;
-
- impl Visitor for DurationVisitor {
- type Value = Duration;
-
- fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Duration, V::Error>
- where V: SeqVisitor,
- {
- let secs: u64 = match try!(visitor.visit()) {
- Some(value) => value,
- None => {
- try!(visitor.end());
- return Err(Error::invalid_length(0));
- }
- };
- let nanos: u32 = match try!(visitor.visit()) {
- Some(value) => value,
- None => {
- try!(visitor.end());
- return Err(Error::invalid_length(1));
- }
- };
- try!(visitor.end());
- Ok(Duration::new(secs, nanos))
- }
-
- fn visit_map<V>(&mut self, mut visitor: V) -> Result<Duration, V::Error>
- where V: MapVisitor,
- {
- let mut secs: Option<u64> = None;
- let mut nanos: Option<u32> = None;
- while let Some(key) = try!(visitor.visit_key::<Field>()) {
- match key {
- Field::Secs => {
- if secs.is_some() {
- return Err(<V::Error as Error>::duplicate_field("secs"));
- }
- secs = Some(try!(visitor.visit_value()));
- }
- Field::Nanos => {
- if nanos.is_some() {
- return Err(<V::Error as Error>::duplicate_field("nanos"));
- }
- nanos = Some(try!(visitor.visit_value()));
- }
- }
- }
- try!(visitor.end());
- let secs = match secs {
- Some(secs) => secs,
- None => try!(visitor.missing_field("secs")),
- };
- let nanos = match nanos {
- Some(nanos) => nanos,
- None => try!(visitor.missing_field("nanos")),
- };
- Ok(Duration::new(secs, nanos))
- }
- }
-
- const FIELDS: &'static [&'static str] = &["secs", "nanos"];
- deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(feature = "unstable")]
-impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
- fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
- let value = try!(Deserialize::deserialize(deserializer));
- if value == Zero::zero() {
- return Err(Error::invalid_value("expected a non-zero value"))
- }
- unsafe {
- Ok(NonZero::new(value))
- }
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-
-impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
- fn deserialize<D>(deserializer: &mut D) -> Result<Result<T, E>, D::Error>
- where D: Deserializer {
- enum Field {
- Ok,
- Err,
- }
-
- impl Deserialize for Field {
- #[inline]
- fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
- where D: Deserializer
- {
- struct FieldVisitor;
-
- impl ::de::Visitor for FieldVisitor {
- type Value = Field;
-
- #[cfg(any(feature = "std", feature = "collections"))]
- fn visit_usize<E>(&mut self, value: usize) -> Result<Field, E> where E: Error {
- #[cfg(feature = "collections")]
- use collections::string::ToString;
- match value {
- 0 => Ok(Field::Ok),
- 1 => Ok(Field::Err),
- _ => Err(Error::unknown_field(&value.to_string())),
- }
- }
-
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn visit_usize<E>(&mut self, value: usize) -> Result<Field, E> where E: Error {
- match value {
- 0 => Ok(Field::Ok),
- 1 => Ok(Field::Err),
- _ => Err(Error::unknown_field("some number")),
- }
- }
-
- fn visit_str<E>(&mut self, value: &str) -> Result<Field, E> where E: Error {
- match value {
- "Ok" => Ok(Field::Ok),
- "Err" => Ok(Field::Err),
- _ => Err(Error::unknown_field(value)),
- }
- }
-
- fn visit_bytes<E>(&mut self, value: &[u8]) -> Result<Field, E> where E: Error {
- match value {
- b"Ok" => Ok(Field::Ok),
- b"Err" => Ok(Field::Err),
- _ => {
- match str::from_utf8(value) {
- Ok(value) => Err(Error::unknown_field(value)),
- Err(_) => Err(Error::invalid_type(Type::String)),
- }
- }
- }
- }
- }
-
- deserializer.deserialize(FieldVisitor)
- }
- }
-
- struct Visitor<T, E>(PhantomData<Result<T, E>>);
-
- impl<T, E> EnumVisitor for Visitor<T, E>
- where T: Deserialize,
- E: Deserialize
- {
- type Value = Result<T, E>;
-
- fn visit<V>(&mut self, mut visitor: V) -> Result<Result<T, E>, V::Error>
- where V: VariantVisitor
- {
- match try!(visitor.visit_variant()) {
- Field::Ok => {
- let value = try!(visitor.visit_newtype());
- Ok(Ok(value))
- }
- Field::Err => {
- let value = try!(visitor.visit_newtype());
- Ok(Err(value))
- }
- }
- }
- }
-
- const VARIANTS: &'static [&'static str] = &["Ok", "Err"];
-
- deserializer.deserialize_enum("Result", VARIANTS, Visitor(PhantomData))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A target for deserializers that want to ignore data. Implements
-/// Deserialize and silently eats data given to it.
-pub struct IgnoredAny;
-
-impl Deserialize for IgnoredAny {
- #[inline]
- fn deserialize<D>(deserializer: &mut D) -> Result<IgnoredAny, D::Error>
- where D: Deserializer,
- {
- struct IgnoredAnyVisitor;
-
- impl Visitor for IgnoredAnyVisitor {
- type Value = IgnoredAny;
-
- #[inline]
- fn visit_bool<E>(&mut self, _: bool) -> Result<IgnoredAny, E> {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_i64<E>(&mut self, _: i64) -> Result<IgnoredAny, E> {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_u64<E>(&mut self, _: u64) -> Result<IgnoredAny, E> {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_f64<E>(&mut self, _: f64) -> Result<IgnoredAny, E> {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_str<E>(&mut self, _: &str) -> Result<IgnoredAny, E>
- where E: Error,
- {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_none<E>(&mut self) -> Result<IgnoredAny, E> {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_some<D>(&mut self, _: &mut D) -> Result<IgnoredAny, D::Error>
- where D: Deserializer,
- {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_newtype_struct<D>(&mut self, _: &mut D) -> Result<IgnoredAny, D::Error>
- where D: Deserializer,
- {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_unit<E>(&mut self) -> Result<IgnoredAny, E> {
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_seq<V>(&mut self, mut visitor: V) -> Result<IgnoredAny, V::Error>
- where V: SeqVisitor,
- {
- while let Some(_) = try!(visitor.visit::<IgnoredAny>()) {
- // Gobble
- }
-
- try!(visitor.end());
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_map<V>(&mut self, mut visitor: V) -> Result<IgnoredAny, V::Error>
- where V: MapVisitor,
- {
- while let Some((_, _)) = try!(visitor.visit::<IgnoredAny, IgnoredAny>()) {
- // Gobble
- }
-
- try!(visitor.end());
- Ok(IgnoredAny)
- }
-
- #[inline]
- fn visit_bytes<E>(&mut self, _: &[u8]) -> Result<IgnoredAny, E>
- where E: Error,
- {
- Ok(IgnoredAny)
- }
- }
-
- // TODO maybe not necessary with impl specialization
- deserializer.deserialize_ignored_any(IgnoredAnyVisitor)
- }
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/de/mod.rs
+++ /dev/null
@@ -1,830 +0,0 @@
-//! Generic deserialization framework.
-
-#[cfg(feature = "std")]
-use std::error;
-#[cfg(not(feature = "std"))]
-use error;
-
-#[cfg(all(not(feature = "std"), feature = "collections"))]
-use collections::{String, Vec};
-
-use core::fmt;
-
-///////////////////////////////////////////////////////////////////////////////
-
-pub mod impls;
-pub mod value;
-mod from_primitive;
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `Error` is a trait that allows a `Deserialize` to generically create a
-/// `Deserializer` error.
-pub trait Error: Sized + error::Error {
- /// Raised when there is general error when deserializing a type.
- #[cfg(any(feature = "std", feature = "collections"))]
- fn custom<T: Into<String>>(msg: T) -> Self;
-
- /// Raised when there is general error when deserializing a type.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn custom<T: Into<&'static str>>(msg: T) -> Self;
-
- /// Raised when a `Deserialize` type unexpectedly hit the end of the stream.
- fn end_of_stream() -> Self;
-
- /// Raised when a `Deserialize` was passed an incorrect type.
- fn invalid_type(ty: Type) -> Self {
- Error::custom(format!("Invalid type. Expected `{:?}`", ty))
- }
-
- /// Raised when a `Deserialize` was passed an incorrect value.
- fn invalid_value(msg: &str) -> Self {
- Error::custom(format!("Invalid value: {}", msg))
- }
-
- /// Raised when a fixed sized sequence or map was passed in the wrong amount of arguments.
- ///
- /// The parameter `len` is the number of arguments found in the serialization. The sequence
- /// may either expect more arguments or less arguments.
- fn invalid_length(len: usize) -> Self {
- Error::custom(format!("Invalid length: {}", len))
- }
-
- /// Raised when a `Deserialize` enum type received an unexpected variant.
- fn unknown_variant(field: &str) -> Self {
- Error::custom(format!("Unknown variant `{}`", field))
- }
-
- /// Raised when a `Deserialize` struct type received an unexpected struct field.
- fn unknown_field(field: &str) -> Self {
- Error::custom(format!("Unknown field `{}`", field))
- }
-
- /// raised when a `deserialize` struct type did not receive a field.
- fn missing_field(field: &'static str) -> Self {
- Error::custom(format!("Missing field `{}`", field))
- }
-
- /// Raised when a `Deserialize` struct type received more than one of the
- /// same struct field.
- fn duplicate_field(field: &'static str) -> Self {
- Error::custom(format!("Duplicate field `{}`", field))
- }
-}
-
-/// `Type` represents all the primitive types that can be deserialized. This is used by
-/// `Error::invalid_type`.
-#[derive(Copy, Clone, PartialEq, Eq, Debug)]
-pub enum Type {
- /// Represents a `bool` type.
- Bool,
-
- /// Represents a `usize` type.
- Usize,
-
- /// Represents a `u8` type.
- U8,
-
- /// Represents a `u16` type.
- U16,
-
- /// Represents a `u32` type.
- U32,
-
- /// Represents a `u64` type.
- U64,
-
- /// Represents a `isize` type.
- Isize,
-
- /// Represents a `i8` type.
- I8,
-
- /// Represents a `i16` type.
- I16,
-
- /// Represents a `i32` type.
- I32,
-
- /// Represents a `i64` type.
- I64,
-
- /// Represents a `f32` type.
- F32,
-
- /// Represents a `f64` type.
- F64,
-
- /// Represents a `char` type.
- Char,
-
- /// Represents a `&str` type.
- Str,
-
- /// Represents a `String` type.
- String,
-
- /// Represents a `()` type.
- Unit,
-
- /// Represents an `Option<T>` type.
- Option,
-
- /// Represents a sequence type.
- Seq,
-
- /// Represents a map type.
- Map,
-
- /// Represents a unit struct type.
- UnitStruct,
-
- /// Represents a newtype type.
- NewtypeStruct,
-
- /// Represents a tuple struct type.
- TupleStruct,
-
- /// Represents a struct type.
- Struct,
-
- /// Represents a struct field name.
- FieldName,
-
- /// Represents a tuple type.
- Tuple,
-
- /// Represents an `enum` type.
- Enum,
-
- /// Represents an enum variant name.
- VariantName,
-
- /// Represents a struct variant.
- StructVariant,
-
- /// Represents a tuple variant.
- TupleVariant,
-
- /// Represents a unit variant.
- UnitVariant,
-
- /// Represents a `&[u8]` type.
- Bytes,
-}
-
-impl fmt::Display for Type {
- fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- let display = match *self {
- Type::Bool => "bool",
- Type::Usize => "usize",
- Type::U8 => "u8",
- Type::U16 => "u16",
- Type::U32 => "u32",
- Type::U64 => "u64",
- Type::Isize => "isize",
- Type::I8 => "i8",
- Type::I16 => "i16",
- Type::I32 => "i32",
- Type::I64 => "i64",
- Type::F32 => "f32",
- Type::F64 => "f64",
- Type::Char => "char",
- Type::Str => "str",
- Type::String => "string",
- Type::Unit => "unit",
- Type::Option => "option",
- Type::Seq => "seq",
- Type::Map => "map",
- Type::UnitStruct => "unit struct",
- Type::NewtypeStruct => "newtype struct",
- Type::TupleStruct => "tuple struct",
- Type::Struct => "struct",
- Type::FieldName => "field name",
- Type::Tuple => "tuple",
- Type::Enum => "enum",
- Type::VariantName => "variant name",
- Type::StructVariant => "struct variant",
- Type::TupleVariant => "tuple variant",
- Type::UnitVariant => "unit variant",
- Type::Bytes => "bytes",
- };
- display.fmt(formatter)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `Deserialize` represents a type that can be deserialized.
-pub trait Deserialize: Sized {
- /// Deserialize this value given this `Deserializer`.
- fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
- where D: Deserializer;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `Deserializer` is a trait that can deserialize values by threading a `Visitor` trait through a
-/// value. It supports two entry point styles which enables different kinds of deserialization.
-///
-/// 1) The `deserialize` method. File formats like JSON embed the type of its construct in its file
-/// format. This allows the `Deserializer` to deserialize into a generic type like
-/// `json::Value`, which can represent all JSON types.
-///
-/// 2) The `deserialize_*` methods. File formats like bincode do not embed in its format how to
-/// decode its values. It relies instead on the `Deserialize` type to hint to the `Deserializer`
-/// with the `deserialize_*` methods how it should parse the next value. One downside though to
-/// only supporting the `deserialize_*` types is that it does not allow for deserializing into a
-/// generic `json::Value`-esque type.
-pub trait Deserializer {
- /// The error type that can be returned if some error occurs during deserialization.
- type Error: Error;
-
- /// This method walks a visitor through a value as it is being deserialized.
- fn deserialize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a `bool` value.
- fn deserialize_bool<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `usize` value.
- /// A reasonable default is to forward to `deserialize_u64`.
- fn deserialize_usize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `u8` value.
- /// A reasonable default is to forward to `deserialize_u64`.
- fn deserialize_u8<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `u16` value.
- /// A reasonable default is to forward to `deserialize_u64`.
- fn deserialize_u16<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `u32` value.
- /// A reasonable default is to forward to `deserialize_u64`.
- fn deserialize_u32<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `u64` value.
- fn deserialize_u64<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `isize` value.
- /// A reasonable default is to forward to `deserialize_i64`.
- fn deserialize_isize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `i8` value.
- /// A reasonable default is to forward to `deserialize_i64`.
- fn deserialize_i8<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `i16` value.
- /// A reasonable default is to forward to `deserialize_i64`.
- fn deserialize_i16<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `i32` value.
- /// A reasonable default is to forward to `deserialize_i64`.
- fn deserialize_i32<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `i64` value.
- fn deserialize_i64<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a `f32` value.
- /// A reasonable default is to forward to `deserialize_f64`.
- fn deserialize_f32<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a `f64` value.
- fn deserialize_f64<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a `char` value.
- fn deserialize_char<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a `&str` value.
- fn deserialize_str<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a `String` value.
- fn deserialize_string<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `unit` value.
- fn deserialize_unit<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an `Option` value. This allows
- /// deserializers that encode an optional value as a nullable value to convert the null value
- /// into a `None`, and a regular value as `Some(value)`.
- fn deserialize_option<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a sequence value. This allows
- /// deserializers to parse sequences that aren't tagged as sequences.
- fn deserialize_seq<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a fixed size array. This allows
- /// deserializers to parse arrays that aren't tagged as arrays.
- fn deserialize_seq_fixed_size<V>(&mut self,
- len: usize,
- visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows
- /// deserializers that provide a custom byte vector serialization to properly deserialize the
- /// type.
- fn deserialize_bytes<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a map of values. This allows
- /// deserializers to parse sequences that aren't tagged as maps.
- fn deserialize_map<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a unit struct. This allows
- /// deserializers to a unit struct that aren't tagged as a unit struct.
- fn deserialize_unit_struct<V>(&mut self,
- name: &'static str,
- visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a newtype struct. This allows
- /// deserializers to a newtype struct that aren't tagged as a newtype struct.
- /// A reasonable default is to simply deserialize the expected value directly.
- fn deserialize_newtype_struct<V>(&mut self,
- name: &'static str,
- visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a tuple struct. This allows
- /// deserializers to parse sequences that aren't tagged as sequences.
- fn deserialize_tuple_struct<V>(&mut self,
- name: &'static str,
- len: usize,
- visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a struct. This allows
- /// deserializers to parse sequences that aren't tagged as maps.
- fn deserialize_struct<V>(&mut self,
- name: &'static str,
- fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting some sort of struct field
- /// name. This allows deserializers to choose between &str, usize, or &[u8] to properly
- /// deserialize a struct field.
- fn deserialize_struct_field<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting a tuple value. This allows
- /// deserializers that provide a custom tuple serialization to properly deserialize the type.
- fn deserialize_tuple<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// This method hints that the `Deserialize` type is expecting an enum value. This allows
- /// deserializers that provide a custom enumeration serialization to properly deserialize the
- /// type.
- fn deserialize_enum<V>(&mut self,
- name: &'static str,
- variants: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
- where V: EnumVisitor;
-
- /// This method hints that the `Deserialize` type needs to deserialize a value whose type
- /// doesn't matter because it is ignored.
- fn deserialize_ignored_any<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// This trait represents a visitor that walks through a deserializer.
-pub trait Visitor {
- /// The value produced by this visitor.
- type Value: Deserialize;
-
- /// `visit_bool` deserializes a `bool` into a `Value`.
- fn visit_bool<E>(&mut self, v: bool) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = v;
- Err(Error::invalid_type(Type::Bool))
- }
-
- /// `visit_isize` deserializes a `isize` into a `Value`.
- fn visit_isize<E>(&mut self, v: isize) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_i64(v as i64)
- }
-
- /// `visit_i8` deserializes a `i8` into a `Value`.
- fn visit_i8<E>(&mut self, v: i8) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_i64(v as i64)
- }
-
- /// `visit_i16` deserializes a `i16` into a `Value`.
- fn visit_i16<E>(&mut self, v: i16) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_i64(v as i64)
- }
-
- /// `visit_i32` deserializes a `i32` into a `Value`.
- fn visit_i32<E>(&mut self, v: i32) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_i64(v as i64)
- }
-
- /// `visit_i64` deserializes a `i64` into a `Value`.
- fn visit_i64<E>(&mut self, v: i64) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = v;
- Err(Error::invalid_type(Type::I64))
- }
-
- /// `visit_usize` deserializes a `usize` into a `Value`.
- fn visit_usize<E>(&mut self, v: usize) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_u64(v as u64)
- }
-
- /// `visit_u8` deserializes a `u8` into a `Value`.
- fn visit_u8<E>(&mut self, v: u8) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_u64(v as u64)
- }
-
- /// `visit_u16` deserializes a `u16` into a `Value`.
- fn visit_u16<E>(&mut self, v: u16) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_u64(v as u64)
- }
-
- /// `visit_u32` deserializes a `u32` into a `Value`.
- fn visit_u32<E>(&mut self, v: u32) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_u64(v as u64)
- }
-
- /// `visit_u64` deserializes a `u64` into a `Value`.
- fn visit_u64<E>(&mut self, v: u64) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = v;
- Err(Error::invalid_type(Type::U64))
- }
-
- /// `visit_f32` deserializes a `f32` into a `Value`.
- fn visit_f32<E>(&mut self, v: f32) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_f64(v as f64)
- }
-
- /// `visit_f64` deserializes a `f64` into a `Value`.
- fn visit_f64<E>(&mut self, v: f64) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = v;
- Err(Error::invalid_type(Type::F64))
- }
-
- /// `visit_char` deserializes a `char` into a `Value`.
- #[inline]
- fn visit_char<E>(&mut self, v: char) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_str(::utils::encode_utf8(v).as_str())
- }
-
- /// `visit_str` deserializes a `&str` into a `Value`.
- fn visit_str<E>(&mut self, v: &str) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = v;
- Err(Error::invalid_type(Type::Str))
- }
-
- /// `visit_string` deserializes a `String` into a `Value`. This allows a deserializer to avoid
- /// a copy if it is deserializing a string from a `String` type. By default it passes a `&str`
- /// to the `visit_str` method.
- #[inline]
- #[cfg(any(feature = "std", feature = "collections"))]
- fn visit_string<E>(&mut self, v: String) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_str(&v)
- }
-
- /// `visit_unit` deserializes a `()` into a `Value`.
- fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
- where E: Error,
- {
- Err(Error::invalid_type(Type::Unit))
- }
-
- /// `visit_unit_struct` deserializes a unit struct into a `Value`.
- #[inline]
- fn visit_unit_struct<E>(&mut self, name: &'static str) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = name;
- self.visit_unit()
- }
-
- /// `visit_none` deserializes a none value into a `Value`.
- fn visit_none<E>(&mut self) -> Result<Self::Value, E>
- where E: Error,
- {
- Err(Error::invalid_type(Type::Option))
- }
-
- /// `visit_some` deserializes a value into a `Value`.
- fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Self::Value, D::Error>
- where D: Deserializer,
- {
- let _ = deserializer;
- Err(Error::invalid_type(Type::Option))
- }
-
- /// `visit_newtype_struct` deserializes a value into a `Value`.
- fn visit_newtype_struct<D>(&mut self, deserializer: &mut D) -> Result<Self::Value, D::Error>
- where D: Deserializer,
- {
- let _ = deserializer;
- Err(Error::invalid_type(Type::NewtypeStruct))
- }
-
- /// `visit_seq` deserializes a `SeqVisitor` into a `Value`.
- fn visit_seq<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
- where V: SeqVisitor,
- {
- let _ = visitor;
- Err(Error::invalid_type(Type::Seq))
- }
-
- /// `visit_map` deserializes a `MapVisitor` into a `Value`.
- fn visit_map<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
- where V: MapVisitor,
- {
- let _ = visitor;
- Err(Error::invalid_type(Type::Map))
- }
-
- /// `visit_bytes` deserializes a `&[u8]` into a `Value`.
- fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = v;
- Err(Error::invalid_type(Type::Bytes))
- }
-
- /// `visit_byte_buf` deserializes a `Vec<u8>` into a `Value`.
- #[cfg(any(feature = "std", feature = "collections"))]
- fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_bytes(&v)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `SeqVisitor` visits each item in a sequence.
-///
-/// This is a trait that a `Deserializer` passes to a `Visitor` implementation, which deserializes
-/// each item in a sequence.
-pub trait SeqVisitor {
- /// The error type that can be returned if some error occurs during deserialization.
- type Error: Error;
-
- /// This returns a `Ok(Some(value))` for the next value in the sequence, or `Ok(None)` if there
- /// are no more remaining items.
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: Deserialize;
-
- /// This signals to the `SeqVisitor` that the `Visitor` does not expect any more items.
- fn end(&mut self) -> Result<(), Self::Error>;
-
- /// Return the lower and upper bound of items remaining in the sequence.
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- (0, None)
- }
-}
-
-impl<'a, V> SeqVisitor for &'a mut V where V: SeqVisitor {
- type Error = V::Error;
-
- #[inline]
- fn visit<T>(&mut self) -> Result<Option<T>, V::Error>
- where T: Deserialize
- {
- (**self).visit()
- }
-
- #[inline]
- fn end(&mut self) -> Result<(), V::Error> {
- (**self).end()
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- (**self).size_hint()
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `MapVisitor` visits each item in a sequence.
-///
-/// This is a trait that a `Deserializer` passes to a `Visitor` implementation.
-pub trait MapVisitor {
- /// The error type that can be returned if some error occurs during deserialization.
- type Error: Error;
-
- /// This returns a `Ok(Some((key, value)))` for the next (key-value) pair in the map, or
- /// `Ok(None)` if there are no more remaining items.
- #[inline]
- fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
- where K: Deserialize,
- V: Deserialize,
- {
- match try!(self.visit_key()) {
- Some(key) => {
- let value = try!(self.visit_value());
- Ok(Some((key, value)))
- }
- None => Ok(None)
- }
- }
-
- /// This returns a `Ok(Some(key))` for the next key in the map, or `Ok(None)` if there are no
- /// more remaining items.
- fn visit_key<K>(&mut self) -> Result<Option<K>, Self::Error>
- where K: Deserialize;
-
- /// This returns a `Ok(value)` for the next value in the map.
- fn visit_value<V>(&mut self) -> Result<V, Self::Error>
- where V: Deserialize;
-
- /// This signals to the `MapVisitor` that the `Visitor` does not expect any more items.
- fn end(&mut self) -> Result<(), Self::Error>;
-
- /// Return the lower and upper bound of items remaining in the sequence.
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- (0, None)
- }
-
- /// Report that the struct has a field that wasn't deserialized
- fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
- where V: Deserialize,
- {
- Err(Error::missing_field(field))
- }
-}
-
-impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
- type Error = V_::Error;
-
- #[inline]
- fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error>
- where K: Deserialize,
- V: Deserialize,
- {
- (**self).visit()
- }
-
- #[inline]
- fn visit_key<K>(&mut self) -> Result<Option<K>, V_::Error>
- where K: Deserialize
- {
- (**self).visit_key()
- }
-
- #[inline]
- fn visit_value<V>(&mut self) -> Result<V, V_::Error>
- where V: Deserialize
- {
- (**self).visit_value()
- }
-
- #[inline]
- fn end(&mut self) -> Result<(), V_::Error> {
- (**self).end()
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- (**self).size_hint()
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `EnumVisitor` is a visitor that is created by the `Deserialize` and passed to the
-/// `Deserializer` in order to deserialize enums.
-pub trait EnumVisitor {
- /// The value produced by this visitor.
- type Value;
-
- /// Visit the specific variant with the `VariantVisitor`.
- fn visit<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
- where V: VariantVisitor;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `VariantVisitor` is a visitor that is created by the `Deserializer` and passed to the
-/// `Deserialize` in order to deserialize a specific enum variant.
-pub trait VariantVisitor {
- /// The error type that can be returned if some error occurs during deserialization.
- type Error: Error;
-
- /// `visit_variant` is called to identify which variant to deserialize.
- fn visit_variant<V>(&mut self) -> Result<V, Self::Error>
- where V: Deserialize;
-
- /// `visit_unit` is called when deserializing a variant with no values.
- fn visit_unit(&mut self) -> Result<(), Self::Error> {
- Err(Error::invalid_type(Type::UnitVariant))
- }
-
- /// `visit_newtype` is called when deserializing a variant with a single value.
- /// A good default is often to use the `visit_tuple` method to deserialize a `(value,)`.
- fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
- where T: Deserialize;
-
- /// `visit_tuple` is called when deserializing a tuple-like variant.
- /// If no tuple variants are expected, yield a
- /// `Err(serde::de::Error::invalid_type(serde::de::Type::TupleVariant))`
- fn visit_tuple<V>(&mut self,
- len: usize,
- visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
- /// `visit_struct` is called when deserializing a struct-like variant.
- /// If no struct variants are expected, yield a
- /// `Err(serde::de::Error::invalid_type(serde::de::Type::StructVariant))`
- fn visit_struct<V>(&mut self,
- fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-}
-
-impl<'a, T> VariantVisitor for &'a mut T where T: VariantVisitor {
- type Error = T::Error;
-
- fn visit_variant<V>(&mut self) -> Result<V, T::Error>
- where V: Deserialize
- {
- (**self).visit_variant()
- }
-
- fn visit_unit(&mut self) -> Result<(), T::Error> {
- (**self).visit_unit()
- }
-
- fn visit_newtype<D>(&mut self) -> Result<D, T::Error>
- where D: Deserialize,
- {
- (**self).visit_newtype()
- }
-
- fn visit_tuple<V>(&mut self,
- len: usize,
- visitor: V) -> Result<V::Value, T::Error>
- where V: Visitor,
- {
- (**self).visit_tuple(len, visitor)
- }
-
- fn visit_struct<V>(&mut self,
- fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, T::Error>
- where V: Visitor,
- {
- (**self).visit_struct(fields, visitor)
- }
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/de/value.rs
+++ /dev/null
@@ -1,1067 +0,0 @@
-//! This module supports deserializing from primitives with the `ValueDeserializer` trait.
-
-#[cfg(feature = "std")]
-use std::collections::{
- BTreeMap,
- BTreeSet,
- HashMap,
- HashSet,
- btree_map,
- btree_set,
- hash_map,
- hash_set,
-};
-#[cfg(feature = "std")]
-use std::borrow::Cow;
-#[cfg(feature = "std")]
-use std::vec;
-
-#[cfg(all(feature = "collections", not(feature = "std")))]
-use collections::{
- BTreeMap,
- BTreeSet,
- Vec,
- String,
- btree_map,
- btree_set,
- vec,
-};
-#[cfg(all(feature = "collections", not(feature = "std")))]
-use collections::borrow::Cow;
-
-#[cfg(all(feature = "unstable", feature = "collections"))]
-use collections::borrow::ToOwned;
-
-use core::hash::Hash;
-#[cfg(feature = "std")]
-use std::error;
-#[cfg(not(feature = "std"))]
-use error;
-
-use core::fmt;
-use core::marker::PhantomData;
-
-use de;
-use bytes;
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// This represents all the possible errors that can occur using the `ValueDeserializer`.
-#[derive(Clone, Debug, PartialEq)]
-pub enum Error {
- /// The value had some custom error.
- #[cfg(any(feature = "std", feature = "collections"))]
- Custom(String),
- /// The value had some custom error.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- Custom(&'static str),
-
- /// The value had an incorrect type.
- InvalidType(de::Type),
-
- /// The value had an invalid length.
- InvalidLength(usize),
-
- /// The value is invalid and cannot be deserialized.
- #[cfg(any(feature = "std", feature = "collections"))]
- InvalidValue(String),
- /// The value is invalid and cannot be deserialized.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- InvalidValue(&'static str),
-
- /// EOF while deserializing a value.
- EndOfStream,
-
- /// Unknown variant in enum.
- #[cfg(any(feature = "std", feature = "collections"))]
- UnknownVariant(String),
- /// Unknown variant in enum.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- UnknownVariant(&'static str),
-
- /// Unknown field in struct.
- #[cfg(any(feature = "std", feature = "collections"))]
- UnknownField(String),
- /// Unknown field in struct.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- UnknownField(&'static str),
-
- /// Struct is missing a field.
- MissingField(&'static str),
-}
-
-impl de::Error for Error {
- #[cfg(any(feature = "std", feature = "collections"))]
- fn custom<T: Into<String>>(msg: T) -> Self { Error::Custom(msg.into()) }
-
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn custom<T: Into<&'static str>>(msg: T) -> Self { Error::Custom(msg.into()) }
-
- fn end_of_stream() -> Self { Error::EndOfStream }
- fn invalid_type(ty: de::Type) -> Self { Error::InvalidType(ty) }
-
- #[cfg(any(feature = "std", feature = "collections"))]
- fn invalid_value(msg: &str) -> Self { Error::InvalidValue(msg.to_owned()) }
-
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn invalid_value(msg: &str) -> Self { Error::InvalidValue("invalid value") }
-
- fn invalid_length(len: usize) -> Self { Error::InvalidLength(len) }
-
- #[cfg(any(feature = "std", feature = "collections"))]
- fn unknown_variant(variant: &str) -> Self { Error::UnknownVariant(String::from(variant)) }
- #[cfg(any(feature = "std", feature = "collections"))]
- fn unknown_field(field: &str) -> Self { Error::UnknownField(String::from(field)) }
-
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn unknown_variant(variant: &str) -> Self { Error::UnknownVariant("unknown variant") }
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn unknown_field(field: &str) -> Self { Error::UnknownField("unknown field") }
- fn missing_field(field: &'static str) -> Self { Error::MissingField(field) }
-}
-
-impl fmt::Display for Error {
- fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- match *self {
- Error::Custom(ref s) => write!(formatter, "{}", s),
- Error::EndOfStream => formatter.write_str("End of stream"),
- Error::InvalidType(ty) => write!(formatter, "Invalid type, expected `{:?}`", ty),
- Error::InvalidValue(ref value) => write!(formatter, "Invalid value: {}", value),
- Error::InvalidLength(len) => write!(formatter, "Invalid length: {}", len),
- Error::UnknownVariant(ref variant) => {
- write!(formatter, "Unknown variant: {}", variant)
- }
- Error::UnknownField(ref field) => write!(formatter, "Unknown field: {}", field),
- Error::MissingField(field) => write!(formatter, "Missing field: {}", field),
- }
- }
-}
-
-impl error::Error for Error {
- fn description(&self) -> &str {
- "Serde Deserialization Error"
- }
-
- fn cause(&self) -> Option<&error::Error> {
- None
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// This trait converts primitive types into a deserializer.
-pub trait ValueDeserializer<E: de::Error = Error> {
- /// The actual deserializer type.
- type Deserializer: de::Deserializer<Error=E>;
-
- /// Convert this value into a deserializer.
- fn into_deserializer(self) -> Self::Deserializer;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-impl<E> ValueDeserializer<E> for ()
- where E: de::Error,
-{
- type Deserializer = UnitDeserializer<E>;
-
- fn into_deserializer(self) -> UnitDeserializer<E> {
- UnitDeserializer(PhantomData)
- }
-}
-
-/// A helper deserializer that deserializes a `()`.
-pub struct UnitDeserializer<E>(PhantomData<E>);
-
-impl<E> de::Deserializer for UnitDeserializer<E>
- where E: de::Error
-{
- type Error = E;
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
- }
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- visitor.visit_unit()
- }
-
- fn deserialize_option<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- visitor.visit_none()
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-macro_rules! primitive_deserializer {
- ($ty:ty, $name:ident, $method:ident) => {
- /// A helper deserializer that deserializes a number.
- pub struct $name<E>(Option<$ty>, PhantomData<E>);
-
- impl<E> ValueDeserializer<E> for $ty
- where E: de::Error,
- {
- type Deserializer = $name<E>;
-
- fn into_deserializer(self) -> $name<E> {
- $name(Some(self), PhantomData)
- }
- }
-
- impl<E> de::Deserializer for $name<E>
- where E: de::Error,
- {
- type Error = E;
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str
- string unit option seq seq_fixed_size bytes map unit_struct
- newtype_struct tuple_struct struct struct_field tuple enum
- ignored_any
- }
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- match self.0.take() {
- Some(v) => visitor.$method(v),
- None => Err(de::Error::end_of_stream()),
- }
- }
- }
- }
-}
-
-primitive_deserializer!(bool, BoolDeserializer, visit_bool);
-primitive_deserializer!(i8, I8Deserializer, visit_i8);
-primitive_deserializer!(i16, I16Deserializer, visit_i16);
-primitive_deserializer!(i32, I32Deserializer, visit_i32);
-primitive_deserializer!(i64, I64Deserializer, visit_i64);
-primitive_deserializer!(isize, IsizeDeserializer, visit_isize);
-primitive_deserializer!(u8, U8Deserializer, visit_u8);
-primitive_deserializer!(u16, U16Deserializer, visit_u16);
-primitive_deserializer!(u32, U32Deserializer, visit_u32);
-primitive_deserializer!(u64, U64Deserializer, visit_u64);
-primitive_deserializer!(usize, UsizeDeserializer, visit_usize);
-primitive_deserializer!(f32, F32Deserializer, visit_f32);
-primitive_deserializer!(f64, F64Deserializer, visit_f64);
-primitive_deserializer!(char, CharDeserializer, visit_char);
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A helper deserializer that deserializes a `&str`.
-pub struct StrDeserializer<'a, E>(Option<&'a str>, PhantomData<E>);
-
-impl<'a, E> ValueDeserializer<E> for &'a str
- where E: de::Error,
-{
- type Deserializer = StrDeserializer<'a, E>;
-
- fn into_deserializer(self) -> StrDeserializer<'a, E> {
- StrDeserializer(Some(self), PhantomData)
- }
-}
-
-impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
- where E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- match self.0.take() {
- Some(v) => visitor.visit_str(v),
- None => Err(de::Error::end_of_stream()),
- }
- }
-
- fn deserialize_enum<V>(&mut self,
- _name: &str,
- _variants: &'static [&'static str],
- mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::EnumVisitor,
- {
- visitor.visit(self)
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any
- }
-}
-
-impl<'a, E> de::VariantVisitor for StrDeserializer<'a, E>
- where E: de::Error,
-{
- type Error = E;
-
- fn visit_variant<T>(&mut self) -> Result<T, Self::Error>
- where T: de::Deserialize,
- {
- de::Deserialize::deserialize(self)
- }
-
- fn visit_unit(&mut self) -> Result<(), Self::Error> {
- Ok(())
- }
-
- fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
- where T: super::Deserialize,
- {
- let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
- Ok(value)
- }
-
- fn visit_tuple<V>(&mut self,
- _len: usize,
- _visitor: V) -> Result<V::Value, Self::Error>
- where V: super::Visitor
- {
- Err(super::Error::invalid_type(super::Type::TupleVariant))
- }
-
- fn visit_struct<V>(&mut self,
- _fields: &'static [&'static str],
- _visitor: V) -> Result<V::Value, Self::Error>
- where V: super::Visitor
- {
- Err(super::Error::invalid_type(super::Type::StructVariant))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A helper deserializer that deserializes a `String`.
-#[cfg(any(feature = "std", feature = "collections"))]
-pub struct StringDeserializer<E>(Option<String>, PhantomData<E>);
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<E> ValueDeserializer<E> for String
- where E: de::Error,
-{
- type Deserializer = StringDeserializer<E>;
-
- fn into_deserializer(self) -> StringDeserializer<E> {
- StringDeserializer(Some(self), PhantomData)
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<E> de::Deserializer for StringDeserializer<E>
- where E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- match self.0.take() {
- Some(string) => visitor.visit_string(string),
- None => Err(de::Error::end_of_stream()),
- }
- }
-
- fn deserialize_enum<V>(&mut self,
- _name: &str,
- _variants: &'static [&'static str],
- mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::EnumVisitor,
- {
- visitor.visit(self)
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<'a, E> de::VariantVisitor for StringDeserializer<E>
- where E: de::Error,
-{
- type Error = E;
-
- fn visit_variant<T>(&mut self) -> Result<T, Self::Error>
- where T: de::Deserialize,
- {
- de::Deserialize::deserialize(self)
- }
-
- fn visit_unit(&mut self) -> Result<(), Self::Error> {
- Ok(())
- }
-
- fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
- where T: super::Deserialize,
- {
- let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
- Ok(value)
- }
-
- fn visit_tuple<V>(&mut self,
- _len: usize,
- _visitor: V) -> Result<V::Value, Self::Error>
- where V: super::Visitor
- {
- Err(super::Error::invalid_type(super::Type::TupleVariant))
- }
-
- fn visit_struct<V>(&mut self,
- _fields: &'static [&'static str],
- _visitor: V) -> Result<V::Value, Self::Error>
- where V: super::Visitor
- {
- Err(super::Error::invalid_type(super::Type::StructVariant))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A helper deserializer that deserializes a `String`.
-#[cfg(any(feature = "std", feature = "collections"))]
-pub struct CowStrDeserializer<'a, E>(Option<Cow<'a, str>>, PhantomData<E>);
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
- where E: de::Error,
-{
- type Deserializer = CowStrDeserializer<'a, E>;
-
- fn into_deserializer(self) -> CowStrDeserializer<'a, E> {
- CowStrDeserializer(Some(self), PhantomData)
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
- where E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- match self.0.take() {
- Some(Cow::Borrowed(string)) => visitor.visit_str(string),
- Some(Cow::Owned(string)) => visitor.visit_string(string),
- None => Err(de::Error::end_of_stream()),
- }
- }
-
- fn deserialize_enum<V>(&mut self,
- _name: &str,
- _variants: &'static [&'static str],
- mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::EnumVisitor,
- {
- visitor.visit(self)
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<'a, E> de::VariantVisitor for CowStrDeserializer<'a, E>
- where E: de::Error,
-{
- type Error = E;
-
- fn visit_variant<T>(&mut self) -> Result<T, Self::Error>
- where T: de::Deserialize,
- {
- de::Deserialize::deserialize(self)
- }
-
- fn visit_unit(&mut self) -> Result<(), Self::Error> {
- Ok(())
- }
-
- fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
- where T: super::Deserialize,
- {
- let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
- Ok(value)
- }
-
- fn visit_tuple<V>(&mut self,
- _len: usize,
- _visitor: V) -> Result<V::Value, Self::Error>
- where V: super::Visitor
- {
- Err(super::Error::invalid_type(super::Type::TupleVariant))
- }
-
- fn visit_struct<V>(&mut self,
- _fields: &'static [&'static str],
- _visitor: V) -> Result<V::Value, Self::Error>
- where V: super::Visitor
- {
- Err(super::Error::invalid_type(super::Type::StructVariant))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A helper deserializer that deserializes a sequence.
-pub struct SeqDeserializer<I, E> {
- iter: I,
- len: usize,
- marker: PhantomData<E>,
-}
-
-impl<I, E> SeqDeserializer<I, E>
- where E: de::Error,
-{
- /// Construct a new `SeqDeserializer<I>`.
- pub fn new(iter: I, len: usize) -> Self {
- SeqDeserializer {
- iter: iter,
- len: len,
- marker: PhantomData,
- }
- }
-}
-
-impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
- where I: Iterator<Item=T>,
- T: ValueDeserializer<E>,
- E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- visitor.visit_seq(self)
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
- }
-}
-
-impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
- where I: Iterator<Item=T>,
- T: ValueDeserializer<E>,
- E: de::Error,
-{
- type Error = E;
-
- fn visit<V>(&mut self) -> Result<Option<V>, Self::Error>
- where V: de::Deserialize
- {
- match self.iter.next() {
- Some(value) => {
- self.len -= 1;
- let mut de = value.into_deserializer();
- Ok(Some(try!(de::Deserialize::deserialize(&mut de))))
- }
- None => Ok(None),
- }
- }
-
- fn end(&mut self) -> Result<(), Self::Error> {
- if self.len == 0 {
- Ok(())
- } else {
- Err(de::Error::invalid_length(self.len))
- }
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- (self.len, Some(self.len))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<T, E> ValueDeserializer<E> for Vec<T>
- where T: ValueDeserializer<E>,
- E: de::Error,
-{
- type Deserializer = SeqDeserializer<vec::IntoIter<T>, E>;
-
- fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- SeqDeserializer::new(self.into_iter(), len)
- }
-}
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<T, E> ValueDeserializer<E> for BTreeSet<T>
- where T: ValueDeserializer<E> + Eq + Ord,
- E: de::Error,
-{
- type Deserializer = SeqDeserializer<btree_set::IntoIter<T>, E>;
-
- fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- SeqDeserializer::new(self.into_iter(), len)
- }
-}
-
-#[cfg(feature = "std")]
-impl<T, E> ValueDeserializer<E> for HashSet<T>
- where T: ValueDeserializer<E> + Eq + Hash,
- E: de::Error,
-{
- type Deserializer = SeqDeserializer<hash_set::IntoIter<T>, E>;
-
- fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- SeqDeserializer::new(self.into_iter(), len)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A helper deserializer that deserializes a sequence using a `SeqVisitor`.
-pub struct SeqVisitorDeserializer<V_, E> {
- visitor: V_,
- marker: PhantomData<E>,
-}
-
-impl<V_, E> SeqVisitorDeserializer<V_, E>
- where V_: de::SeqVisitor<Error = E>,
- E: de::Error,
-{
- /// Construct a new `SeqVisitorDeserializer<V_, E>`.
- pub fn new(visitor: V_) -> Self {
- SeqVisitorDeserializer{
- visitor: visitor,
- marker: PhantomData
- }
- }
-}
-
-impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
- where V_: de::SeqVisitor<Error = E>,
- E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V: de::Visitor>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error> {
- visitor.visit_seq(&mut self.visitor)
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A helper deserializer that deserializes a map.
-pub struct MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
- E: de::Error,
-{
- iter: I,
- value: Option<V>,
- len: Option<usize>,
- marker: PhantomData<E>,
-}
-
-impl<I, K, V, E> MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
- E: de::Error,
-{
- /// Construct a new `MapDeserializer<I, K, V, E>` with a specific length.
- pub fn new(iter: I, len: usize) -> Self {
- MapDeserializer {
- iter: iter,
- value: None,
- len: Some(len),
- marker: PhantomData,
- }
- }
-
- /// Construct a new `MapDeserializer<I, K, V, E>` that is not bounded
- /// by a specific length and that delegates to `iter` for its size hint.
- pub fn unbounded(iter: I) -> Self {
- MapDeserializer {
- iter: iter,
- value: None,
- len: None,
- marker: PhantomData,
- }
- }
-
- fn next(&mut self) -> Option<(K, V)> {
- self.iter.next().map(|(k, v)| {
- if let Some(len) = self.len.as_mut() {
- *len -= 1;
- }
- (k, v)
- })
- }
-}
-
-impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
- E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V_>(&mut self, mut visitor: V_) -> Result<V_::Value, Self::Error>
- where V_: de::Visitor,
- {
- visitor.visit_map(self)
- }
-
- fn deserialize_seq<V_>(&mut self, mut visitor: V_) -> Result<V_::Value, Self::Error>
- where V_: de::Visitor,
- {
- visitor.visit_seq(self)
- }
-
- fn deserialize_seq_fixed_size<V_>(&mut self, len: usize, mut visitor: V_) -> Result<V_::Value, Self::Error>
- where V_: de::Visitor,
- {
- match self.len {
- Some(map_len) if map_len == len => visitor.visit_seq(self),
- Some(_) => Err(de::Error::invalid_length(len)),
- None => visitor.visit_seq(self),
- }
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option bytes map unit_struct newtype_struct tuple_struct struct
- struct_field tuple enum ignored_any
- }
-}
-
-impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
- E: de::Error,
-{
- type Error = E;
-
- fn visit_key<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: de::Deserialize,
- {
- match self.next() {
- Some((key, value)) => {
- self.value = Some(value);
- let mut de = key.into_deserializer();
- de::Deserialize::deserialize(&mut de).map(Some)
- }
- None => Ok(None),
- }
- }
-
- fn visit_value<T>(&mut self) -> Result<T, Self::Error>
- where T: de::Deserialize,
- {
- match self.value.take() {
- Some(value) => {
- let mut de = value.into_deserializer();
- de::Deserialize::deserialize(&mut de)
- }
- None => {
- Err(de::Error::end_of_stream())
- }
- }
- }
-
- fn end(&mut self) -> Result<(), Self::Error> {
- match self.len {
- Some(len) if len > 0 => Err(de::Error::invalid_length(len)),
- _ => Ok(())
- }
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.len.map_or_else(
- || self.iter.size_hint(),
- |len| (len, Some(len)))
- }
-}
-
-impl<I, K, V, E> de::SeqVisitor for MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
- E: de::Error,
-{
- type Error = E;
-
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: de::Deserialize,
- {
- match self.next() {
- Some(kv) => {
- let mut de = PairDeserializer(Some(kv), PhantomData);
- de::Deserialize::deserialize(&mut de).map(Some)
- }
- None => Ok(None),
- }
- }
-
- fn end(&mut self) -> Result<(), Self::Error> {
- de::MapVisitor::end(self)
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- de::MapVisitor::size_hint(self)
- }
-}
-
-// Used in the `impl SeqVisitor for MapDeserializer` to visit the map as a
-// sequence of pairs.
-struct PairDeserializer<A, B, E>(Option<(A, B)>, PhantomData<E>);
-
-impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
- where A: ValueDeserializer<E>,
- B: ValueDeserializer<E>,
- E: de::Error
-{
- type Error = E;
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option bytes map unit_struct newtype_struct tuple_struct struct
- struct_field tuple enum ignored_any
- }
-
- fn deserialize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- self.deserialize_seq(visitor)
- }
-
- fn deserialize_seq<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- match self.0.take() {
- Some((k, v)) => {
- visitor.visit_seq(PairVisitor(Some(k), Some(v), PhantomData))
- }
- None => Err(de::Error::end_of_stream()),
- }
- }
-
- fn deserialize_seq_fixed_size<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- if len == 2 {
- self.deserialize_seq(visitor)
- } else {
- Err(de::Error::invalid_length(len))
- }
- }
-}
-
-struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
-
-impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
- where A: ValueDeserializer<E>,
- B: ValueDeserializer<E>,
- E: de::Error,
-{
- type Error = E;
-
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: de::Deserialize,
- {
- if let Some(k) = self.0.take() {
- let mut de = k.into_deserializer();
- de::Deserialize::deserialize(&mut de).map(Some)
- } else if let Some(v) = self.1.take() {
- let mut de = v.into_deserializer();
- de::Deserialize::deserialize(&mut de).map(Some)
- } else {
- Ok(None)
- }
- }
-
- fn end(&mut self) -> Result<(), Self::Error> {
- if self.1.is_none() {
- Ok(())
- } else {
- Err(de::Error::invalid_length(self.size_hint().0))
- }
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- let len = if self.0.is_some() {
- 2
- } else if self.1.is_some() {
- 1
- } else {
- 0
- };
- (len, Some(len))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
- where K: ValueDeserializer<E> + Eq + Ord,
- V: ValueDeserializer<E>,
- E: de::Error,
-{
- type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, K, V, E>;
-
- fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- MapDeserializer::new(self.into_iter(), len)
- }
-}
-
-#[cfg(feature = "std")]
-impl<K, V, E> ValueDeserializer<E> for HashMap<K, V>
- where K: ValueDeserializer<E> + Eq + Hash,
- V: ValueDeserializer<E>,
- E: de::Error,
-{
- type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, K, V, E>;
-
- fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- MapDeserializer::new(self.into_iter(), len)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A helper deserializer that deserializes a map using a `MapVisitor`.
-pub struct MapVisitorDeserializer<V_, E> {
- visitor: V_,
- marker: PhantomData<E>,
-}
-
-impl<V_, E> MapVisitorDeserializer<V_, E>
- where V_: de::MapVisitor<Error = E>,
- E: de::Error,
-{
- /// Construct a new `MapVisitorDeserializer<V_, E>`.
- pub fn new(visitor: V_) -> Self {
- MapVisitorDeserializer{
- visitor: visitor,
- marker: PhantomData
- }
- }
-}
-
-impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
- where V_: de::MapVisitor<Error = E>,
- E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V: de::Visitor>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error> {
- visitor.visit_map(&mut self.visitor)
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-impl<'a, E> ValueDeserializer<E> for bytes::Bytes<'a>
- where E: de::Error,
-{
- type Deserializer = BytesDeserializer<'a, E>;
-
- fn into_deserializer(self) -> BytesDeserializer<'a, E> {
- BytesDeserializer(Some(self.into()), PhantomData)
- }
-}
-
-/// A helper deserializer that deserializes a `&[u8]`.
-pub struct BytesDeserializer<'a, E> (Option<&'a [u8]>, PhantomData<E>);
-
-impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
- where E: de::Error
-{
- type Error = E;
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- match self.0.take() {
- Some(bytes) => visitor.visit_bytes(bytes),
- None => Err(de::Error::end_of_stream()),
- }
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<E> ValueDeserializer<E> for bytes::ByteBuf
- where E: de::Error,
-{
- type Deserializer = ByteBufDeserializer<E>;
-
- fn into_deserializer(self) -> Self::Deserializer {
- ByteBufDeserializer(Some(self.into()), PhantomData)
- }
-}
-
-/// A helper deserializer that deserializes a `Vec<u8>`.
-#[cfg(any(feature = "std", feature = "collections"))]
-pub struct ByteBufDeserializer<E>(Option<Vec<u8>>, PhantomData<E>);
-
-#[cfg(any(feature = "std", feature = "collections"))]
-impl<E> de::Deserializer for ByteBufDeserializer<E>
- where E: de::Error,
-{
- type Error = E;
-
- fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
- {
- match self.0.take() {
- Some(bytes) => visitor.visit_byte_buf(bytes),
- None => Err(de::Error::end_of_stream()),
- }
- }
-
- forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
- }
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/error.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-//! A stand-in for `std::error`
-use core::any::TypeId;
-use core::fmt::{Debug, Display};
-
-
-/// A stand-in for `std::error::Error`, which requires no allocation.
-#[cfg(feature = "unstable")]
-pub trait Error: Debug + Display + ::core::marker::Reflect {
- /// 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 }
-
- /// Get the `TypeId` of `self`
- #[doc(hidden)]
- fn type_id(&self) -> TypeId where Self: 'static {
- TypeId::of::<Self>()
- }
-}
-
-/// A stand-in for `std::error::Error`, which requires no allocation.
-#[cfg(not(feature = "unstable"))]
-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 }
-
- /// Stubbed! Returns type_id of `()`
- #[doc(hidden)]
- fn type_id(&self) -> TypeId where Self: 'static {
- TypeId::of::<()>()
- }
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/iter.rs
+++ /dev/null
@@ -1,61 +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)),
- }
- }
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/lib.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-//! Serde Serialization Framework
-//!
-//! Serde is a powerful framework that enables serialization libraries to generically serialize
-//! Rust data structures without the overhead of runtime type information. In many situations, the
-//! handshake protocol between serializers and serializees can be completely optimized away,
-//! leaving serde to perform roughly the same speed as a hand written serializer for a specific
-//! type.
-//!
-//! For a detailed tutorial on the different ways to use serde please check out the
-//! [github repository](https://github.com/serde-rs/serde)
-
-#![doc(html_root_url="https://docs.serde.rs")]
-#![cfg_attr(not(feature = "std"), no_std)]
-#![cfg_attr(feature = "unstable", feature(reflect_marker, unicode, nonzero, plugin, step_trait, zero_one))]
-#![cfg_attr(feature = "alloc", feature(alloc))]
-#![cfg_attr(feature = "collections", feature(collections, enumset))]
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-#![cfg_attr(feature = "clippy", allow(linkedlist))]
-
-#![cfg_attr(any(not(feature = "std"), feature = "unstable"), allow(unused_variables, unused_imports, unused_features, dead_code))]
-
-#![deny(missing_docs)]
-
-#[cfg(all(feature = "unstable", feature = "collections"))]
-extern crate collections;
-
-#[cfg(all(feature = "unstable", feature = "alloc"))]
-extern crate alloc;
-
-#[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};
- #[cfg(feature = "unstable")]
- extern crate core;
- #[cfg(feature = "unstable")]
- pub use self::core::nonzero;
-}
-
-pub use ser::{Serialize, Serializer};
-pub use de::{Deserialize, Deserializer, Error};
-
-#[cfg(not(feature = "std"))]
-macro_rules! format {
- ($s:expr, $($rest:tt)*) => ($s)
-}
-
-#[macro_use]
-mod macros;
-
-pub mod bytes;
-pub mod de;
-#[cfg(feature = "std")]
-pub mod iter;
-pub mod ser;
-#[cfg(not(feature = "std"))]
-pub mod error;
-mod utils;
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/macros.rs
+++ /dev/null
@@ -1,179 +0,0 @@
-#[cfg(feature = "std")]
-#[doc(hidden)]
-#[macro_export]
-macro_rules! forward_to_deserialize_method {
- ($func:ident($($arg:ty),*)) => {
- #[inline]
- fn $func<__V>(&mut 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>(&mut self, $(_: $arg,)* visitor: __V) -> ::core::result::Result<__V::Value, Self::Error>
- where __V: $crate::de::Visitor
- {
- self.deserialize(visitor)
- }
- };
-}
-
-#[cfg(feature = "std")]
-#[doc(hidden)]
-#[macro_export]
-macro_rules! forward_to_deserialize_enum {
- () => {
- #[inline]
- fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _: __V) -> ::std::result::Result<__V::Value, Self::Error>
- where __V: $crate::de::EnumVisitor
- {
- Err($crate::de::Error::invalid_type($crate::de::Type::Enum))
- }
- };
-}
-
-#[cfg(not(feature = "std"))]
-#[doc(hidden)]
-#[macro_export]
-macro_rules! forward_to_deserialize_enum {
- () => {
- #[inline]
- fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _: __V) -> ::core::result::Result<__V::Value, Self::Error>
- where __V: $crate::de::EnumVisitor
- {
- Err($crate::de::Error::invalid_type($crate::de::Type::Enum))
- }
- };
-}
-
-#[doc(hidden)]
-#[macro_export]
-macro_rules! forward_to_deserialize_helper {
- (bool) => {
- forward_to_deserialize_method!{deserialize_bool()}
- };
- (usize) => {
- forward_to_deserialize_method!{deserialize_usize()}
- };
- (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()}
- };
- (isize) => {
- forward_to_deserialize_method!{deserialize_isize()}
- };
- (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()}
- };
- (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)}
- };
- (ignored_any) => {
- forward_to_deserialize_method!{deserialize_ignored_any()}
- };
- (enum) => {
- forward_to_deserialize_enum!();
- };
-}
-
-/// Helper to forward `Deserializer` methods to `Deserializer::deserialize`.
-/// Every given method ignores all arguments and forwards to `deserialize`.
-/// Note that `deserialize_enum` simply returns an `Error::invalid_type`; a
-/// better approach is tracked in [serde-rs/serde#521][1].
-///
-/// ```rust,ignore
-/// impl Deserializer for MyDeserializer {
-/// fn deserialize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
-/// where V: Visitor
-/// {
-/// /* ... */
-/// }
-///
-/// forward_to_deserialize! {
-/// bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
-/// unit option seq seq_fixed_size bytes map unit_struct newtype_struct
-/// tuple_struct struct struct_field tuple enum ignored_any
-/// }
-/// }
-/// ```
-///
-/// [1]: https://github.com/serde-rs/serde/issues/521
-#[macro_export]
-macro_rules! forward_to_deserialize {
- ($($func:ident)*) => {
- $(forward_to_deserialize_helper!{$func})*
- };
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/ser/impls.rs
+++ /dev/null
@@ -1,725 +0,0 @@
-//! Implementations for all of Rust's builtin types. Tuples implement the `Serialize` trait if they
-//! have at most 16 fields. Arrays implement the `Serialize` trait if their length is 32 or less.
-//! You can always forward array serialization to slice serialization, which works for any length.
-//! Long tuples are best replaced by tuple structs, for which you can use `derive(Serialize)`. In
-//! that case the number of fields is irrelevant.
-
-#[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(all(feature = "unstable", feature = "collections"))]
-use collections::enum_set::{CLike, EnumSet};
-#[cfg(all(feature = "unstable", feature = "collections"))]
-use collections::borrow::ToOwned;
-
-use core::hash::{Hash, BuildHasher};
-#[cfg(feature = "unstable")]
-use core::iter;
-#[cfg(feature = "std")]
-use std::net;
-#[cfg(feature = "unstable")]
-use core::num;
-#[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::{
- Error,
- Serialize,
- Serializer,
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-macro_rules! impl_visit {
- ($ty:ty, $method:ident) => {
- impl Serialize for $ty {
- #[inline]
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- serializer.$method(*self)
- }
- }
- }
-}
-
-impl_visit!(bool, serialize_bool);
-impl_visit!(isize, serialize_isize);
-impl_visit!(i8, serialize_i8);
-impl_visit!(i16, serialize_i16);
-impl_visit!(i32, serialize_i32);
-impl_visit!(i64, serialize_i64);
-impl_visit!(usize, serialize_usize);
-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: &mut S) -> Result<(), 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: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- (&self[..]).serialize(serializer)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-impl<T> Serialize for Option<T> where T: Serialize {
- #[inline]
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), 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: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- serializer.serialize_unit_struct("PhantomData")
- }
-}
-
-
-///////////////////////////////////////////////////////////////////////////////
-
-impl<T> Serialize for [T]
- where T: Serialize,
-{
- #[inline]
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- let mut state = try!(serializer.serialize_seq(Some(self.len())));
- for e in self {
- try!(serializer.serialize_seq_elt(&mut state, e));
- }
- serializer.serialize_seq_end(state)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-macro_rules! array_impls {
- ($len:expr) => {
- impl<T> Serialize for [T; $len] where T: Serialize {
- #[inline]
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- let mut state = try!(serializer.serialize_seq_fixed_size($len));
- for e in self {
- try!(serializer.serialize_seq_elt(&mut state, e));
- }
- serializer.serialize_seq_end(state)
- }
- }
- }
-}
-
-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: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- let mut state = try!(serializer.serialize_seq(Some(self.len())));
- for e in self {
- try!(serializer.serialize_seq_elt(&mut state, e));
- }
- serializer.serialize_seq_end(state)
- }
- }
-}
-
-#[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(all(feature = "unstable", feature = "collections"))]
-impl<T> Serialize for EnumSet<T>
- where T: Serialize + CLike
-{
- 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 A: Serialize + Clone + iter::Step + num::One,
- for<'a> &'a A: ops::Add<&'a A, Output = A>,
-{
- #[inline]
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- let len = iter::Step::steps_between(&self.start, &self.end, &A::one());
- let mut state = try!(serializer.serialize_seq(len));
- for e in self.clone() {
- try!(serializer.serialize_seq_elt(&mut state, e));
- }
- serializer.serialize_seq_end(state)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-impl Serialize for () {
- #[inline]
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), 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: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- let mut state = try!(serializer.serialize_tuple($len));
- $(
- try!(serializer.serialize_tuple_elt(&mut state, &self.$idx));
- )+
- serializer.serialize_tuple_end(state)
- }
- }
- )+
- }
-}
-
-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: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- let mut state = try!(serializer.serialize_map(Some(self.len())));
- for (k, v) in self {
- try!(serializer.serialize_map_key(&mut state, k));
- try!(serializer.serialize_map_value(&mut state, v));
- }
- serializer.serialize_map_end(state)
- }
- }
-}
-
-#[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: &mut S) -> Result<(), 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: &mut S) -> Result<(), 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: &mut S) -> Result<(), 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: &mut S) -> Result<(), 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: &mut S) -> Result<(), 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: &mut S) -> Result<(), 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: &mut S) -> Result<(), 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: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- let mut state = try!(serializer.serialize_struct("Duration", 2));
- try!(serializer.serialize_struct_elt(&mut state, "secs", self.as_secs()));
- try!(serializer.serialize_struct_elt(&mut state, "nanos", self.subsec_nanos()));
- serializer.serialize_struct_end(state)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(feature = "std")]
-impl Serialize for net::IpAddr {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- self.to_string().serialize(serializer)
- }
-}
-
-#[cfg(feature = "std")]
-impl Serialize for net::Ipv4Addr {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- self.to_string().serialize(serializer)
- }
-}
-
-#[cfg(feature = "std")]
-impl Serialize for net::Ipv6Addr {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- self.to_string().serialize(serializer)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(feature = "std")]
-impl Serialize for net::SocketAddr {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), 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: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- self.to_string().serialize(serializer)
- }
-}
-
-#[cfg(feature = "std")]
-impl Serialize for net::SocketAddrV6 {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- self.to_string().serialize(serializer)
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#[cfg(feature = "std")]
-impl Serialize for path::Path {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer,
- {
- match self.to_str() {
- Some(s) => s.serialize(serializer),
- None => Err(Error::invalid_value("Path contains invalid UTF-8 characters")),
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl Serialize for path::PathBuf {
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), 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: &mut S) -> Result<(), S::Error> where S: Serializer {
- (**self).serialize(serializer)
- }
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/ser/mod.rs
+++ /dev/null
@@ -1,412 +0,0 @@
-//! Generic serialization framework.
-//! # For Developers who want to serialize objects
-//! Implement the `Serialize` trait for the type of objects you want to serialize. Call methods of
-//! the `serializer` object. For which methods to call and how to do so, look at the documentation
-//! of the `Serializer` trait.
-//!
-//! # For Serialization Format Developers
-//! Implement the `Serializer` trait for a structure that contains fields that enable it to write
-//! the serialization result to your target. When a method's argument is an object of type
-//! `Serialize`, you can either forward the serializer object (`self`) or create a new one,
-//! depending on the quirks of your format.
-
-#[cfg(feature = "std")]
-use std::error;
-#[cfg(not(feature = "std"))]
-use error;
-
-#[cfg(all(feature = "collections", not(feature = "std")))]
-use collections::String;
-
-pub mod impls;
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// `Error` is a trait that allows a `Serialize` to generically create a
-/// `Serializer` error.
-pub trait Error: Sized + error::Error {
- /// Raised when there is a general error when serializing a type.
- #[cfg(any(feature = "std", feature = "collections"))]
- fn custom<T: Into<String>>(msg: T) -> Self;
-
- /// Raised when there is a general error when serializing a type.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn custom<T: Into<&'static str>>(msg: T) -> Self;
-
- /// Raised when a `Serialize` was passed an incorrect value.
- fn invalid_value(msg: &str) -> Self {
- Error::custom(format!("invalid value: {}", msg))
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A trait that describes a type that can be serialized by a `Serializer`.
-pub trait Serialize {
- /// Serializes this value into this serializer.
- fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
- where S: Serializer;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-/// A trait that describes a type that can serialize a stream of values into the underlying format.
-///
-/// # For `Serialize` Developers
-/// Non-aggrergate types like integers and strings can be serialized directly by calling the
-/// appropriate function. For Aggregate types there's an initial `serialize_T` method that yields
-/// a State object that you should not interact with. For each part of the aggregate there's a
-/// `serialize_T_elt` method that allows you to pass values or key/value pairs. The types of the
-/// values or the keys may change between calls, but the serialization format may not necessarily
-/// accept it. The `serialize_T_elt` method also takes a mutable reference to the state object.
-/// Make sure that you always use the same state object and only the state object that was returned
-/// by the `serialize_T` method. Finally, when your object is done, call the `serialize_T_end`
-/// method and pass the state object by value
-///
-/// # For Serialization Format Developers
-/// If your format has different situations where it accepts different types, create a
-/// `Serializer` for each situation. You can create the sub-`Serializer` in one of the aggregate
-/// `serialize_T` methods and return it as a state object. Remember to also set the corresponding
-/// associated type `TState`. In the `serialize_T_elt` methods you will be given a mutable
-/// reference to that state. You do not need to do any additional checks for the correctness of the
-/// state object, as it is expected that the user will not modify it. Due to the generic nature
-/// of the `Serialize` impls, modifying the object is impossible on stable Rust.
-pub trait Serializer {
- /// The error type that can be returned if some error occurs during serialization.
- type Error: Error;
-
- /// A state object that is initialized by `serialize_seq`, passed to
- /// `serialize_seq_elt`, and consumed by `serialize_seq_end`. Use `()` if no
- /// state is required.
- type SeqState;
- /// A state object that is initialized by `serialize_tuple`, passed to
- /// `serialize_tuple_elt`, and consumed by `serialize_tuple_end`. Use `()`
- /// if no state is required.
- type TupleState;
- /// A state object that is initialized by `serialize_tuple_struct`, passed
- /// to `serialize_tuple_struct_elt`, and consumed by
- /// `serialize_tuple_struct_end`. Use `()` if no state is required.
- type TupleStructState;
- /// A state object that is initialized by `serialize_tuple_variant`, passed
- /// to `serialize_tuple_variant_elt`, and consumed by
- /// `serialize_tuple_variant_end`. Use `()` if no state is required.
- type TupleVariantState;
- /// A state object that is initialized by `serialize_map`, passed to
- /// `serialize_map_elt`, and consumed by `serialize_map_end`. Use `()` if no
- /// state is required.
- type MapState;
- /// A state object that is initialized by `serialize_struct`, passed to
- /// `serialize_struct_elt`, and consumed by `serialize_struct_end`. Use `()`
- /// if no state is required.
- type StructState;
- /// A state object that is initialized by `serialize_struct_variant`, passed
- /// to `serialize_struct_variant_elt`, and consumed by
- /// `serialize_struct_variant_end`. Use `()` if no state is required.
- type StructVariantState;
-
- /// Serializes a `bool` value.
- fn serialize_bool(&mut self, v: bool) -> Result<(), Self::Error>;
-
- /// Serializes an `isize` value. If the format does not differentiate
- /// between `isize` and `i64`, a reasonable implementation would be to cast
- /// the value to `i64` and forward to `serialize_i64`.
- fn serialize_isize(&mut self, v: isize) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: i8) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: i16) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: i32) -> Result<(), Self::Error>;
-
- /// Serializes an `i64` value.
- fn serialize_i64(&mut self, v: i64) -> Result<(), Self::Error>;
-
- /// Serializes a `usize` value. If the format does not differentiate between
- /// `usize` and `u64`, a reasonable implementation would be to cast the
- /// value to `u64` and forward to `serialize_u64`.
- fn serialize_usize(&mut self, v: usize) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: u8) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: u16) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: u32) -> Result<(), Self::Error>;
-
- /// `Serializes a `u64` value.
- fn serialize_u64(&mut self, v: u64) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: f32) -> Result<(), Self::Error>;
-
- /// Serializes an `f64` value.
- fn serialize_f64(&mut self, v: f64) -> Result<(), Self::Error>;
-
- /// Serializes 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(&mut self, v: char) -> Result<(), Self::Error>;
-
- /// Serializes a `&str`.
- fn serialize_str(&mut self, value: &str) -> Result<(), Self::Error>;
-
- /// 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
- /// let mut state = try!(self.serialize_seq(value));
- /// for b in value {
- /// try!(self.serialize_seq_elt(&mut state, b));
- /// }
- /// self.serialize_seq_end(state)
- /// ```
- fn serialize_bytes(&mut self, value: &[u8]) -> Result<(), Self::Error>;
-
- /// Serializes a `()` value. It's reasonable to just not serialize anything.
- fn serialize_unit(&mut self) -> Result<(), Self::Error>;
-
- /// Serializes a unit struct value. A reasonable implementation would be to
- /// forward to `serialize_unit`.
- fn serialize_unit_struct(
- &mut self,
- name: &'static str,
- ) -> Result<(), Self::Error>;
-
- /// Serializes a unit variant, otherwise known as a variant with no
- /// arguments. A reasonable implementation would be to forward to
- /// `serialize_unit`.
- fn serialize_unit_variant(
- &mut self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- ) -> Result<(), Self::Error>;
-
- /// Allows a tuple struct with a single element, also known as a newtype
- /// struct, to be more efficiently serialized than a tuple struct with
- /// multiple items. A reasonable implementation would be to forward to
- /// `serialize_tuple_struct` or to just serialize the inner value without wrapping.
- fn serialize_newtype_struct<T: Serialize>(
- &mut self,
- name: &'static str,
- value: T,
- ) -> Result<(), Self::Error>;
-
- /// Allows a variant with a single item to be more efficiently serialized
- /// than a variant with multiple items. A reasonable implementation would be
- /// to forward to `serialize_tuple_variant`.
- fn serialize_newtype_variant<T: Serialize>(
- &mut self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- value: T,
- ) -> Result<(), Self::Error>;
-
- /// Serializes a `None` value.
- fn serialize_none(&mut self) -> Result<(), Self::Error>;
-
- /// Serializes a `Some(...)` value.
- fn serialize_some<T: Serialize>(
- &mut self,
- value: T,
- ) -> Result<(), Self::Error>;
-
- /// Begins to serialize a sequence. This call must be followed by zero or
- /// more calls to `serialize_seq_elt`, then a call to `serialize_seq_end`.
- fn serialize_seq(
- &mut self,
- len: Option<usize>,
- ) -> Result<Self::SeqState, Self::Error>;
-
- /// Serializes a sequence element. Must have previously called
- /// `serialize_seq`.
- fn serialize_seq_elt<T: Serialize>(
- &mut self,
- state: &mut Self::SeqState,
- value: T,
- ) -> Result<(), Self::Error>;
-
- /// Finishes serializing a sequence.
- fn serialize_seq_end(
- &mut self,
- state: Self::SeqState,
- ) -> Result<(), Self::Error>;
-
- /// Begins to serialize a sequence whose length will be known at
- /// deserialization time. This call must be followed by zero or more calls
- /// to `serialize_seq_elt`, then a call to `serialize_seq_end`. A reasonable
- /// implementation would be to forward to `serialize_seq`.
- fn serialize_seq_fixed_size(
- &mut self,
- size: usize,
- ) -> Result<Self::SeqState, Self::Error>;
-
- /// Begins to serialize a tuple. This call must be followed by zero or more
- /// calls to `serialize_tuple_elt`, then a call to `serialize_tuple_end`. A
- /// reasonable implementation would be to forward to `serialize_seq`.
- fn serialize_tuple(
- &mut self,
- len: usize,
- ) -> Result<Self::TupleState, Self::Error>;
-
- /// Serializes a tuple element. Must have previously called
- /// `serialize_tuple`.
- fn serialize_tuple_elt<T: Serialize>(
- &mut self,
- state: &mut Self::TupleState,
- value: T,
- ) -> Result<(), Self::Error>;
-
- /// Finishes serializing a tuple.
- fn serialize_tuple_end(
- &mut self,
- state: Self::TupleState,
- ) -> Result<(), Self::Error>;
-
- /// Begins to serialize a tuple struct. This call must be followed by zero
- /// or more calls to `serialize_tuple_struct_elt`, then a call to
- /// `serialize_tuple_struct_end`. A reasonable implementation would be to
- /// forward to `serialize_tuple`.
- fn serialize_tuple_struct(
- &mut self,
- name: &'static str,
- len: usize,
- ) -> Result<Self::TupleStructState, Self::Error>;
-
- /// Serializes a tuple struct element. Must have previously called
- /// `serialize_tuple_struct`.
- fn serialize_tuple_struct_elt<T: Serialize>(
- &mut self,
- state: &mut Self::TupleStructState,
- value: T,
- ) -> Result<(), Self::Error>;
-
- /// Finishes serializing a tuple struct.
- fn serialize_tuple_struct_end(
- &mut self,
- state: Self::TupleStructState,
- ) -> Result<(), Self::Error>;
-
- /// Begins to serialize a tuple variant. This call must be followed by zero
- /// or more calls to `serialize_tuple_variant_elt`, then a call to
- /// `serialize_tuple_variant_end`. A reasonable implementation would be to
- /// forward to `serialize_tuple_struct`.
- fn serialize_tuple_variant(
- &mut self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- len: usize,
- ) -> Result<Self::TupleVariantState, Self::Error>;
-
- /// Serializes a tuple variant element. Must have previously called
- /// `serialize_tuple_variant`.
- fn serialize_tuple_variant_elt<T: Serialize>(
- &mut self,
- state: &mut Self::TupleVariantState,
- value: T,
- ) -> Result<(), Self::Error>;
-
- /// Finishes serializing a tuple variant.
- fn serialize_tuple_variant_end(
- &mut self,
- state: Self::TupleVariantState,
- ) -> Result<(), Self::Error>;
-
- /// Begins to serialize a map. This call must be followed by zero or more
- /// calls to `serialize_map_key` and `serialize_map_value`, then a call to
- /// `serialize_map_end`.
- fn serialize_map(
- &mut self,
- len: Option<usize>,
- ) -> Result<Self::MapState, Self::Error>;
-
- /// Serialize a map key. Must have previously called `serialize_map`.
- fn serialize_map_key<T: Serialize>(
- &mut self,
- state: &mut Self::MapState,
- key: T
- ) -> Result<(), Self::Error>;
-
- /// Serialize a map value. Must have previously called `serialize_map`.
- fn serialize_map_value<T: Serialize>(
- &mut self,
- state: &mut Self::MapState,
- value: T
- ) -> Result<(), Self::Error>;
-
- /// Finishes serializing a map.
- fn serialize_map_end(
- &mut self,
- state: Self::MapState,
- ) -> Result<(), Self::Error>;
-
- /// Begins to serialize a struct. This call must be followed by zero or more
- /// calls to `serialize_struct_elt`, then a call to `serialize_struct_end`.
- fn serialize_struct(
- &mut self,
- name: &'static str,
- len: usize,
- ) -> Result<Self::StructState, Self::Error>;
-
- /// Serializes a struct field. Must have previously called
- /// `serialize_struct`.
- fn serialize_struct_elt<V: Serialize>(
- &mut self,
- state: &mut Self::StructState,
- key: &'static str,
- value: V,
- ) -> Result<(), Self::Error>;
-
- /// Finishes serializing a struct.
- fn serialize_struct_end(
- &mut self,
- state: Self::StructState,
- ) -> Result<(), Self::Error>;
-
- /// Begins to serialize a struct variant. This call must be followed by zero
- /// or more calls to `serialize_struct_variant_elt`, then a call to
- /// `serialize_struct_variant_end`.
- fn serialize_struct_variant(
- &mut self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- len: usize,
- ) -> Result<Self::StructVariantState, Self::Error>;
-
- /// Serialize a struct variant element. Must have previously called
- /// `serialize_struct_variant`.
- fn serialize_struct_variant_elt<V: Serialize>(
- &mut self,
- state: &mut Self::StructVariantState,
- key: &'static str,
- value: V,
- ) -> Result<(), Self::Error>;
-
- /// Finishes serializing a struct variant.
- fn serialize_struct_variant_end(
- &mut self,
- state: Self::StructVariantState,
- ) -> Result<(), Self::Error>;
-}
deleted file mode 100644
--- a/third_party/rust/serde-0.8.23/src/utils.rs
+++ /dev/null
@@ -1,72 +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)
-}
--- a/third_party/rust/serde_codegen/.cargo-checksum.json
+++ b/third_party/rust/serde_codegen/.cargo-checksum.json
@@ -1,1 +1,1 @@
-{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"b16e3c93d139c09eb72a661a4201661c3c57ccca250a928a2ebc29f587d92540","src/bound.rs":"d1f94299052acaeeae0c011c2304b072dec76c7c32469d2b8881c2e380346496","src/de.rs":"a16c27918c973463427faaa98a7e7bd156c828bac4b96d605c30f82dad347476","src/lib.rs":"3ce6c8c8445b9f0987472477586c26281dd129f7dd9af4fd0a99d51bdfb65782","src/ser.rs":"5b86cf6b0b7941d3d82f3ed32cd26b845c821558f086fe9d7237f0ff1e066e61"},"package":"a4c5d8a33087d8984f9535daa62a6498a08f6476050b00ab9339dd847e4c25cc"}
\ No newline at end of file
+{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","Cargo.toml":"dea9bd4a6e93fc97a4ba26460497c35d3225c4c935f84c5a559094768c25f616","src/bound.rs":"d1f94299052acaeeae0c011c2304b072dec76c7c32469d2b8881c2e380346496","src/de.rs":"c1a4060eeb40de7ac96828cf35dc538ee0df7ba501388092f7e75d31542b11ba","src/lib.rs":"47db5228d2bc20d2d1d2403323de3ad4578f95b9baa5495aa7a095a2eae525dd","src/ser.rs":"361cd76e182d8ddb60560aab7a648dd012673b89e1090b59ff9565ec3c54143c"},"package":"1f94de585a73dfc312ca77194209278a587bf90d3edc6c2d0fc479b0ed71d1f0"}
\ No newline at end of file
--- a/third_party/rust/serde_codegen/Cargo.toml
+++ b/third_party/rust/serde_codegen/Cargo.toml
@@ -1,11 +1,11 @@
[package]
name = "serde_codegen"
-version = "0.8.23"
+version = "0.9.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
homepage = "https://serde.rs"
repository = "https://github.com/serde-rs/serde"
documentation = "https://serde.rs/codegen.html"
keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
@@ -22,8 +22,11 @@ with-syn = []
[dependencies]
clippy = { version = "^0.*", optional = true }
quote = "0.3.8"
serde_codegen_internals = { version = "=0.11.3", default-features = false, path = "../serde_codegen_internals" }
syn = { version = "0.10", features = ["aster", "visit"] }
syntex = { version = "^0.54.0", optional = true }
syntex_syntax = { version = "^0.54.0", optional = true }
+
+[badges]
+travis-ci = { repository = "serde-rs/serde" }
--- a/third_party/rust/serde_codegen/src/de.rs
+++ b/third_party/rust/serde_codegen/src/de.rs
@@ -1,9 +1,9 @@
-use syn::{self, aster};
+use syn::{self, aster, Ident};
use quote::{self, Tokens};
use bound;
use internals::ast::{Body, Field, Item, Style, Variant};
use internals::{self, attr};
use std::iter;
@@ -23,26 +23,26 @@ pub fn expand_derive_deserialize(item: &
.build();
let body = deserialize_body(&item,
&impl_generics,
ty.clone());
let where_clause = &impl_generics.where_clause;
- let dummy_const = aster::id(format!("_IMPL_DESERIALIZE_FOR_{}", item.ident));
+ let dummy_const = Ident::new(format!("_IMPL_DESERIALIZE_FOR_{}", item.ident));
Ok(quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const #dummy_const: () = {
extern crate serde as _serde;
#[automatically_derived]
- impl #impl_generics _serde::de::Deserialize for #ty #where_clause {
- fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<#ty, __D::Error>
- where __D: _serde::de::Deserializer
+ impl #impl_generics _serde::Deserialize for #ty #where_clause {
+ fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<#ty, __D::Error>
+ where __D: _serde::Deserializer
#body
}
};
})
}
// All the generics in the input, plus a bound `T: Deserialize` for each generic
// field type that will be deserialized by us, plus a bound `T: Default` for
@@ -56,17 +56,17 @@ fn build_impl_generics(item: &Item) -> s
match item.attrs.de_bound() {
Some(predicates) => {
bound::with_where_predicates(&generics, predicates)
}
None => {
let generics = bound::with_bound(item, &generics,
needs_deserialize_bound,
- &aster::path().ids(&["_serde", "de", "Deserialize"]).build());
+ &aster::path().ids(&["_serde", "Deserialize"]).build());
bound::with_bound(item, &generics,
requires_default,
&aster::path().global().ids(&["std", "default", "Default"]).build())
}
}
}
// Fields with a `skip_deserializing` or `deserialize_with` attribute are not
@@ -153,47 +153,41 @@ fn deserialize_visitor(generics: &syn::G
} else {
let where_clause = &generics.where_clause;
let num_phantoms = generics.lifetimes.len() + generics.ty_params.len();
let phantom_types = generics.lifetimes.iter()
.map(|lifetime_def| {
let lifetime = &lifetime_def.lifetime;
- quote!(::std::marker::PhantomData<& #lifetime ()>)
+ quote!(_serde::export::PhantomData<& #lifetime ()>)
}).chain(generics.ty_params.iter()
.map(|ty_param| {
let ident = &ty_param.ident;
- quote!(::std::marker::PhantomData<#ident>)
+ quote!(_serde::export::PhantomData<#ident>)
}));
let all_params = generics.lifetimes.iter()
.map(|lifetime_def| {
let lifetime = &lifetime_def.lifetime;
quote!(#lifetime)
}).chain(generics.ty_params.iter()
.map(|ty_param| {
let ident = &ty_param.ident;
quote!(#ident)
}));
- let ty_param_idents: Vec<_> = generics.ty_params.iter()
- .map(|t| {
- let ident = &t.ident;
- quote!(#ident)
- })
- .collect();
-
- let ty_param_idents = if ty_param_idents.is_empty() {
+ let ty_param_idents = if generics.ty_params.is_empty() {
None
} else {
+ let ty_param_idents = generics.ty_params.iter().map(|t| &t.ident);
Some(quote!(::<#(#ty_param_idents),*>))
};
- let phantom_exprs = iter::repeat(quote!(::std::marker::PhantomData)).take(num_phantoms);
+ let phantom_exprs = iter::repeat(quote!(_serde::export::PhantomData)).take(num_phantoms);
(
quote! {
struct __Visitor #generics ( #(#phantom_types),* ) #where_clause;
},
quote!(__Visitor <#(#all_params),*> ),
quote!(__Visitor #ty_param_idents ( #(#phantom_exprs),* )),
)
@@ -201,35 +195,40 @@ fn deserialize_visitor(generics: &syn::G
}
fn deserialize_unit_struct(
type_ident: &syn::Ident,
item_attrs: &attr::Item,
) -> Tokens {
let type_name = item_attrs.name().deserialize_name();
+ let expecting = format!("unit struct {}", type_ident);
+
quote!({
struct __Visitor;
impl _serde::de::Visitor for __Visitor {
type Value = #type_ident;
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
#[inline]
- fn visit_unit<__E>(&mut self) -> ::std::result::Result<#type_ident, __E>
+ fn visit_unit<__E>(self) -> _serde::export::Result<#type_ident, __E>
where __E: _serde::de::Error,
{
Ok(#type_ident)
}
#[inline]
- fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#type_ident, __V::Error>
+ fn visit_seq<__V>(self, _: __V) -> _serde::export::Result<#type_ident, __V::Error>
where __V: _serde::de::SeqVisitor,
{
- try!(visitor.end());
- self.visit_unit()
+ Ok(#type_ident)
}
}
deserializer.deserialize_unit_struct(#type_name, __Visitor)
})
}
fn deserialize_tuple(
@@ -244,16 +243,20 @@ fn deserialize_tuple(
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
let is_enum = variant_ident.is_some();
let type_path = match variant_ident {
Some(variant_ident) => quote!(#type_ident::#variant_ident),
None => quote!(#type_ident),
};
+ let expecting = match variant_ident {
+ Some(variant_ident) => format!("tuple variant {}::{}", type_ident, variant_ident),
+ None => format!("tuple struct {}", type_ident),
+ };
let nfields = fields.len();
let visit_newtype_struct = if !is_enum && nfields == 1 {
Some(deserialize_newtype_struct(
type_ident,
&type_path,
impl_generics,
@@ -267,35 +270,46 @@ fn deserialize_tuple(
type_ident,
&type_path,
impl_generics,
fields,
false,
);
let dispatch = if is_enum {
- quote!(visitor.visit_tuple(#nfields, #visitor_expr))
+ quote!(_serde::de::VariantVisitor::visit_tuple(visitor, #nfields, #visitor_expr))
} else if nfields == 1 {
let type_name = item_attrs.name().deserialize_name();
quote!(deserializer.deserialize_newtype_struct(#type_name, #visitor_expr))
} else {
let type_name = item_attrs.name().deserialize_name();
quote!(deserializer.deserialize_tuple_struct(#type_name, #nfields, #visitor_expr))
};
+ let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
+ let visitor_var = if all_skipped {
+ quote!(_)
+ } else {
+ quote!(mut visitor)
+ };
+
quote!({
#visitor_item
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
#visit_newtype_struct
#[inline]
- fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::SeqVisitor
{
#visit_seq
}
}
#dispatch
})
@@ -303,25 +317,30 @@ fn deserialize_tuple(
fn deserialize_seq(
type_ident: &syn::Ident,
type_path: &Tokens,
impl_generics: &syn::Generics,
fields: &[Field],
is_struct: bool,
) -> Tokens {
+ let vars = (0..fields.len()).map(field_i as fn(_) -> _);
+
+ let deserialized_count = fields.iter()
+ .filter(|field| !field.attrs.skip_deserializing())
+ .count();
+ let expecting = format!("tuple of {} elements", deserialized_count);
+
let mut index_in_seq = 0usize;
- let let_values: Vec<_> = fields.iter()
- .enumerate()
- .map(|(i, field)| {
- let name = aster::id(format!("__field{}", i));
+ let let_values = vars.clone().zip(fields)
+ .map(|(var, field)| {
if field.attrs.skip_deserializing() {
let default = expr_is_missing(&field.attrs);
quote! {
- let #name = #default;
+ let #var = #default;
}
} else {
let visit = match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
quote!(try!(visitor.visit::<#field_ty>()))
}
Some(path) => {
@@ -330,53 +349,41 @@ fn deserialize_seq(
quote!({
#wrapper
#wrapper_impl
try!(visitor.visit::<#wrapper_ty>()).map(|wrap| wrap.value)
})
}
};
let assign = quote! {
- let #name = match #visit {
+ let #var = match #visit {
Some(value) => { value },
None => {
- try!(visitor.end());
- return Err(_serde::de::Error::invalid_length(#index_in_seq));
+ return Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
}
};
};
index_in_seq += 1;
assign
}
- })
- .collect();
+ });
let result = if is_struct {
- let args = fields.iter()
- .enumerate()
- .map(|(i, field)| {
- let ident = field.ident.clone().expect("struct contains unnamed fields");
- let value = aster::id(format!("__field{}", i));
- quote!(#ident: #value)
- });
+ let names = fields.iter().map(|f| &f.ident);
quote! {
- #type_path { #(#args),* }
+ #type_path { #( #names: #vars ),* }
}
} else {
- let args = (0..fields.len()).map(|i| aster::id(format!("__field{}", i)));
quote! {
- #type_path ( #(#args),* )
+ #type_path ( #(#vars),* )
}
};
quote! {
#(#let_values)*
-
- try!(visitor.end());
-
Ok(#result)
}
}
fn deserialize_newtype_struct(
type_ident: &syn::Ident,
type_path: &Tokens,
impl_generics: &syn::Generics,
@@ -396,18 +403,18 @@ fn deserialize_newtype_struct(
#wrapper
#wrapper_impl
try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value
})
}
};
quote! {
#[inline]
- fn visit_newtype_struct<__E>(&mut self, __e: &mut __E) -> ::std::result::Result<Self::Value, __E::Error>
- where __E: _serde::de::Deserializer,
+ fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
+ where __E: _serde::Deserializer,
{
Ok(#type_path(#value))
}
}
}
fn deserialize_struct(
type_ident: &syn::Ident,
@@ -420,16 +427,20 @@ fn deserialize_struct(
let where_clause = &impl_generics.where_clause;
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
let type_path = match variant_ident {
Some(variant_ident) => quote!(#type_ident::#variant_ident),
None => quote!(#type_ident),
};
+ let expecting = match variant_ident {
+ Some(variant_ident) => format!("struct variant {}::{}", type_ident, variant_ident),
+ None => format!("struct {}", type_ident),
+ };
let visit_seq = deserialize_seq(
type_ident,
&type_path,
impl_generics,
fields,
true,
);
@@ -440,42 +451,53 @@ fn deserialize_struct(
impl_generics,
fields,
item_attrs,
);
let is_enum = variant_ident.is_some();
let dispatch = if is_enum {
quote! {
- visitor.visit_struct(FIELDS, #visitor_expr)
+ _serde::de::VariantVisitor::visit_struct(visitor, FIELDS, #visitor_expr)
}
} else {
let type_name = item_attrs.name().deserialize_name();
quote! {
deserializer.deserialize_struct(#type_name, FIELDS, #visitor_expr)
}
};
+ let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
+ let visitor_var = if all_skipped {
+ quote!(_)
+ } else {
+ quote!(mut visitor)
+ };
+
quote!({
#field_visitor
#visitor_item
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
#[inline]
- fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::SeqVisitor
{
#visit_seq
}
#[inline]
- fn visit_map<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_map<__V>(self, mut visitor: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::MapVisitor
{
#visit_map
}
}
#fields_stmt
@@ -489,76 +511,93 @@ fn deserialize_item_enum(
ty: syn::Ty,
variants: &[Variant],
item_attrs: &attr::Item
) -> Tokens {
let where_clause = &impl_generics.where_clause;
let type_name = item_attrs.name().deserialize_name();
+ let expecting = format!("enum {}", type_ident);
+
+ let variant_names_idents: Vec<_> = variants.iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i)))
+ .collect();
+
+ let variants_stmt = {
+ let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name);
+ quote! {
+ const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
+ }
+ };
+
let variant_visitor = deserialize_field_visitor(
- variants.iter()
- .filter(|variant| !variant.attrs.skip_deserializing())
- .map(|variant| variant.attrs.name().deserialize_name())
- .collect(),
+ variant_names_idents,
item_attrs,
true,
);
- let variant_names = variants.iter().map(|variant| variant.ident.to_string());
-
- let variants_stmt = quote! {
- const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
- };
+ // Match arms to extract a variant from a string
+ let variant_arms = variants.iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .map(|(i, variant)| {
+ let variant_name = field_i(i);
- let ignored_arm = if item_attrs.deny_unknown_fields() {
- None
- } else {
- Some(quote! {
- __Field::__ignore => { Err(_serde::de::Error::end_of_stream()) }
- })
- };
+ let block = deserialize_variant(
+ type_ident,
+ impl_generics,
+ ty.clone(),
+ variant,
+ item_attrs,
+ );
- // Match arms to extract a variant from a string
- let mut variant_arms = vec![];
- for (i, variant) in variants.iter().filter(|variant| !variant.attrs.skip_deserializing()).enumerate() {
- let variant_name = aster::id(format!("__field{}", i));
- let variant_name = quote!(__Field::#variant_name);
+ quote! {
+ (__Field::#variant_name, visitor) => #block
+ }
+ });
- let block = deserialize_variant(
- type_ident,
- impl_generics,
- ty.clone(),
- variant,
- item_attrs,
- );
-
- let arm = quote! {
- #variant_name => #block
- };
- variant_arms.push(arm);
- }
- variant_arms.extend(ignored_arm.into_iter());
+ let all_skipped = variants.iter().all(|variant| variant.attrs.skip_deserializing());
+ let match_variant = if all_skipped {
+ // This is an empty enum like `enum Impossible {}` or an enum in which
+ // all variants have `#[serde(skip_deserializing)]`.
+ quote! {
+ // FIXME: Once we drop support for Rust 1.15:
+ // let Err(err) = visitor.visit_variant::<__Field>();
+ // Err(err)
+ visitor.visit_variant::<__Field>().map(|(impossible, _)| match impossible {})
+ }
+ } else {
+ quote! {
+ match try!(visitor.visit_variant()) {
+ #(#variant_arms)*
+ }
+ }
+ };
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
quote!({
#variant_visitor
#visitor_item
- impl #impl_generics _serde::de::EnumVisitor for #visitor_ty #where_clause {
+ impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
- fn visit<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
- where __V: _serde::de::VariantVisitor,
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
+ fn visit_enum<__V>(self, visitor: __V) -> _serde::export::Result<#ty, __V::Error>
+ where __V: _serde::de::EnumVisitor,
{
- match try!(visitor.visit_variant()) {
- #(#variant_arms)*
- }
+ #match_variant
}
}
#variants_stmt
deserializer.deserialize_enum(#type_name, VARIANTS, #visitor_expr)
})
}
@@ -570,17 +609,17 @@ fn deserialize_variant(
variant: &Variant,
item_attrs: &attr::Item,
) -> Tokens {
let variant_ident = &variant.ident;
match variant.style {
Style::Unit => {
quote!({
- try!(visitor.visit_unit());
+ try!(_serde::de::VariantVisitor::visit_unit(visitor));
Ok(#type_ident::#variant_ident)
})
}
Style::Newtype => {
deserialize_newtype_variant(
type_ident,
variant_ident,
generics,
@@ -614,237 +653,209 @@ fn deserialize_newtype_variant(
type_ident: &syn::Ident,
variant_ident: &syn::Ident,
impl_generics: &syn::Generics,
field: &Field,
) -> Tokens {
let visit = match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
- quote!(try!(visitor.visit_newtype::<#field_ty>()))
+ quote! {
+ try!(_serde::de::VariantVisitor::visit_newtype::<#field_ty>(visitor))
+ }
}
Some(path) => {
let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
type_ident, impl_generics, field.ty, path);
quote!({
#wrapper
#wrapper_impl
- try!(visitor.visit_newtype::<#wrapper_ty>()).value
+ try!(_serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(visitor)).value
})
}
};
quote! {
Ok(#type_ident::#variant_ident(#visit)),
}
}
fn deserialize_field_visitor(
- field_names: Vec<String>,
+ fields: Vec<(String, Ident)>,
item_attrs: &attr::Item,
is_variant: bool,
) -> Tokens {
- // Create the field names for the fields.
- let field_idents: Vec<_> = (0 .. field_names.len())
- .map(|i| aster::id(format!("__field{}", i)))
- .collect();
+ let field_strs = fields.iter().map(|&(ref name, _)| name);
+ let field_bytes = fields.iter().map(|&(ref name, _)| quote::ByteStr(name));
+ let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect();
- let ignore_variant = if item_attrs.deny_unknown_fields() {
+ let ignore_variant = if is_variant || item_attrs.deny_unknown_fields() {
None
} else {
Some(quote!(__ignore,))
};
- let index_field_arms: Vec<_> = field_idents.iter()
- .enumerate()
- .map(|(field_index, field_ident)| {
- quote! {
- #field_index => { Ok(__Field::#field_ident) }
+ let visit_index = if is_variant {
+ let variant_indices = 0u32..;
+ let fallthrough_msg = format!("variant index 0 <= i < {}", fields.len());
+ Some(quote! {
+ fn visit_u32<__E>(self, value: u32) -> _serde::export::Result<__Field, __E>
+ where __E: _serde::de::Error
+ {
+ match value {
+ #(
+ #variant_indices => Ok(__Field::#field_idents),
+ )*
+ _ => Err(_serde::de::Error::invalid_value(
+ _serde::de::Unexpected::Unsigned(value as u64),
+ &#fallthrough_msg))
+ }
}
})
- .collect();
-
- let (index_error_msg, unknown_ident) = if is_variant {
- ("expected a variant", aster::id("unknown_variant"))
} else {
- ("expected a field", aster::id("unknown_field"))
+ None
};
- let fallthrough_index_arm_expr = if !is_variant && !item_attrs.deny_unknown_fields() {
+ let fallthrough_arm = if is_variant {
quote! {
- Ok(__Field::__ignore)
+ Err(_serde::de::Error::unknown_variant(value, VARIANTS))
+ }
+ } else if item_attrs.deny_unknown_fields() {
+ quote! {
+ Err(_serde::de::Error::unknown_field(value, FIELDS))
}
} else {
quote! {
- Err(_serde::de::Error::invalid_value(#index_error_msg))
- }
- };
-
- let index_body = quote! {
- match value {
- #(#index_field_arms)*
- _ => #fallthrough_index_arm_expr
+ Ok(__Field::__ignore)
}
};
- // Match arms to extract a field from a string
- let str_field_arms: Vec<_> = field_idents.iter().zip(field_names.iter())
- .map(|(field_ident, field_name)| {
- quote! {
- #field_name => { Ok(__Field::#field_ident) }
- }
+ let bytes_to_str = if is_variant || item_attrs.deny_unknown_fields() {
+ Some(quote! {
+ // TODO https://github.com/serde-rs/serde/issues/666
+ // update this to use str::from_utf8(value).unwrap_or("���") on no_std
+ let value = &_serde::export::from_utf8_lossy(value);
})
- .collect();
-
- let fallthrough_str_arm_expr = if !is_variant && !item_attrs.deny_unknown_fields() {
- quote! {
- Ok(__Field::__ignore)
- }
} else {
- quote! {
- Err(_serde::de::Error::#unknown_ident(value))
- }
- };
-
- let str_body = quote! {
- match value {
- #(#str_field_arms)*
- _ => #fallthrough_str_arm_expr
- }
- };
-
- // Match arms to extract a field from a string
- let bytes_field_arms: Vec<_> = field_idents.iter().zip(field_names.iter())
- .map(|(field_ident, field_name)| {
- let bytes_field_name = quote::ByteStr(field_name);
- quote! {
- #bytes_field_name => { Ok(__Field::#field_ident) }
- }
- })
- .collect();
-
- let fallthrough_bytes_arm_expr = if !is_variant && !item_attrs.deny_unknown_fields() {
- quote! {
- Ok(__Field::__ignore)
- }
- } else {
- quote!({
- let value = ::std::string::String::from_utf8_lossy(value);
- Err(_serde::de::Error::#unknown_ident(&value))
- })
- };
-
- let bytes_body = quote! {
- match value {
- #(#bytes_field_arms)*
- _ => #fallthrough_bytes_arm_expr
- }
+ None
};
quote! {
#[allow(non_camel_case_types)]
enum __Field {
#(#field_idents,)*
#ignore_variant
}
- impl _serde::de::Deserialize for __Field {
+ impl _serde::Deserialize for __Field {
#[inline]
- fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<__Field, __D::Error>
- where __D: _serde::de::Deserializer,
+ fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<__Field, __D::Error>
+ where __D: _serde::Deserializer,
{
struct __FieldVisitor;
impl _serde::de::Visitor for __FieldVisitor {
type Value = __Field;
- fn visit_usize<__E>(&mut self, value: usize) -> ::std::result::Result<__Field, __E>
- where __E: _serde::de::Error
- {
- #index_body
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
+ formatter.write_str("field name")
}
- fn visit_str<__E>(&mut self, value: &str) -> ::std::result::Result<__Field, __E>
+ #visit_index
+
+ fn visit_str<__E>(self, value: &str) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
- #str_body
+ match value {
+ #(
+ #field_strs => Ok(__Field::#field_idents),
+ )*
+ _ => #fallthrough_arm
+ }
}
- fn visit_bytes<__E>(&mut self, value: &[u8]) -> ::std::result::Result<__Field, __E>
+ fn visit_bytes<__E>(self, value: &[u8]) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
- #bytes_body
+ match value {
+ #(
+ #field_bytes => Ok(__Field::#field_idents),
+ )*
+ _ => {
+ #bytes_to_str
+ #fallthrough_arm
+ }
+ }
}
}
deserializer.deserialize_struct_field(__FieldVisitor)
}
}
}
}
fn deserialize_struct_visitor(
type_ident: &syn::Ident,
struct_path: Tokens,
impl_generics: &syn::Generics,
fields: &[Field],
item_attrs: &attr::Item,
) -> (Tokens, Tokens, Tokens) {
- let field_exprs = fields.iter()
- .map(|field| field.attrs.name().deserialize_name())
+ let field_names_idents: Vec<_> = fields.iter()
+ .enumerate()
+ .filter(|&(_, field)| !field.attrs.skip_deserializing())
+ .map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i)))
.collect();
+ let fields_stmt = {
+ let field_names = field_names_idents.iter().map(|&(ref name, _)| name);
+ quote! {
+ const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
+ }
+ };
+
let field_visitor = deserialize_field_visitor(
- field_exprs,
+ field_names_idents,
item_attrs,
false,
);
let visit_map = deserialize_map(
type_ident,
struct_path,
impl_generics,
fields,
item_attrs,
);
- let field_names = fields.iter().map(|field| {
- field.ident.clone().expect("struct contains unnamed field").to_string()
- });
-
- let fields_stmt = quote! {
- const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
- };
-
(field_visitor, fields_stmt, visit_map)
}
fn deserialize_map(
type_ident: &syn::Ident,
struct_path: Tokens,
impl_generics: &syn::Generics,
fields: &[Field],
item_attrs: &attr::Item,
) -> Tokens {
// Create the field names for the fields.
- let fields_names = fields.iter()
+ let fields_names: Vec<_> = fields.iter()
.enumerate()
- .map(|(i, field)|
- (field, aster::id(format!("__field{}", i))))
- .collect::<Vec<_>>();
+ .map(|(i, field)| (field, field_i(i)))
+ .collect();
// Declare each field that will be deserialized.
- let let_values: Vec<_> = fields_names.iter()
+ let let_values = fields_names.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|&(field, ref name)| {
let field_ty = &field.ty;
quote! {
let mut #name: Option<#field_ty> = None;
}
- })
- .collect();
+ });
// Match arms to extract a value for a field.
let value_arms = fields_names.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|&(field, ref name)| {
let deser_name = field.attrs.name().deserialize_name();
let visit = match field.attrs.deserialize_with() {
@@ -867,85 +878,84 @@ fn deserialize_map(
quote! {
__Field::#name => {
if #name.is_some() {
return Err(<__V::Error as _serde::de::Error>::duplicate_field(#deser_name));
}
#name = Some(#visit);
}
}
- })
- .collect::<Vec<_>>();
-
- // Match arms to ignore value for fields that have `skip_deserializing`.
- // Ignored even if `deny_unknown_fields` is set.
- let skipped_arms = fields_names.iter()
- .filter(|&&(field, _)| field.attrs.skip_deserializing())
- .map(|&(_, ref name)| {
- quote! {
- __Field::#name => {
- let _ = try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>());
- }
- }
- })
- .collect::<Vec<_>>();
+ });
// Visit ignored values to consume them
let ignored_arm = if item_attrs.deny_unknown_fields() {
None
} else {
Some(quote! {
_ => { let _ = try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>()); }
})
};
+ let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
+ let match_keys = if item_attrs.deny_unknown_fields() && all_skipped {
+ quote! {
+ // FIXME: Once we drop support for Rust 1.15:
+ // let None::<__Field> = try!(visitor.visit_key());
+ try!(visitor.visit_key::<__Field>()).map(|impossible| match impossible {});
+ }
+ } else {
+ quote! {
+ while let Some(key) = try!(visitor.visit_key::<__Field>()) {
+ match key {
+ #(#value_arms)*
+ #ignored_arm
+ }
+ }
+ }
+ };
+
let extract_values = fields_names.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|&(field, ref name)| {
let missing_expr = expr_is_missing(&field.attrs);
quote! {
let #name = match #name {
Some(#name) => #name,
None => #missing_expr
};
}
- })
- .collect::<Vec<_>>();
+ });
let result = fields_names.iter()
.map(|&(field, ref name)| {
let ident = field.ident.clone().expect("struct contains unnamed fields");
let value = if field.attrs.skip_deserializing() {
expr_is_missing(&field.attrs)
} else {
quote!(#name)
};
quote!(#ident: #value)
});
quote! {
#(#let_values)*
- while let Some(key) = try!(visitor.visit_key::<__Field>()) {
- match key {
- #(#value_arms)*
- #(#skipped_arms)*
- #ignored_arm
- }
- }
-
- try!(visitor.end());
+ #match_keys
#(#extract_values)*
Ok(#struct_path { #(#result),* })
}
}
+fn field_i(i: usize) -> Ident {
+ Ident::new(format!("__field{}", i))
+}
+
/// This function wraps the expression in `#[serde(deserialize_with="...")]` in
/// a trait to prevent it from accessing the internal `Deserialize` state.
fn wrap_deserialize_with(
type_ident: &syn::Ident,
impl_generics: &syn::Generics,
field_ty: &syn::Ty,
deserialize_with: &syn::Path,
) -> (Tokens, Tokens, syn::Path) {
@@ -966,52 +976,52 @@ fn wrap_deserialize_with(
.build())
.build()
.build();
(
quote! {
struct __SerdeDeserializeWithStruct #impl_generics #where_clause {
value: #field_ty,
- phantom: ::std::marker::PhantomData<#phantom_ty>,
+ phantom: _serde::export::PhantomData<#phantom_ty>,
}
},
quote! {
- impl #impl_generics _serde::de::Deserialize for #wrapper_ty #where_clause {
- fn deserialize<__D>(__d: &mut __D) -> ::std::result::Result<Self, __D::Error>
- where __D: _serde::de::Deserializer
+ impl #impl_generics _serde::Deserialize for #wrapper_ty #where_clause {
+ fn deserialize<__D>(__d: __D) -> _serde::export::Result<Self, __D::Error>
+ where __D: _serde::Deserializer
{
let value = try!(#deserialize_with(__d));
Ok(__SerdeDeserializeWithStruct {
value: value,
- phantom: ::std::marker::PhantomData,
+ phantom: _serde::export::PhantomData,
})
}
}
},
wrapper_ty,
)
}
fn expr_is_missing(attrs: &attr::Field) -> Tokens {
match *attrs.default() {
attr::FieldDefault::Default => {
- return quote!(::std::default::Default::default());
+ return quote!(_serde::export::Default::default());
}
attr::FieldDefault::Path(ref path) => {
return quote!(#path());
}
attr::FieldDefault::None => { /* below */ }
}
let name = attrs.name().deserialize_name();
match attrs.deserialize_with() {
None => {
quote! {
- try!(visitor.missing_field(#name))
+ try!(_serde::de::private::missing_field(#name))
}
}
Some(_) => {
quote! {
return Err(<__V::Error as _serde::de::Error>::missing_field(#name))
}
}
}
--- a/third_party/rust/serde_codegen/src/lib.rs
+++ b/third_party/rust/serde_codegen/src/lib.rs
@@ -7,17 +7,16 @@
#![recursion_limit = "192"]
extern crate serde_codegen_internals as internals;
#[cfg(feature = "with-syntex")]
extern crate syntex;
#[cfg(feature = "with-syntex")]
-#[macro_use]
extern crate syntex_syntax as syntax;
extern crate syn;
#[macro_use]
extern crate quote;
#[cfg(feature = "with-syntex")]
use std::path::Path;
--- a/third_party/rust/serde_codegen/src/ser.rs
+++ b/third_party/rust/serde_codegen/src/ser.rs
@@ -1,9 +1,9 @@
-use syn::{self, aster};
+use syn::{self, aster, Ident};
use quote::Tokens;
use bound;
use internals::ast::{Body, Field, Item, Style, Variant};
use internals::{self, attr};
pub fn expand_derive_serialize(item: &syn::MacroInput) -> Result<Tokens, String> {
let ctxt = internals::Ctxt::new();
@@ -17,26 +17,26 @@ pub fn expand_derive_serialize(item: &sy
.build();
let body = serialize_body(&item,
&impl_generics,
ty.clone());
let where_clause = &impl_generics.where_clause;
- let dummy_const = aster::id(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
+ let dummy_const = Ident::new(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
Ok(quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const #dummy_const: () = {
extern crate serde as _serde;
#[automatically_derived]
- impl #impl_generics _serde::ser::Serialize for #ty #where_clause {
- fn serialize<__S>(&self, _serializer: &mut __S) -> ::std::result::Result<(), __S::Error>
- where __S: _serde::ser::Serializer
+ impl #impl_generics _serde::Serialize for #ty #where_clause {
+ fn serialize<__S>(&self, _serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
+ where __S: _serde::Serializer
{
#body
}
}
};
})
}
@@ -51,17 +51,17 @@ fn build_impl_generics(item: &Item) -> s
match item.attrs.ser_bound() {
Some(predicates) => {
bound::with_where_predicates(&generics, predicates)
}
None => {
bound::with_bound(item, &generics,
needs_serialize_bound,
- &aster::path().ids(&["_serde", "ser", "Serialize"]).build())
+ &aster::path().ids(&["_serde", "Serialize"]).build())
}
}
}
// Fields with a `skip_serializing` or `serialize_with` attribute are not
// serialized by us so we do not generate a bound. Fields with a `bound`
// attribute specify their own bound so we do not generate one. All other fields
// may need a `T: Serialize` bound where T is the type of the field.
@@ -154,42 +154,42 @@ fn serialize_tuple_struct(
fields: &[Field],
item_attrs: &attr::Item,
) -> Tokens {
let serialize_stmts = serialize_tuple_struct_visitor(
ty.clone(),
fields,
impl_generics,
false,
- aster::id("serialize_tuple_struct_elt"),
+ quote!(_serde::ser::SerializeTupleStruct::serialize_field),
);
let type_name = item_attrs.name().serialize_name();
let len = serialize_stmts.len();
let let_mut = mut_if(len > 0);
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_tuple_struct(#type_name, #len));
#(#serialize_stmts)*
- _serializer.serialize_tuple_struct_end(__serde_state)
+ _serde::ser::SerializeTupleStruct::end(__serde_state)
}
}
fn serialize_struct(
impl_generics: &syn::Generics,
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
) -> Tokens {
let serialize_fields = serialize_struct_visitor(
ty.clone(),
fields,
impl_generics,
false,
- aster::id("serialize_struct_elt"),
+ quote!(_serde::ser::SerializeStruct::serialize_field),
);
let type_name = item_attrs.name().serialize_name();
let mut serialized_fields = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.peekable();
@@ -205,17 +205,17 @@ fn serialize_struct(
None => quote!(1),
}
})
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_struct(#type_name, #len));
#(#serialize_fields)*
- _serializer.serialize_struct_end(__serde_state)
+ _serde::ser::SerializeStruct::end(__serde_state)
}
}
fn serialize_item_enum(
type_ident: &syn::Ident,
impl_generics: &syn::Generics,
ty: syn::Ty,
variants: &[Variant],
@@ -252,35 +252,35 @@ fn serialize_variant(
item_attrs: &attr::Item,
) -> Tokens {
let type_name = item_attrs.name().serialize_name();
let variant_ident = variant.ident.clone();
let variant_name = variant.attrs.name().serialize_name();
if variant.attrs.skip_serializing() {
- let skipped_msg = format!("The enum variant {}::{} cannot be serialized",
+ let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
type_ident, variant_ident);
let skipped_err = quote! {
- Err(_serde::ser::Error::invalid_value(#skipped_msg))
+ Err(_serde::ser::Error::custom(#skipped_msg))
};
let fields_pat = match variant.style {
Style::Unit => quote!(),
Style::Newtype | Style::Tuple => quote!( (..) ),
Style::Struct => quote!( {..} ),
};
quote! {
#type_ident::#variant_ident #fields_pat => #skipped_err,
}
} else { // variant wasn't skipped
match variant.style {
Style::Unit => {
quote! {
#type_ident::#variant_ident =>
- _serde::ser::Serializer::serialize_unit_variant(
+ _serde::Serializer::serialize_unit_variant(
_serializer,
#type_name,
#variant_index,
#variant_name,
),
}
},
Style::Newtype => {
@@ -294,17 +294,17 @@ fn serialize_variant(
);
quote! {
#type_ident::#variant_ident(ref __simple_value) => #block,
}
},
Style::Tuple => {
let field_names = (0 .. variant.fields.len())
- .map(|i| aster::id(format!("__field{}", i)));
+ .map(|i| Ident::new(format!("__field{}", i)));
let block = serialize_tuple_variant(
type_name,
variant_index,
variant_name,
generics,
ty,
&variant.fields,
@@ -345,17 +345,17 @@ fn serialize_newtype_variant(
) -> Tokens {
let mut field_expr = quote!(__simple_value);
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(
&item_ty, generics, field.ty, path, field_expr);
}
quote! {
- _serde::ser::Serializer::serialize_newtype_variant(
+ _serde::Serializer::serialize_newtype_variant(
_serializer,
#type_name,
#variant_index,
#variant_name,
#field_expr,
)
}
}
@@ -368,47 +368,47 @@ fn serialize_tuple_variant(
structure_ty: syn::Ty,
fields: &[Field],
) -> Tokens {
let serialize_stmts = serialize_tuple_struct_visitor(
structure_ty,
fields,
generics,
true,
- aster::id("serialize_tuple_variant_elt"),
+ quote!(_serde::ser::SerializeTupleVariant::serialize_field),
);
let len = serialize_stmts.len();
let let_mut = mut_if(len > 0);
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_tuple_variant(
#type_name,
#variant_index,
#variant_name,
#len));
#(#serialize_stmts)*
- _serializer.serialize_tuple_variant_end(__serde_state)
+ _serde::ser::SerializeTupleVariant::end(__serde_state)
}
}
fn serialize_struct_variant(
variant_index: usize,
variant_name: String,
generics: &syn::Generics,
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
) -> Tokens {
let serialize_fields = serialize_struct_visitor(
ty.clone(),
fields,
generics,
true,
- aster::id("serialize_struct_variant_elt"),
+ quote!(_serde::ser::SerializeStructVariant::serialize_field),
);
let item_name = item_attrs.name().serialize_name();
let mut serialized_fields = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.peekable();
@@ -428,64 +428,64 @@ fn serialize_struct_variant(
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_struct_variant(
#item_name,
#variant_index,
#variant_name,
#len,
));
#(#serialize_fields)*
- _serializer.serialize_struct_variant_end(__serde_state)
+ _serde::ser::SerializeStructVariant::end(__serde_state)
}
}
fn serialize_tuple_struct_visitor(
structure_ty: syn::Ty,
fields: &[Field],
generics: &syn::Generics,
is_enum: bool,
- func: syn::Ident,
+ func: Tokens,
) -> Vec<Tokens> {
fields.iter()
.enumerate()
.map(|(i, field)| {
let mut field_expr = if is_enum {
- let id = aster::id(format!("__field{}", i));
+ let id = Ident::new(format!("__field{}", i));
quote!(#id)
} else {
- let i = aster::id(i);
+ let i = Ident::new(i);
quote!(&self.#i)
};
let skip = field.attrs.skip_serializing_if()
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(
&structure_ty, generics, field.ty, path, field_expr);
}
let ser = quote! {
- try!(_serializer.#func(&mut __serde_state, #field_expr));
+ try!(#func(&mut __serde_state, #field_expr));
};
match skip {
None => ser,
Some(skip) => quote!(if !#skip { #ser }),
}
})
.collect()
}
fn serialize_struct_visitor(
structure_ty: syn::Ty,
fields: &[Field],
generics: &syn::Generics,
is_enum: bool,
- func: syn::Ident,
+ func: Tokens,
) -> Vec<Tokens> {
fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.map(|field| {
let ident = field.ident.clone().expect("struct has unnamed field");
let mut field_expr = if is_enum {
quote!(#ident)
} else {
@@ -498,17 +498,17 @@ fn serialize_struct_visitor(
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(
&structure_ty, generics, field.ty, path, field_expr)
}
let ser = quote! {
- try!(_serializer.#func(&mut __serde_state, #key_expr, #field_expr));
+ try!(#func(&mut __serde_state, #key_expr, #field_expr));
};
match skip {
None => ser,
Some(skip) => quote!(if !#skip { #ser }),
}
})
.collect()
@@ -535,35 +535,35 @@ fn wrap_serialize_with(
.build();
quote!({
struct __SerializeWith #wrapper_generics #where_clause {
value: &'__a #field_ty,
phantom: ::std::marker::PhantomData<#item_ty>,
}
- impl #wrapper_generics _serde::ser::Serialize for #wrapper_ty #where_clause {
- fn serialize<__S>(&self, __s: &mut __S) -> ::std::result::Result<(), __S::Error>
- where __S: _serde::ser::Serializer
+ impl #wrapper_generics _serde::Serialize for #wrapper_ty #where_clause {
+ fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error>
+ where __S: _serde::Serializer
{
#path(self.value, __s)
}
}
- __SerializeWith {
+ &__SerializeWith {
value: #value,
phantom: ::std::marker::PhantomData::<#item_ty>,
}
})
}
// Serialization of an empty struct results in code like:
//
// let mut __serde_state = try!(serializer.serialize_struct("S", 0));
-// serializer.serialize_struct_end(__serde_state)
+// _serde::ser::SerializeStruct::end(__serde_state)
//
// where we want to omit the `mut` to avoid a warning.
fn mut_if(is_mut: bool) -> Option<Tokens> {
if is_mut {
Some(quote!(mut))
} else {
None
}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/servo-dwrote/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"172610b244a5ee8a8e2f1f045058b8abf9291d84bb76bf8779d2fd420419c2d6","Cargo.toml":"dea6c3d3d4b1440983aa6e3d218b52c630283c8ef52102fa5443c67d954e14f0","README.md":"d69d75705e2582721cbfb2d3b4b2af052c71679057a0b2ac53a22c03f1755bba","build.rs":"b40ce243f62825724b4a45092a8e658d71fa952a6840b83f3bee58e719a56d3b","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":"7dc9d6bbe0ca46082b5c7d049b230388ff2681831506b2798d7ab6e478e18693","src/rendering_params.rs":"be1d1c433f76926c285d8ecdb747c5d9cc6a6c10c1a1890c0760cd99755ed471","src/test.rs":"d77e45f8866abeea070cbbafd4cbde62d875292e8d191310a04c70091978547c","src/types.rs":"784235c15d61fb0d001373575169aa473c92af18dcbc1709a5b2bbaa3a7ceb22"},"package":"9f013da79c3fb2a9653534b064cd2ca62e10f8b6d19ed8fdc885cb2873412789"}
\ No newline at end of file
rename from third_party/rust/dwrote/.gitignore
rename to third_party/rust/servo-dwrote/.gitignore
new file mode 100644
--- /dev/null
+++ b/third_party/rust/servo-dwrote/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "servo-dwrote"
+description = "Lightweight binding to DirectWrite."
+repository = "https://github.com/servo/dwrote-rs"
+license = "MPL-2.0"
+version = "0.2.0"
+authors = ["Vladimir Vukicevic <vladimir@pobox.com>"]
+build = "build.rs"
+
+[lib]
+name = "dwrote"
+
+[features]
+default = ["codegen"]
+nightly = ["serde/unstable"]
+codegen = ["serde_codegen", "serde_codegen/with-syntex"]
+
+[dependencies]
+libc = "0.2"
+lazy_static = "0.2"
+winapi = "0.2"
+kernel32-sys = "0.2"
+gdi32-sys = "0.2"
+serde = "0.9"
+serde_derive = {version = "0.9", optional = true}
+
+[build-dependencies.serde_codegen]
+version = "0.9"
+default_features = false
+optional = true
rename from third_party/rust/dwrote/README.md
rename to third_party/rust/servo-dwrote/README.md
rename from third_party/rust/dwrote/build.rs
rename to third_party/rust/servo-dwrote/build.rs
rename from third_party/rust/dwrote/src/bitmap_render_target.rs
rename to third_party/rust/servo-dwrote/src/bitmap_render_target.rs
rename from third_party/rust/dwrote/src/com_helpers.rs
rename to third_party/rust/servo-dwrote/src/com_helpers.rs
rename from third_party/rust/dwrote/src/comptr.rs
rename to third_party/rust/servo-dwrote/src/comptr.rs
rename from third_party/rust/dwrote/src/font.rs
rename to third_party/rust/servo-dwrote/src/font.rs
rename from third_party/rust/dwrote/src/font_collection.rs
rename to third_party/rust/servo-dwrote/src/font_collection.rs
rename from third_party/rust/dwrote/src/font_face.rs
rename to third_party/rust/servo-dwrote/src/font_face.rs
rename from third_party/rust/dwrote/src/font_family.rs
rename to third_party/rust/servo-dwrote/src/font_family.rs
rename from third_party/rust/dwrote/src/font_file.rs
rename to third_party/rust/servo-dwrote/src/font_file.rs
rename from third_party/rust/dwrote/src/font_file_loader_impl.rs
rename to third_party/rust/servo-dwrote/src/font_file_loader_impl.rs
rename from third_party/rust/dwrote/src/gdi_interop.rs
rename to third_party/rust/servo-dwrote/src/gdi_interop.rs
rename from third_party/rust/dwrote/src/glyph_run_analysis.rs
rename to third_party/rust/servo-dwrote/src/glyph_run_analysis.rs
rename from third_party/rust/dwrote/src/helpers.rs
rename to third_party/rust/servo-dwrote/src/helpers.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/servo-dwrote/src/lib.rs
@@ -0,0 +1,140 @@
+/* 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/. */
+
+#![allow(non_upper_case_globals)]
+
+#[cfg(feature = "serde_derive")]
+#[macro_use]
+extern crate serde_derive;
+
+#[macro_use]
+extern crate lazy_static;
+#[macro_use(DEFINE_GUID)]
+extern crate winapi;
+extern crate gdi32;
+extern crate kernel32;
+extern crate libc;
+extern crate serde;
+
+#[cfg(feature = "serde_codegen")]
+include!(concat!(env!("OUT_DIR"), "/types.rs"));
+
+#[cfg(feature = "serde_derive")]
+include!("types.rs");
+
+use winapi::DWRITE_FACTORY_TYPE_SHARED;
+use winapi::IDWriteFactory;
+use winapi::IDWriteRenderingParams;
+use std::ffi::CString;
+
+use comptr::ComPtr;
+use winapi::S_OK;
+
+mod comptr;
+mod helpers;
+use helpers::ToWide;
+use std::os::raw::c_void;
+
+#[cfg(test)]
+mod test;
+
+// We still use the DWrite structs for things like metrics; re-export them
+// here
+pub use winapi::DWRITE_FONT_METRICS as FontMetrics;
+pub use winapi::DWRITE_GLYPH_OFFSET as GlyphOffset;
+pub use winapi::{DWRITE_MATRIX, DWRITE_GLYPH_RUN};
+pub use winapi::{DWRITE_RENDERING_MODE_DEFAULT,
+ DWRITE_RENDERING_MODE_ALIASED,
+ DWRITE_RENDERING_MODE_GDI_CLASSIC,
+ DWRITE_RENDERING_MODE_GDI_NATURAL,
+ DWRITE_RENDERING_MODE_NATURAL,
+ DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC,
+ DWRITE_RENDERING_MODE_OUTLINE,
+ DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC,
+ DWRITE_RENDERING_MODE_CLEARTYPE_GDI_NATURAL,
+ DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL,
+ DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC};
+pub use winapi::{DWRITE_MEASURING_MODE_NATURAL,
+ DWRITE_MEASURING_MODE_GDI_CLASSIC,
+ DWRITE_MEASURING_MODE_GDI_NATURAL};
+pub use winapi::{DWRITE_FONT_SIMULATIONS_NONE,
+ DWRITE_FONT_SIMULATIONS_BOLD,
+ DWRITE_FONT_SIMULATIONS_OBLIQUE};
+pub use winapi::{DWRITE_TEXTURE_ALIASED_1x1, DWRITE_TEXTURE_CLEARTYPE_3x1};
+pub use winapi::{DWRITE_RENDERING_MODE};
+pub use winapi::{DWRITE_MEASURING_MODE};
+pub use winapi::{DWRITE_TEXTURE_TYPE};
+
+#[macro_use] mod com_helpers;
+
+mod bitmap_render_target; pub use bitmap_render_target::BitmapRenderTarget;
+mod font; pub use font::Font;
+mod font_collection; pub use font_collection::FontCollection;
+mod font_face; pub use font_face::FontFace;
+mod font_family; pub use font_family::FontFamily;
+mod font_file; pub use font_file::FontFile;
+mod gdi_interop; pub use gdi_interop::GdiInterop;
+mod rendering_params; pub use rendering_params::RenderingParams;
+mod glyph_run_analysis; pub use glyph_run_analysis::GlyphRunAnalysis;
+
+// This is an internal implementation of FontFileLoader, for our utility
+// functions. We don't wrap the DWriteFontFileLoader interface and
+// related things.
+mod font_file_loader_impl;
+
+DEFINE_GUID!{UuidOfIDWriteFactory, 0xb859ee5a, 0xd838, 0x4b5b, 0xa2, 0xe8, 0x1a, 0xdc, 0x7d, 0x93, 0xdb, 0x48}
+
+unsafe impl Sync for ComPtr<IDWriteFactory> { }
+unsafe impl Sync for ComPtr<IDWriteRenderingParams> {}
+
+lazy_static! {
+ static ref DWRITE_FACTORY_RAW_PTR: usize = {
+ unsafe {
+ type DWriteCreateFactoryType = extern "system" fn(winapi::DWRITE_FACTORY_TYPE, winapi::REFIID, *mut *mut winapi::IUnknown) -> winapi::HRESULT;
+
+ let dwrite_dll = kernel32::LoadLibraryW("dwrite.dll".to_wide_null().as_ptr());
+ assert!(!dwrite_dll.is_null());
+ let create_factory_name = CString::new("DWriteCreateFactory").unwrap();
+ let dwrite_create_factory_ptr =
+ kernel32::GetProcAddress(dwrite_dll, create_factory_name.as_ptr() as winapi::LPCSTR);
+ assert!(!dwrite_create_factory_ptr.is_null());
+
+ let dwrite_create_factory =
+ mem::transmute::<*const c_void, DWriteCreateFactoryType>(dwrite_create_factory_ptr);
+
+ let mut factory: ComPtr<IDWriteFactory> = ComPtr::new();
+ let hr = dwrite_create_factory(
+ DWRITE_FACTORY_TYPE_SHARED,
+ &UuidOfIDWriteFactory,
+ factory.getter_addrefs());
+ assert!(hr == S_OK);
+ factory.forget() as usize
+ }
+ };
+
+ static ref DEFAULT_DWRITE_RENDERING_PARAMS_RAW_PTR: usize = {
+ unsafe {
+ let mut default_rendering_params: ComPtr<IDWriteRenderingParams> = ComPtr::new();
+ let hr = (*DWriteFactory()).CreateRenderingParams(default_rendering_params.getter_addrefs());
+ assert!(hr == S_OK);
+
+ default_rendering_params.forget() as usize
+ }
+ };
+
+} // end lazy static
+
+// FIXME vlad would be nice to return, say, FactoryPtr<IDWriteFactory>
+// that has a DerefMut impl, so that we can write
+// DWriteFactory().SomeOperation() as opposed to
+// (*DWriteFactory()).SomeOperation()
+#[allow(non_snake_case)]
+fn DWriteFactory() -> *mut IDWriteFactory {
+ (*DWRITE_FACTORY_RAW_PTR) as *mut IDWriteFactory
+}
+
+#[allow(non_snake_case)]
+fn DefaultDWriteRenderParams() -> *mut IDWriteRenderingParams {
+ (*DEFAULT_DWRITE_RENDERING_PARAMS_RAW_PTR) as *mut IDWriteRenderingParams
+}
rename from third_party/rust/dwrote/src/rendering_params.rs
rename to third_party/rust/servo-dwrote/src/rendering_params.rs
rename from third_party/rust/dwrote/src/test.rs
rename to third_party/rust/servo-dwrote/src/test.rs
rename from third_party/rust/dwrote/src/types.rs
rename to third_party/rust/servo-dwrote/src/types.rs