author | Kartikaya Gupta <kgupta@mozilla.com> |
Tue, 20 Jun 2017 09:37:16 -0400 | |
changeset 365083 | 30e895051542b949bbcca68d5adf26f6f9817050 |
parent 365082 | 41de8a2dbb94c994682c467f42fc36d70d1412b1 |
child 365084 | 71560f69abe2c11df90e59056cdc165c08a159b3 |
push id | 91680 |
push user | kwierso@gmail.com |
push date | Wed, 21 Jun 2017 01:32:01 +0000 |
treeherder | mozilla-inbound@f7b9dc31956c [default view] [failures only] |
perfherder | [talos] [build metrics] [platform microbench] (compared to previous push) |
reviewers | jrmuizel |
bugs | 1373381 |
milestone | 56.0a1 |
first release with | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
last release without | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
deleted file mode 100644 --- a/third_party/rust/app_units-0.4.1/.cargo-checksum.json +++ /dev/null @@ -1,1 +0,0 @@ -{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"12cc0f91b51fedf41ae1670d1624ee1d78a284bdb101645b60a06a12de16c069",".travis.yml":"6b96b2c6bfd7e1acef4b825a2813fc4277859eb9400a16800db8835c25e4087d","Cargo.toml":"e8e47fdafc02dca1094469954c142173859165ac583ff702500d6feef5b7cd3f","README.md":"9f048d969f9f8333cdcdb892744cd0816e4f2922c8817fa5e9e07f9472fe1050","src/app_unit.rs":"da3c29a2fa7fc357f41df76f29a5f6983d878a5050cf07443a20c00fe46094fd","src/lib.rs":"2df7d863c47d8b22f9af66caeafa87e6a206ee713a8aeaa55c5a80a42a92513b"},"package":"c89beb28482985f88b312de4021d748f45b3eecec6cc8dbaf0c2b3c3d1ce6da5"} \ No newline at end of file
deleted file mode 100644 --- a/third_party/rust/app_units-0.4.1/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -target/ -Cargo.lock
deleted file mode 100644 --- a/third_party/rust/app_units-0.4.1/.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.4.1/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "app_units" -version = "0.4.1" -authors = ["The Servo Project Developers"] -description = "Servo app units type (Au)" -documentation = "http://doc.servo.org/app_units/" -repository = "https://github.com/servo/app_units" -license = "MPL-2.0" - -[dependencies] -heapsize = "0.3" -num-traits = "0.1.32" -rustc-serialize = "0.3" -serde = "0.9"
deleted file mode 100644 --- a/third_party/rust/app_units-0.4.1/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.4.1/src/app_unit.rs +++ /dev/null @@ -1,379 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use heapsize::HeapSizeOf; -use num_traits::Zero; -use rustc_serialize::{Encodable, Encoder}; -use serde::de::{Deserialize, Deserializer}; -use serde::ser::{Serialize, Serializer}; -use std::default::Default; -use std::fmt; -use std::i32; -use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign}; - -/// The number of app units in a pixel. -pub const AU_PER_PX: i32 = 60; - -#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)] -/// An App Unit, the fundamental unit of length in Servo. Usually -/// 1/60th of a pixel (see AU_PER_PX) -/// -/// Please ensure that the values are between MIN_AU and MAX_AU. -/// It is safe to construct invalid Au values, but it may lead to -/// panics and overflows. -pub struct Au(pub i32); - -impl HeapSizeOf for Au { - fn heap_size_of_children(&self) -> usize { 0 } -} - -impl Deserialize for Au { - fn deserialize<D: Deserializer>(deserializer: D) -> Result<Au, D::Error> { - Ok(Au(try!(i32::deserialize(deserializer))).clamp()) - } -} - -impl Serialize for Au { - fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { - self.0.serialize(serializer) - } -} - -impl Default for Au { - #[inline] - fn default() -> Au { - Au(0) - } -} - -impl Zero for Au { - #[inline] - fn zero() -> Au { - Au(0) - } - - #[inline] - fn is_zero(&self) -> bool { - self.0 == 0 - } -} - -// 1 << 30 lets us add/subtract two Au and check for overflow -// after the operation. Gecko uses the same min/max values -pub const MAX_AU: Au = Au(1 << 30); -pub const MIN_AU: Au = Au(- (1 << 30)); - -impl Encodable for Au { - fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { - e.emit_f64(self.to_f64_px()) - } -} - -impl fmt::Debug for Au { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}px", self.to_f64_px()) - } -} - -impl Add for Au { - type Output = Au; - - #[inline] - fn add(self, other: Au) -> Au { - Au(self.0 + other.0).clamp() - } -} - -impl Sub for Au { - type Output = Au; - - #[inline] - fn sub(self, other: Au) -> Au { - Au(self.0 - other.0).clamp() - } - -} - -impl Mul<i32> for Au { - type Output = Au; - - #[inline] - fn mul(self, other: i32) -> Au { - if let Some(new) = self.0.checked_mul(other) { - Au(new).clamp() - } else if (self.0 > 0) ^ (other > 0) { - MIN_AU - } else { - MAX_AU - } - } -} - -impl Div<i32> for Au { - type Output = Au; - - #[inline] - fn div(self, other: i32) -> Au { - Au(self.0 / other) - } -} - -impl Rem<i32> for Au { - type Output = Au; - - #[inline] - fn rem(self, other: i32) -> Au { - Au(self.0 % other) - } -} - -impl Neg for Au { - type Output = Au; - - #[inline] - fn neg(self) -> Au { - Au(-self.0) - } -} - -impl AddAssign for Au { - #[inline] - fn add_assign(&mut self, other: Au) { - *self = *self + other; - self.clamp_self(); - } -} - -impl SubAssign for Au { - #[inline] - fn sub_assign(&mut self, other: Au) { - *self = *self - other; - self.clamp_self(); - } -} - -impl MulAssign<i32> for Au { - #[inline] - fn mul_assign(&mut self, other: i32) { - *self = *self * other; - self.clamp_self(); - } -} - -impl DivAssign<i32> for Au { - #[inline] - fn div_assign(&mut self, other: i32) { - *self = *self / other; - self.clamp_self(); - } -} - -impl Au { - /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! - #[inline] - pub fn new(value: i32) -> Au { - Au(value).clamp() - } - - #[inline] - fn clamp(self) -> Self { - if self.0 > MAX_AU.0 { - MAX_AU - } else if self.0 < MIN_AU.0 { - MIN_AU - } else { - self - } - } - - #[inline] - fn clamp_self(&mut self) { - *self = self.clamp() - } - - #[inline] - pub fn scale_by(self, factor: f32) -> Au { - let new_float = ((self.0 as f32) * factor).round(); - if new_float > MAX_AU.0 as f32 { - MAX_AU - } else if new_float < MIN_AU.0 as f32 { - MIN_AU - } else { - Au(new_float as i32) - } - } - - #[inline] - pub fn from_px(px: i32) -> Au { - Au(px) * AU_PER_PX - } - - /// Rounds this app unit down to the pixel towards zero and returns it. - #[inline] - pub fn to_px(self) -> i32 { - self.0 / AU_PER_PX - } - - /// Ceil this app unit to the appropriate pixel boundary and return it. - #[inline] - pub fn ceil_to_px(self) -> i32 { - ((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32 - } - - #[inline] - pub fn to_nearest_px(self) -> i32 { - ((self.0 as f64) / (AU_PER_PX as f64)).round() as i32 - } - - #[inline] - pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 { - ((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px - } - - #[inline] - pub fn to_f32_px(self) -> f32 { - (self.0 as f32) / (AU_PER_PX as f32) - } - - #[inline] - pub fn to_f64_px(self) -> f64 { - (self.0 as f64) / (AU_PER_PX as f64) - } - - #[inline] - pub fn from_f32_px(px: f32) -> Au { - let float = (px * AU_PER_PX as f32).round(); - if float > MAX_AU.0 as f32 { - MAX_AU - } else if float < MIN_AU.0 as f32 { - MIN_AU - } else { - Au(float as i32) - } - } - - #[inline] - pub fn from_f64_px(px: f64) -> Au { - let float = (px * AU_PER_PX as f64).round(); - if float > MAX_AU.0 as f64 { - MAX_AU - } else if float < MIN_AU.0 as f64 { - MIN_AU - } else { - Au(float as i32) - } - } -} - -#[test] -fn create() { - assert_eq!(Au::zero(), Au(0)); - assert_eq!(Au::default(), Au(0)); - assert_eq!(Au::new(7), Au(7)); -} - -#[test] -fn operations() { - assert_eq!(Au(7) + Au(5), Au(12)); - assert_eq!(MAX_AU + Au(1), MAX_AU); - - assert_eq!(Au(7) - Au(5), Au(2)); - assert_eq!(MIN_AU - Au(1), MIN_AU); - - assert_eq!(Au(7) * 5, Au(35)); - assert_eq!(MAX_AU * -1, MIN_AU); - assert_eq!(MIN_AU * -1, MAX_AU); - - assert_eq!(Au(35) / 5, Au(7)); - assert_eq!(Au(35) % 6, Au(5)); - - assert_eq!(-Au(7), Au(-7)); -} - -#[test] -fn saturate() { - let half = MAX_AU / 2; - assert_eq!(half + half + half + half + half, MAX_AU); - assert_eq!(-half - half - half - half - half, MIN_AU); - assert_eq!(half * -10, MIN_AU); - assert_eq!(-half * 10, MIN_AU); - assert_eq!(half * 10, MAX_AU); - assert_eq!(-half * -10, MAX_AU); -} - -#[test] -fn scale() { - assert_eq!(Au(12).scale_by(1.5), Au(18)); - assert_eq!(Au(12).scale_by(1.7), Au(20)); - assert_eq!(Au(12).scale_by(1.8), Au(22)); -} - -#[test] -fn convert() { - assert_eq!(Au::from_px(5), Au(300)); - - assert_eq!(Au(300).to_px(), 5); - assert_eq!(Au(330).to_px(), 5); - assert_eq!(Au(350).to_px(), 5); - assert_eq!(Au(360).to_px(), 6); - - assert_eq!(Au(300).ceil_to_px(), 5); - assert_eq!(Au(310).ceil_to_px(), 6); - assert_eq!(Au(330).ceil_to_px(), 6); - assert_eq!(Au(350).ceil_to_px(), 6); - assert_eq!(Au(360).ceil_to_px(), 6); - - assert_eq!(Au(300).to_nearest_px(), 5); - assert_eq!(Au(310).to_nearest_px(), 5); - assert_eq!(Au(330).to_nearest_px(), 6); - assert_eq!(Au(350).to_nearest_px(), 6); - assert_eq!(Au(360).to_nearest_px(), 6); - - assert_eq!(Au(60).to_nearest_pixel(2.), 1.); - assert_eq!(Au(70).to_nearest_pixel(2.), 1.); - assert_eq!(Au(80).to_nearest_pixel(2.), 1.5); - assert_eq!(Au(90).to_nearest_pixel(2.), 1.5); - assert_eq!(Au(100).to_nearest_pixel(2.), 1.5); - assert_eq!(Au(110).to_nearest_pixel(2.), 2.); - assert_eq!(Au(120).to_nearest_pixel(2.), 2.); - - assert_eq!(Au(300).to_f32_px(), 5.); - assert_eq!(Au(312).to_f32_px(), 5.2); - assert_eq!(Au(330).to_f32_px(), 5.5); - assert_eq!(Au(348).to_f32_px(), 5.8); - assert_eq!(Au(360).to_f32_px(), 6.); - assert_eq!((Au(367).to_f32_px() * 1000.).round(), 6_117.); - assert_eq!((Au(368).to_f32_px() * 1000.).round(), 6_133.); - - assert_eq!(Au(300).to_f64_px(), 5.); - assert_eq!(Au(312).to_f64_px(), 5.2); - assert_eq!(Au(330).to_f64_px(), 5.5); - assert_eq!(Au(348).to_f64_px(), 5.8); - assert_eq!(Au(360).to_f64_px(), 6.); - assert_eq!((Au(367).to_f64_px() * 1000.).round(), 6_117.); - assert_eq!((Au(368).to_f64_px() * 1000.).round(), 6_133.); - - assert_eq!(Au::from_f32_px(5.), Au(300)); - assert_eq!(Au::from_f32_px(5.2), Au(312)); - assert_eq!(Au::from_f32_px(5.5), Au(330)); - assert_eq!(Au::from_f32_px(5.8), Au(348)); - assert_eq!(Au::from_f32_px(6.), Au(360)); - assert_eq!(Au::from_f32_px(6.12), Au(367)); - assert_eq!(Au::from_f32_px(6.13), Au(368)); - - assert_eq!(Au::from_f64_px(5.), Au(300)); - assert_eq!(Au::from_f64_px(5.2), Au(312)); - assert_eq!(Au::from_f64_px(5.5), Au(330)); - assert_eq!(Au::from_f64_px(5.8), Au(348)); - assert_eq!(Au::from_f64_px(6.), Au(360)); - assert_eq!(Au::from_f64_px(6.12), Au(367)); - assert_eq!(Au::from_f64_px(6.13), Au(368)); -} - -#[test] -fn heapsize() { - use heapsize::HeapSizeOf; - fn f<T: HeapSizeOf>(_: T) {} - f(Au::new(0)); -}
deleted file mode 100644 --- a/third_party/rust/app_units-0.4.1/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":"f705a11b487bf71c41ebd8223cc1f3cbde0dfdfeea96a100af55e06e93397a1b","Cargo.toml":"3268085d1b2f5a6b658d02c98188a631e81c18323dbe1af2cbcccde8664bf2a4","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","changelist.org":"7e1dd0a38f886c111f9a50bc5ecd8ccab0800fcc737c1c211cc5c3361648aa2b","examples/basic.rs":"ef6ab76936c8322b9f89fe8308311339c0bf7b413c5f88b5314b0035d49917a3","logo.png":"ebc5305aae938c1f834cf35302faa8be0f1b7b8c3c3beef5cf6b2f68b9628c35","readme.dev.md":"43bad3bcc13a5c057344d3ba7f64bd2b313f8c133d6afa068108df73e8e8facd","readme.md":"06e09e4e80b048416116640a8352305ceae48f775fd13786c25892cbf55c8fbd","src/lib.rs":"a4dff78a7c5af47c1dc9f240ba7ba3305dd66f638d2d326627093bb326c5fe59","src/refbox.rs":"fe266cec4f9f36942a1a9a9ad094a4bb1003d0c0f3c070cfb6214790d0f21b69","src/serde/mod.rs":"a4aaf85ac92468e246be4533f014b93b8e21059da22342155d03578a81e7f556","src/serde/reader.rs":"21db7aa79660acaa2ac39adfe273a99a27c2a1c39506e2a782f9c7f76500f866","src/serde/writer.rs":"02819f71cda1742188feb66c9ecf58bbd4e35c6d88961763667a3cde72450963","tests/test.rs":"36f7e11cc480ea9f68c4656d55e065f69998346baa8112fcde1f9c1dc4891c02"},"package":"fb0cdeac1c5d567fdb487ae5853c024e4acf1ea85ba6a6552fe084e0805fea5d"} \ No newline at end of file +{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"e084df3ce631ce22082bd63f9e421e7f4d7a2408d6520de532f6a649e4d320dd",".travis.yml":"f705a11b487bf71c41ebd8223cc1f3cbde0dfdfeea96a100af55e06e93397a1b","Cargo.toml":"b3ef32df664d22cfe4526f0022c8789e8976970b9e0982e1dd52f4f811134515","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","changelist.org":"936b58455e1c221539b73b5250302dcd96baa04a5d8536199d3351142addad57","examples/basic.rs":"ef6ab76936c8322b9f89fe8308311339c0bf7b413c5f88b5314b0035d49917a3","logo.png":"ebc5305aae938c1f834cf35302faa8be0f1b7b8c3c3beef5cf6b2f68b9628c35","readme.dev.md":"43bad3bcc13a5c057344d3ba7f64bd2b313f8c133d6afa068108df73e8e8facd","readme.md":"ca48b4a712089d792d449ef6e0e399efaf227dbcfcb141540684a16a2763583b","src/de/mod.rs":"8651e00130bd062e2305dcce8b68d777fff9877688e776b239778e18046dddaf","src/de/read.rs":"5abca51c6f0d93cc144914ed30bf2cfd0074ced09a0de8c3983997aaa471562d","src/internal.rs":"d9448e8467caf4cf24703626dab9e0d9420e98419e323ad7e611e4aeab525e4a","src/lib.rs":"998b85e103f8f5480ffeef43bd8430a66c061011055a053377f37dce32bf9088","src/ser/mod.rs":"0eeb467eeb8189fb935e4996cd45d1f292c401f92b00793907bd428f1bde421d","tests/test.rs":"26598b882a691caa5301a569e56e31567bfba5ffeab6f0ca67ebd95bfae679b0"},"package":"e103c8b299b28a9c6990458b7013dc4a8356a9b854c51b9883241f5866fac36e"} \ No newline at end of file
--- a/third_party/rust/bincode/Cargo.toml +++ b/third_party/rust/bincode/Cargo.toml @@ -1,21 +1,20 @@ [package] name = "bincode" -version = "1.0.0-alpha6" +version = "0.8.0" authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Daniel Griffen"] repository = "https://github.com/TyOverby/bincode" documentation = "https://docs.rs/bincode" keywords = ["binary", "encode", "decode", "serialize", "deserialize"] license = "MIT" 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.serde] -version = "0.9.*" +serde = "1.*.*" [dev-dependencies] -serde_derive = "0.9.*" +serde_bytes = "0.10.*" +serde_derive = "1.*.*"
--- a/third_party/rust/bincode/changelist.org +++ b/third_party/rust/bincode/changelist.org @@ -17,8 +17,11 @@ Since serde is the only supported serialization mechanism, it makes sense to have these functions available at the top level. ** Added the ability to chose your own endian encoding. This functionality is located in the endian_choice module. ** Changed SizeLimit to be a trait instead of an enum Mostly for performance reasons. + +** Removed RefBox / StrBox / SliceBox + Since rustc-serialize support was phased out, you can use `Cow<T>` with serde.
--- a/third_party/rust/bincode/readme.md +++ b/third_party/rust/bincode/readme.md @@ -1,17 +1,17 @@ # Bincode <img align="right" src="./logo.png" /> [](https://travis-ci.org/TyOverby/bincode) [](https://crates.io/crates/bincode) [](http://opensource.org/licenses/MIT) -A compact encoder / decoder pair that uses an binary zero-fluff encoding scheme. +A compact encoder / decoder pair that uses a binary zero-fluff encoding scheme. The size of the encoded object will be the same or smaller than the size that the object takes up in memory in a running Rust program. In addition to exposing two simple functions that encode to Vec<u8> and decode from Vec<u8>, binary-encode exposes a Reader/Writer API that makes it work perfectly with other stream-based apis such as rust files, network streams, and the [flate2-rs](https://github.com/alexcrichton/flate2-rs) compression library. @@ -25,31 +25,31 @@ library. * [servo/ipc-channel](https://github.com/servo/ipc-channel): Ipc-Channel uses Bincode to send structs between processes using a channel-like API. ## Example ```rust #[macro_use] extern crate serde_derive; extern crate bincode; -use bincode::{serialize, deserialize, SizeLimit}; +use bincode::{serialize, deserialize, Infinite}; #[derive(Serialize, Deserialize, PartialEq)] struct Entity { x: f32, y: f32, } #[derive(Serialize, Deserialize, PartialEq)] struct World(Vec<Entity>); fn main() { let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]); - let encoded: Vec<u8> = serialize(&world, SizeLimit::Infinite).unwrap(); + let encoded: Vec<u8> = serialize(&world, Infinite).unwrap(); // 8 bytes for the length of the vector, 4 bytes per float. assert_eq!(encoded.len(), 8 + 4 * 4); let decoded: World = deserialize(&encoded[..]).unwrap(); assert!(world == decoded); }
new file mode 100644 --- /dev/null +++ b/third_party/rust/bincode/src/de/mod.rs @@ -0,0 +1,416 @@ +use std::io::Read; +use std::marker::PhantomData; + +use byteorder::{ReadBytesExt, ByteOrder}; +use serde_crate as serde; +use serde_crate::de::IntoDeserializer; +use serde_crate::de::Error as DeError; +use ::SizeLimit; +use super::{Result, Error, ErrorKind}; +use self::read::BincodeRead; + +pub mod read; + +/// A Deserializer that reads bytes from a buffer. +/// +/// This struct should rarely be used. +/// In most cases, prefer the `decode_from` function. +/// +/// The ByteOrder that is chosen will impact the endianness that +/// is used to read integers out of the reader. +/// +/// ```rust,ignore +/// let d = Deserializer::new(&mut some_reader, SizeLimit::new()); +/// serde::Deserialize::deserialize(&mut deserializer); +/// let bytes_read = d.bytes_read(); +/// ``` +pub struct Deserializer<R, S: SizeLimit, E: ByteOrder> { + reader: R, + size_limit: S, + _phantom: PhantomData<E>, +} + +impl<'de, R: BincodeRead<'de>, E: ByteOrder, S: SizeLimit> Deserializer<R, S, E> { + /// Creates a new Deserializer with a given `Read`er and a size_limit. + pub fn new(r: R, size_limit: S) -> Deserializer<R, S, E> { + Deserializer { + reader: r, + size_limit: size_limit, + _phantom: PhantomData + } + } + + fn read_bytes(&mut self, count: u64) -> Result<()> { + self.size_limit.add(count) + } + + fn read_type<T>(&mut self) -> Result<()> { + use std::mem::size_of; + self.read_bytes(size_of::<T>() as u64) + } + + fn read_vec(&mut self) -> Result<Vec<u8>> { + let len: usize = try!(serde::Deserialize::deserialize(&mut *self)); + self.read_bytes(len as u64)?; + self.reader.get_byte_buffer(len) + } + + fn read_string(&mut self) -> Result<String> { + String::from_utf8(try!(self.read_vec())).map_err(|err| + 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>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + try!(self.read_type::<$ty>()); + let value = try!(self.reader.$reader_method::<E>()); + visitor.$visitor_method(value) + } + } +} + +impl<'de, 'a, R, S, E> serde::Deserializer<'de> for &'a mut Deserializer<R, S, E> +where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder { + type Error = Error; + + #[inline] + fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + let message = "bincode does not support Deserializer::deserialize"; + Err(Error::custom(message)) + } + + fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + let value: u8 = try!(serde::Deserialize::deserialize(self)); + match value { + 1 => visitor.visit_bool(true), + 0 => visitor.visit_bool(false), + value => { + 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>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + try!(self.read_type::<u8>()); + visitor.visit_u8(try!(self.reader.read_u8())) + } + + #[inline] + fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + try!(self.read_type::<i8>()); + visitor.visit_i8(try!(self.reader.read_i8())) + } + + fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + visitor.visit_unit() + } + + fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + use std::str; + + let error = || { + ErrorKind::InvalidEncoding{ + desc: "Invalid char encoding", + detail: None, + }.into() + }; + + let mut buf = [0u8; 4]; + + // Look at the first byte to see how many bytes must be read + let _ = try!(self.reader.read_exact(&mut buf[..1])); + let width = utf8_char_width(buf[0]); + if width == 1 { return visitor.visit_char(buf[0] as char) } + if width == 0 { return Err(error())} + + if self.reader.read_exact(&mut buf[1..width]).is_err() { + return Err(error()); + } + + let res = try!(str::from_utf8(&buf[..width]).ok().and_then(|s| s.chars().next()).ok_or(error())); + visitor.visit_char(res) + } + + fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + let len: usize = try!(serde::Deserialize::deserialize(&mut *self)); + try!(self.read_bytes(len as u64)); + self.reader.forward_read_str(len, visitor) + } + + fn deserialize_string<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + visitor.visit_string(try!(self.read_string())) + } + + fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + let len: usize = try!(serde::Deserialize::deserialize(&mut *self)); + try!(self.read_bytes(len as u64)); + self.reader.forward_read_bytes(len, visitor) + } + + fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + visitor.visit_byte_buf(try!(self.read_vec())) + } + + fn deserialize_enum<V>(self, + _enum: &'static str, + _variants: &'static [&'static str], + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + impl<'de, 'a, R: 'a, S, E> serde::de::EnumAccess<'de> for &'a mut Deserializer<R, S, E> + where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder { + type Error = Error; + type Variant = Self; + + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)> + where V: serde::de::DeserializeSeed<'de>, + { + let idx: u32 = try!(serde::de::Deserialize::deserialize(&mut *self)); + let val: Result<_> = seed.deserialize(idx.into_deserializer()); + Ok((try!(val), self)) + } + } + + visitor.visit_enum(self) + } + + fn deserialize_tuple<V>(self, + len: usize, + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + struct Access<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> { + deserializer: &'a mut Deserializer<R, S, E>, + len: usize, + } + + impl<'de, 'a, 'b: 'a, R: BincodeRead<'de>+ 'b, S: SizeLimit, E: ByteOrder> serde::de::SeqAccess<'de> for Access<'a, R, S, E> { + type Error = Error; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> + where T: serde::de::DeserializeSeed<'de>, + { + if self.len > 0 { + self.len -= 1; + let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)); + Ok(Some(value)) + } else { + Ok(None) + } + } + + fn size_hint(&self) -> Option<usize> { + Some(self.len) + } + } + + visitor.visit_seq(Access { deserializer: self, len: len }) + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + 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<'de>, + { + let len = try!(serde::Deserialize::deserialize(&mut *self)); + + self.deserialize_tuple(len, visitor) + } + + fn deserialize_map<V>(self, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + struct Access<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> { + deserializer: &'a mut Deserializer<R, S, E>, + len: usize, + } + + impl<'de, 'a, 'b: 'a, R: BincodeRead<'de> + 'b, S: SizeLimit, E: ByteOrder> serde::de::MapAccess<'de> for Access<'a, R, S, E> { + type Error = Error; + + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> + where K: serde::de::DeserializeSeed<'de>, + { + if self.len > 0 { + self.len -= 1; + let key = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)); + Ok(Some(key)) + } else { + Ok(None) + } + } + + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> + where V: serde::de::DeserializeSeed<'de>, + { + let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)); + Ok(value) + } + + fn size_hint(&self) -> Option<usize> { + Some(self.len) + } + } + + let len = try!(serde::Deserialize::deserialize(&mut *self)); + + visitor.visit_map(Access { deserializer: self, len: len }) + } + + fn deserialize_struct<V>(self, + _name: &str, + fields: &'static [&'static str], + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + self.deserialize_tuple(fields.len(), visitor) + } + + fn deserialize_identifier<V>(self, + _visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + let message = "bincode does not support Deserializer::deserialize_identifier"; + Err(Error::custom(message)) + } + + fn deserialize_newtype_struct<V>(self, + _name: &str, + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_unit_struct<V>(self, + _name: &'static str, + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + visitor.visit_unit() + } + + fn deserialize_tuple_struct<V>(self, + _name: &'static str, + len: usize, + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + self.deserialize_tuple(len, visitor) + } + + fn deserialize_ignored_any<V>(self, + _visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + let message = "bincode does not support Deserializer::deserialize_ignored_any"; + Err(Error::custom(message)) + } +} + +impl<'de, 'a, R, S, E> serde::de::VariantAccess<'de> for &'a mut Deserializer<R, S, E> +where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder { + type Error = Error; + + fn unit_variant(self) -> Result<()> { + Ok(()) + } + + fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> + where T: serde::de::DeserializeSeed<'de>, + { + serde::de::DeserializeSeed::deserialize(seed, self) + } + + fn tuple_variant<V>(self, + len: usize, + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + serde::de::Deserializer::deserialize_tuple(self, len, visitor) + } + + fn struct_variant<V>(self, + fields: &'static [&'static str], + visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'de>, + { + 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 +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 +}
new file mode 100644 --- /dev/null +++ b/third_party/rust/bincode/src/de/read.rs @@ -0,0 +1,151 @@ +use std::io::{Read as IoRead, Result as IoResult, Error as IoError, ErrorKind as IoErrorKind}; +use ::Result; +use serde_crate as serde; + +/// A byte-oriented reading trait that is specialized for +/// slices and generic readers. +pub trait BincodeRead<'storage>: IoRead { + #[doc(hidden)] + fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'storage>; + + #[doc(hidden)] + fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>>; + + #[doc(hidden)] + fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'storage>; +} + +/// A BincodeRead implementation for byte slices +pub struct SliceReader<'storage> { + slice: &'storage [u8] +} + +/// A BincodeRead implementation for io::Readers +pub struct IoReadReader<R> { + reader: R, + temp_buffer: Vec<u8>, +} + +impl <'storage> SliceReader<'storage> { + /// Constructs a slice reader + pub fn new(bytes: &'storage [u8]) -> SliceReader<'storage> { + SliceReader { + slice: bytes, + } + } +} + +impl <R> IoReadReader<R> { + /// Constructs an IoReadReader + pub fn new(r: R) -> IoReadReader<R> { + IoReadReader { + reader: r, + temp_buffer: vec![], + } + } +} + +impl <'storage> IoRead for SliceReader<'storage> { + fn read(&mut self, out: & mut [u8]) -> IoResult<usize> { + (&mut self.slice).read(out) + } +} + +impl <R: IoRead> IoRead for IoReadReader<R> { + fn read(&mut self, out: & mut [u8]) -> IoResult<usize> { + self.reader.read(out) + } +} + +impl <'storage> SliceReader<'storage> { + fn unexpected_eof() -> Box<::ErrorKind> { + return Box::new(::ErrorKind::IoError(IoError::new(IoErrorKind::UnexpectedEof, ""))); + } +} + +impl <'storage> BincodeRead<'storage> for SliceReader<'storage> { + fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'storage> { + use ::ErrorKind; + if length > self.slice.len() { + return Err(SliceReader::unexpected_eof()); + } + + let string = match ::std::str::from_utf8(&self.slice[..length]) { + Ok(s) => s, + Err(_) => return Err(Box::new(ErrorKind::InvalidEncoding { + desc: "string was not valid utf8", + detail: None, + })), + }; + let r = visitor.visit_borrowed_str(string); + self.slice = &self.slice[length..]; + r + } + + fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> { + if length > self.slice.len() { + return Err(SliceReader::unexpected_eof()); + } + + let r = &self.slice[..length]; + self.slice = &self.slice[length..]; + Ok(r.to_vec()) + } + + fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'storage> { + if length > self.slice.len() { + return Err(SliceReader::unexpected_eof()); + } + + let r = visitor.visit_borrowed_bytes(&self.slice[..length]); + self.slice = &self.slice[length..]; + r + } +} + +impl <R> IoReadReader<R> where R: IoRead { + fn fill_buffer(&mut self, length: usize) -> Result<()> { + let current_length = self.temp_buffer.len(); + if length > current_length{ + self.temp_buffer.reserve_exact(length - current_length); + unsafe { self.temp_buffer.set_len(length); } + } + + self.reader.read_exact(&mut self.temp_buffer[..length])?; + Ok(()) + } +} + +impl <R> BincodeRead<'static> for IoReadReader<R> where R: IoRead { + fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'static> { + self.fill_buffer(length)?; + + let string = match ::std::str::from_utf8(&self.temp_buffer[..length]) { + Ok(s) => s, + Err(_) => return Err(Box::new(::ErrorKind::InvalidEncoding { + desc: "string was not valid utf8", + detail: None, + })), + }; + + let r = visitor.visit_str(string); + r + } + + fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> { + self.fill_buffer(length)?; + Ok(self.temp_buffer[..length].to_vec()) + } + + fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value> + where V: serde::de::Visitor<'static> { + self.fill_buffer(length)?; + let r = visitor.visit_bytes(&self.temp_buffer[..length]); + r + } +}
new file mode 100644 --- /dev/null +++ b/third_party/rust/bincode/src/internal.rs @@ -0,0 +1,240 @@ +//! 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; +use byteorder::{ByteOrder}; + +pub use super::de::{ + Deserializer, +}; + +pub use super::ser::{ + Serializer, +}; + +use super::ser::SizeChecker; + +use serde_crate as serde; + +/// The result of a serialization or deserialization operation. +pub type Result<T> = result::Result<T, Error>; + +/// An error that can be produced during (de)serializing. +/// +/// If decoding from a Buffer, assume that the buffer has been left +/// in an invalid state. +pub type Error = Box<ErrorKind>; + +/// The kind of error that can be produced during a serialization or deserialization. +#[derive(Debug)] +pub enum ErrorKind { + /// If the error stems from the reader/writer that is being used + /// 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 { + #[allow(missing_docs)] + desc: &'static str, + #[allow(missing_docs)] + detail: Option<String> + }, + /// If (de)serializing a message takes more than the provided size limit, this + /// error is returned. + SizeLimit, + /// Bincode can not encode sequences of unknown length (like iterators). + SequenceMustHaveLength, + /// A custom error message from Serde. + Custom(String) +} + +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 `Error` (other than SizeLimit), assume that the +/// writer is in an invalid state, as writing could bail out in the middle of +/// serializing. +pub fn serialize_into<W: ?Sized, T: ?Sized, S, E>(writer: &mut W, value: &T, size_limit: S) -> Result<()> + where W: Write, T: serde::Serialize, S: SizeLimit, E: ByteOrder +{ + if let Some(limit) = size_limit.limit() { + try!(serialized_size_bounded(value, limit).ok_or(ErrorKind::SizeLimit)); + } + + let mut serializer = Serializer::<_, E>::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: ?Sized, S, E>(value: &T, size_limit: S) -> Result<Vec<u8>> + where T: serde::Serialize, S: SizeLimit, E: ByteOrder +{ + let mut writer = match size_limit.limit() { + Some(size_limit) => { + let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(ErrorKind::SizeLimit)); + Vec::with_capacity(actual_size as usize) + } + None => { + let size = serialized_size(value) as usize; + Vec::with_capacity(size) + } + }; + + try!(serialize_into::<_, _, _, E>(&mut writer, value, super::Infinite)); + Ok(writer) +} + + +struct CountSize { + total: u64, + limit: Option<u64>, +} + +impl SizeLimit for CountSize { + fn add(&mut self, c: u64) -> Result<()> { + self.total += c; + if let Some(limit) = self.limit { + if self.total > limit { + return Err(Box::new(ErrorKind::SizeLimit)) + } + } + Ok(()) + } + + fn limit(&self) -> Option<u64> { + unreachable!(); + } +} + +/// 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: ?Sized>(value: &T) -> u64 + where T: serde::Serialize +{ + let mut size_counter = SizeChecker { + size_limit: CountSize { total: 0, limit: None } + }; + + value.serialize(&mut size_counter).ok(); + size_counter.size_limit.total +} + +/// 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: ?Sized>(value: &T, max: u64) -> Option<u64> + where T: serde::Serialize +{ + let mut size_counter = SizeChecker { + size_limit: CountSize { total: 0, limit: Some(max) } + }; + + match value.serialize(&mut size_counter) { + Ok(_) => Some(size_counter.size_limit.total), + Err(_) => None, + } +} + +/// 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 `Error`, assume that the buffer that you passed +/// in is in an invalid state, as the error could be returned during any point +/// in the reading. +pub fn deserialize_from<R: ?Sized, T, S, E>(reader: &mut R, size_limit: S) -> Result<T> + where R: Read, T: serde::de::DeserializeOwned, S: SizeLimit, E: ByteOrder +{ + let reader = ::de::read::IoReadReader::new(reader); + let mut deserializer = Deserializer::<_, S, E>::new(reader, size_limit); + serde::Deserialize::deserialize(&mut deserializer) +} + +/// 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<'a, T, E: ByteOrder>(bytes: &'a [u8]) -> Result<T> + where T: serde::de::Deserialize<'a>, +{ + let reader = ::de::read::SliceReader::new(bytes); + let mut deserializer = Deserializer::<_, _, E>::new(reader, super::Infinite); + serde::Deserialize::deserialize(&mut deserializer) +}
--- a/third_party/rust/bincode/src/lib.rs +++ b/third_party/rust/bincode/src/lib.rs @@ -1,22 +1,24 @@ +#![deny(missing_docs)] + //! `bincode` is a crate for encoding and decoding using a tiny binary //! serialization strategy. //! //! There are simple functions for encoding to `Vec<u8>` and decoding from //! `&[u8]`, but the meat of the library is the `encode_into` and `decode_from` //! functions which respectively allow encoding into a `std::io::Writer` //! and decoding from a `std::io::Buffer`. //! //! ## Modules -//! There are two ways to encode and decode structs using `bincode`, either using `rustc_serialize` -//! or the `serde` crate. `rustc_serialize` and `serde` are crates and and also the names of their -//! corresponding modules inside of `bincode`. Both modules have exactly equivalant functions, and -//! and the only difference is whether or not the library user wants to use `rustc_serialize` or -//! `serde`. +//! Until "default type parameters" lands, we have an extra module called `endian_choice` +//! that duplicates all of the core bincode functionality but with the option to choose +//! which endianness the integers are encoded using. +//! +//! The default endianness is little. //! //! ### Using Basic Functions //! //! ```rust //! extern crate bincode; //! use bincode::{serialize, deserialize, Bounded}; //! fn main() { //! // The object that we will serialize. @@ -29,83 +31,85 @@ //! assert_eq!(target, decoded); //! } //! ``` #![crate_name = "bincode"] #![crate_type = "rlib"] #![crate_type = "dylib"] -#![doc(html_logo_url = "./icon.png")] - extern crate byteorder; extern crate num_traits; extern crate serde as serde_crate; -pub mod refbox; -mod serde; +mod ser; +mod de; +pub mod internal; -pub mod endian_choice { - pub use super::serde::{Deserializer, Serializer, serialize, serialize_into, deserialize, deserialize_from}; +pub mod read_types { + //! The types that the deserializer uses for optimizations + pub use ::de::read::{SliceReader, BincodeRead, IoReadReader}; } use std::io::{Read, Write}; -pub use serde::{ErrorKind, Error, Result, serialized_size, serialized_size_bounded}; +pub use internal::{ErrorKind, Error, Result, serialized_size, serialized_size_bounded}; -pub type Deserializer<W, S> = serde::Deserializer<W, S, byteorder::LittleEndian>; -pub type Serializer<W> = serde::Serializer<W, byteorder::LittleEndian>; +/// A Deserializer that uses LittleEndian byteorder +pub type Deserializer<W, S> = internal::Deserializer<W, S, byteorder::LittleEndian>; +/// A Serializer that uses LittleEndian byteorder +pub type Serializer<W> = internal::Serializer<W, byteorder::LittleEndian>; /// Deserializes a slice of bytes into an object. /// /// This method does not have a size-limit because if you already have the bytes /// in memory, then you don't gain anything by having a limiter. -pub fn deserialize<T>(bytes: &[u8]) -> serde::Result<T> - where T: serde_crate::Deserialize, +pub fn deserialize<'a, T>(bytes: &'a [u8]) -> internal::Result<T> + where T: serde_crate::de::Deserialize<'a>, { - serde::deserialize::<_, byteorder::LittleEndian>(bytes) + internal::deserialize::<_, byteorder::LittleEndian>(bytes) } /// Deserializes an object directly from a `Buffer`ed Reader. /// /// 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 `Error`, assume that the buffer that you passed /// in is in an invalid state, as the error could be returned during any point /// in the reading. -pub fn deserialize_from<R: ?Sized, T, S>(reader: &mut R, size_limit: S) -> serde::Result<T> - where R: Read, T: serde_crate::Deserialize, S: SizeLimit +pub fn deserialize_from<R: ?Sized, T, S>(reader: &mut R, size_limit: S) -> internal::Result<T> + where R: Read, T: serde_crate::de::DeserializeOwned, S: SizeLimit { - serde::deserialize_from::<_, _, _, byteorder::LittleEndian>(reader, size_limit) + internal::deserialize_from::<_, _, _, byteorder::LittleEndian>(reader, size_limit) } /// Serializes an object directly into a `Writer`. /// /// 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 `Error` (other than SizeLimit), assume that the /// writer is in an invalid state, as writing could bail out in the middle of /// serializing. -pub fn serialize_into<W: ?Sized, T: ?Sized, S>(writer: &mut W, value: &T, size_limit: S) -> serde::Result<()> +pub fn serialize_into<W: ?Sized, T: ?Sized, S>(writer: &mut W, value: &T, size_limit: S) -> internal::Result<()> where W: Write, T: serde_crate::Serialize, S: SizeLimit { - serde::serialize_into::<_, _, _, byteorder::LittleEndian>(writer, value, size_limit) + internal::serialize_into::<_, _, _, byteorder::LittleEndian>(writer, value, size_limit) } /// Serializes a serializable object into a `Vec` of bytes. /// /// If the serialization would take more bytes than allowed by `size_limit`, /// an error is returned. -pub fn serialize<T: ?Sized, S>(value: &T, size_limit: S) -> serde::Result<Vec<u8>> +pub fn serialize<T: ?Sized, S>(value: &T, size_limit: S) -> internal::Result<Vec<u8>> where T: serde_crate::Serialize, S: SizeLimit { - serde::serialize::<_, _, byteorder::LittleEndian>(value, size_limit) + internal::serialize::<_, _, byteorder::LittleEndian>(value, size_limit) } /// A limit on the amount of bytes that can be read or written. /// /// 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 @@ -117,38 +121,47 @@ pub fn serialize<T: ?Sized, S>(value: &T /// any more than that. /// /// On the other side, you want to make sure that you aren't encoding a message /// that is larger than your decoder expects. By supplying a size limit to an /// 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. pub trait SizeLimit { + /// Tells the SizeLimit that a certain number of bytes has been + /// read or written. Returns Err if the limit has been exceeded. fn add(&mut self, n: u64) -> Result<()>; + /// Returns the hard limit (if one exists) fn limit(&self) -> Option<u64>; } +/// A SizeLimit that restricts serialized or deserialized messages from +/// exceeding a certain byte length. #[derive(Copy, Clone)] pub struct Bounded(pub u64); +/// A SizeLimit without a limit! +/// Use this if you don't care about the size of encoded or decoded messages. #[derive(Copy, Clone)] pub struct Infinite; impl SizeLimit for Bounded { #[inline(always)] fn add(&mut self, n: u64) -> Result<()> { if self.0 >= n { self.0 -= n; Ok(()) } else { Err(Box::new(ErrorKind::SizeLimit)) } } + #[inline(always)] fn limit(&self) -> Option<u64> { Some(self.0) } } impl SizeLimit for Infinite { #[inline(always)] fn add(&mut self, _: u64) -> Result<()> { Ok (()) } + #[inline(always)] fn limit(&self) -> Option<u64> { None } }
deleted file mode 100644 --- a/third_party/rust/bincode/src/refbox.rs +++ /dev/null @@ -1,363 +0,0 @@ -use std::boxed::Box; -use std::ops::Deref; - -use serde_crate as serde; - -/// A struct for encoding nested reference types. -/// -/// Encoding large objects by reference is really handy. For example, -/// `encode(&large_hashmap, ...)` encodes the large structure without having to -/// own the hashmap. However, it is impossible to serialize a reference if that -/// reference is inside of a struct. -/// -/// ```ignore rust -/// // Not possible, rustc can not decode the reference. -/// #[derive(RustcEncoding, RustcDecoding)] -/// struct Message<'a> { -/// big_map: &'a HashMap<u32, u32>, -/// message_type: String, -/// } -/// ``` -/// -/// This is because on the decoding side, you can't create the Message struct -/// because it needs to have a reference to a HashMap, which is impossible because -/// during deserialization, all members need to be owned by the deserialized -/// object. -/// -/// This is where RefBox comes in. During serialization, it serializs a reference, -/// but during deserialization, it puts that sub-object into a box! -/// -/// ```ignore rust -/// // This works! -/// #[derive(RustcEncoding, RustcDecoding)] -/// struct Message<'a> { -/// big_map: RefBox<'a, HashMap<u32, u32>>, -/// message_type: String -/// } -/// ``` -/// -/// Now we can write -/// -/// ```ignore rust -/// let my_map = HashMap::new(); -/// let my_msg = Message { -/// big_map: RefBox::new(&my_map), -/// message_type: "foo".to_string() -/// }; -/// -/// let encoded = encode(&my_msg, ...).unwrap(); -/// let decoded: Message<'static> = decode(&encoded[]).unwrap(); -/// ``` -/// -/// Notice that we managed to encode and decode a struct with a nested reference -/// and that the decoded message has the lifetime `'static` which shows us -/// that the message owns everything inside it completely. -/// -/// Please don't stick RefBox inside deep data structures. It is much better -/// suited in the outermost layer of whatever it is that you are encoding. -#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Clone)] -pub struct RefBox<'a, T: 'a> { - inner: RefBoxInner<'a, T, Box<T>> -} - -/// Like a RefBox, but encoding from a `str` and decoedes to a `String`. -#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Clone)] -pub struct StrBox<'a> { - inner: RefBoxInner<'a, str, String> -} - -/// Like a RefBox, but encodes from a `[T]` and encodes to a `Vec<T>`. -#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Clone)] -pub struct SliceBox<'a, T: 'a> { - inner: RefBoxInner<'a, [T], Vec<T>> -} - -#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Hash)] -enum RefBoxInner<'a, A: 'a + ?Sized, B> { - Ref(&'a A), - Box(B) -} - -impl<'a, T> Clone for RefBoxInner<'a, T, Box<T>> where T: Clone { - fn clone(&self) -> RefBoxInner<'a, T, Box<T>> { - match *self { - RefBoxInner::Ref(reff) => RefBoxInner::Box(Box::new(reff.clone())), - RefBoxInner::Box(ref boxed) => RefBoxInner::Box(boxed.clone()) - } - } -} - -impl<'a> Clone for RefBoxInner<'a, str, String> { - fn clone(&self) -> RefBoxInner<'a, str, String> { - match *self { - RefBoxInner::Ref(reff) => RefBoxInner::Box(String::from(reff)), - RefBoxInner::Box(ref boxed) => RefBoxInner::Box(boxed.clone()) - } - } -} - -impl<'a, T> Clone for RefBoxInner<'a, [T], Vec<T>> where T: Clone { - fn clone(&self) -> RefBoxInner<'a, [T], Vec<T>> { - match *self { - RefBoxInner::Ref(reff) => RefBoxInner::Box(Vec::from(reff)), - RefBoxInner::Box(ref boxed) => RefBoxInner::Box(boxed.clone()) - } - } -} - -impl <'a, T> RefBox<'a, T> { - /// Creates a new RefBox that looks at a borrowed value. - pub fn new(v: &'a T) -> RefBox<'a, T> { - RefBox { - inner: RefBoxInner::Ref(v) - } - } -} - -impl <T> RefBox<'static, T> { - /// Takes the value out of this refbox. - /// - /// Fails if this refbox was not created out of a deserialization. - /// - /// Unless you are doing some really weird things with static references, - /// this function will never fail. - pub fn take(self) -> Box<T> { - match self.inner { - RefBoxInner::Box(b) => b, - _ => unreachable!() - } - } - - /// Tries to take the value out of this refbox. - pub fn try_take(self) -> Result<Box<T>, RefBox<'static, T>> { - match self.inner { - RefBoxInner::Box(b) => Ok(b), - o => Err(RefBox{ inner: o}) - } - } -} - -impl<'a, T> serde::Serialize for RefBox<'a, T> - where T: serde::Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: serde::Serializer - { - serde::Serialize::serialize(&self.inner, serializer) - } -} - -impl<'a, T: serde::Deserialize> serde::Deserialize for RefBox<'a, T> { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where D: serde::Deserializer - { - let inner = try!(serde::Deserialize::deserialize(deserializer)); - Ok(RefBox{ inner: inner }) - } -} - -impl<'a> StrBox<'a> { - /// Creates a new StrBox that looks at a borrowed value. - pub fn new(s: &'a str) -> StrBox<'a> { - StrBox { - inner: RefBoxInner::Ref(s) - } - } - - /// Extract a String from a StrBox. - pub fn into_string(self) -> String { - match self.inner { - RefBoxInner::Ref(s) => String::from(s), - RefBoxInner::Box(s) => s - } - } - - /// Convert to an Owned `SliceBox`. - pub fn to_owned(self) -> StrBox<'static> { - match self.inner { - RefBoxInner::Ref(s) => StrBox::boxed(String::from(s)), - RefBoxInner::Box(s) => StrBox::boxed(s) - } - } -} - -impl<'a> AsRef<str> for StrBox<'a> { - fn as_ref(&self) -> &str { - match self.inner { - RefBoxInner::Ref(ref s) => s, - RefBoxInner::Box(ref s) => s - } - } -} - -impl StrBox<'static> { - /// Creates a new StrBox made from an allocated String. - pub fn boxed(s: String) -> StrBox<'static> { - StrBox { inner: RefBoxInner::Box(s) } - } - - /// Takes the value out of this refbox. - /// - /// Fails if this refbox was not created out of a deserialization. - /// - /// Unless you are doing some really weird things with static references, - /// this function will never fail. - pub fn take(self) -> String { - match self.inner { - RefBoxInner::Box(b) => b, - RefBoxInner::Ref(b) => String::from(b) - } - } - - /// Tries to take the value out of this refbox. - pub fn try_take(self) -> Result<String, StrBox<'static>> { - match self.inner { - RefBoxInner::Box(b) => Ok(b), - o => Err(StrBox{ inner: o}) - } - } -} - - -impl<'a> serde::Serialize for StrBox<'a> { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: serde::Serializer - { - serde::Serialize::serialize(&self.inner, serializer) - } -} - -impl serde::Deserialize for StrBox<'static> { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where D: serde::Deserializer - { - let inner = try!(serde::Deserialize::deserialize(deserializer)); - Ok(StrBox{ inner: inner }) - } -} - -// -// SliceBox -// - -impl <'a, T> SliceBox<'a, T> { - /// Creates a new RefBox that looks at a borrowed value. - pub fn new(v: &'a [T]) -> SliceBox<'a, T> { - SliceBox { - inner: RefBoxInner::Ref(v) - } - } - - /// Extract a `Vec<T>` from a `SliceBox`. - pub fn into_vec(self) -> Vec<T> where T: Clone { - match self.inner { - RefBoxInner::Ref(s) => s.to_vec(), - RefBoxInner::Box(s) => s - } - } - - /// Convert to an Owned `SliceBox`. - pub fn to_owned(self) -> SliceBox<'static, T> where T: Clone { - match self.inner { - RefBoxInner::Ref(s) => SliceBox::boxed(s.to_vec()), - RefBoxInner::Box(s) => SliceBox::boxed(s) - } - } -} - -impl <T> SliceBox<'static, T> { - /// Creates a new SliceBox made from an allocated `Vec<T>`. - pub fn boxed(s: Vec<T>) -> SliceBox<'static, T> { - SliceBox { inner: RefBoxInner::Box(s) } - } - - /// Takes the value out of this refbox. - /// - /// Fails if this refbox was not created out of a deserialization. - /// - /// Unless you are doing some really weird things with static references, - /// this function will never fail. - pub fn take(self) -> Vec<T> { - match self.inner { - RefBoxInner::Box(b) => b, - _ => unreachable!() - } - } - - /// Tries to take the value out of this refbox. - pub fn try_take(self) -> Result<Vec<T>, SliceBox<'static, T>> { - match self.inner { - RefBoxInner::Box(b) => Ok(b), - o => Err(SliceBox{ inner: o}) - } - } -} - - -impl<'a, T> serde::Serialize for SliceBox<'a, T> - where T: serde::Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: serde::Serializer - { - serde::Serialize::serialize(&self.inner, serializer) - } -} - -impl<'a, T: serde::Deserialize> serde::Deserialize for SliceBox<'a, T> { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where D: serde::Deserializer - { - let inner = try!(serde::Deserialize::deserialize(deserializer)); - Ok(SliceBox{ inner: inner }) - } -} - - -impl<'a, A: ?Sized, B> serde::Serialize for RefBoxInner<'a, A, B> - where A: serde::Serialize, - B: serde::Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: serde::Serializer - { - match self { - &RefBoxInner::Ref(ref r) => serde::Serialize::serialize(r, serializer), - &RefBoxInner::Box(ref b) => serde::Serialize::serialize(b, serializer), - } - } -} - - -impl<'a, A: ?Sized, B> serde::Deserialize for RefBoxInner<'a, A, B> - where B: serde::Deserialize, -{ - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where D: serde::Deserializer - { - let deserialized = try!(serde::Deserialize::deserialize(deserializer)); - Ok(RefBoxInner::Box(deserialized)) - } -} - -impl <'a, T> Deref for RefBox<'a, T> { - type Target = T; - - fn deref(&self) -> &T { - match &self.inner { - &RefBoxInner::Ref(ref t) => t, - &RefBoxInner::Box(ref b) => b.deref() - } - } -} - -impl <'a, T> Deref for SliceBox<'a, T> { - type Target = [T]; - - fn deref(&self) -> &[T] { - match &self.inner { - &RefBoxInner::Ref(ref t) => t, - &RefBoxInner::Box(ref b) => b.deref() - } - } -}
new file mode 100644 --- /dev/null +++ b/third_party/rust/bincode/src/ser/mod.rs @@ -0,0 +1,687 @@ +use std::io::Write; +use std::u32; +use std::marker::PhantomData; + +use serde_crate as serde; + +use byteorder::{WriteBytesExt, ByteOrder}; + +use super::{Result, Error, ErrorKind}; +use super::SizeLimit; + +/// An Serializer that encodes values directly into a Writer. +/// +/// The specified byte-order will impact the endianness that is +/// used during the encoding. +/// +/// This struct should not be used often. +/// For most cases, prefer the `encode_into` function. +pub struct Serializer<W, E: ByteOrder> { + writer: W, + _phantom: PhantomData<E>, +} + +impl<W: Write, E: ByteOrder> Serializer<W, E> { + /// Creates a new Serializer with the given `Write`r. + pub fn new(w: W) -> Serializer<W, E> { + Serializer { + writer: w, + _phantom: PhantomData, + } + } +} + +impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E> { + type Ok = (); + type Error = Error; + type SerializeSeq = Compound<'a, W, E>; + type SerializeTuple = Compound<'a, W, E>; + type SerializeTupleStruct = Compound<'a, W, E>; + type SerializeTupleVariant = Compound<'a, W, E>; + type SerializeMap = Compound<'a, W, E>; + type SerializeStruct = Compound<'a, W, E>; + type SerializeStructVariant = Compound<'a, W, E>; + + fn serialize_unit(self) -> Result<()> { Ok(()) } + + fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) } + + fn serialize_bool(self, v: bool) -> Result<()> { + self.writer.write_u8(if v {1} else {0}).map_err(Into::into) + } + + fn serialize_u8(self, v: u8) -> Result<()> { + self.writer.write_u8(v).map_err(Into::into) + } + + fn serialize_u16(self, v: u16) -> Result<()> { + self.writer.write_u16::<E>(v).map_err(Into::into) + } + + fn serialize_u32(self, v: u32) -> Result<()> { + self.writer.write_u32::<E>(v).map_err(Into::into) + } + + fn serialize_u64(self, v: u64) -> Result<()> { + self.writer.write_u64::<E>(v).map_err(Into::into) + } + + fn serialize_i8(self, v: i8) -> Result<()> { + self.writer.write_i8(v).map_err(Into::into) + } + + fn serialize_i16(self, v: i16) -> Result<()> { + self.writer.write_i16::<E>(v).map_err(Into::into) + } + + fn serialize_i32(self, v: i32) -> Result<()> { + self.writer.write_i32::<E>(v).map_err(Into::into) + } + + fn serialize_i64(self, v: i64) -> Result<()> { + self.writer.write_i64::<E>(v).map_err(Into::into) + } + + fn serialize_f32(self, v: f32) -> Result<()> { + self.writer.write_f32::<E>(v).map_err(Into::into) + } + + fn serialize_f64(self, v: f64) -> Result<()> { + self.writer.write_f64::<E>(v).map_err(Into::into) + } + + 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_char(self, c: char) -> Result<()> { + self.writer.write_all(encode_utf8(c).as_slice()).map_err(Into::into) + } + + 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(self) -> Result<()> { + self.writer.write_u8(0).map_err(Into::into) + } + + fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()> + where T: serde::Serialize, + { + try!(self.writer.write_u8(1)); + v.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_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { + Ok(Compound {ser: self}) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { + Ok(Compound {ser: self}) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + _len: usize) -> Result<Self::SerializeTupleVariant> + { + try!(self.serialize_u32(variant_index)); + Ok(Compound {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(Compound {ser: self}) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { + Ok(Compound {ser: self}) + } + + fn serialize_struct_variant(self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + _len: usize) -> Result<Self::SerializeStructVariant> + { + try!(self.serialize_u32(variant_index)); + Ok(Compound {ser: self}) + } + + fn serialize_newtype_struct<T: ?Sized>(self, + _name: &'static str, + value: &T) -> Result<()> + where T: serde::ser::Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + value: &T) -> Result<()> + where T: serde::ser::Serialize, + { + try!(self.serialize_u32(variant_index)); + value.serialize(self) + } + + fn serialize_unit_variant(self, + _name: &'static str, + variant_index: u32, + _variant: &'static str) -> Result<()> { + self.serialize_u32(variant_index) + } +} + +pub struct SizeChecker<S: SizeLimit> { + pub size_limit: S, +} + +impl <S: SizeLimit> SizeChecker<S> { + pub fn new(size_limit: S) -> SizeChecker<S> { + SizeChecker { + size_limit: size_limit + } + } + + fn add_raw(&mut self, size: u64) -> Result<()> { + self.size_limit.add(size) + } + + fn add_value<T>(&mut self, t: T) -> Result<()> { + use std::mem::size_of_val; + self.add_raw(size_of_val(&t) as u64) + } +} + +impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> { + type Ok = (); + type Error = Error; + type SerializeSeq = SizeCompound<'a, S>; + type SerializeTuple = SizeCompound<'a, S>; + type SerializeTupleStruct = SizeCompound<'a, S>; + type SerializeTupleVariant = SizeCompound<'a, S>; + type SerializeMap = SizeCompound<'a, S>; + type SerializeStruct = SizeCompound<'a, S>; + type SerializeStructVariant = SizeCompound<'a, S>; + + fn serialize_unit(self) -> Result<()> { Ok(()) } + + fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) } + + fn serialize_bool(self, _: bool) -> Result<()> { + self.add_value(0 as u8) + } + + fn serialize_u8(self, v: u8) -> Result<()> { + self.add_value(v) + } + + fn serialize_u16(self, v: u16) -> Result<()> { + self.add_value(v) + } + + fn serialize_u32(self, v: u32) -> Result<()> { + self.add_value(v) + } + + fn serialize_u64(self, v: u64) -> Result<()> { + self.add_value(v) + } + + fn serialize_i8(self, v: i8) -> Result<()> { + self.add_value(v) + } + + fn serialize_i16(self, v: i16) -> Result<()> { + self.add_value(v) + } + + fn serialize_i32(self, v: i32) -> Result<()> { + self.add_value(v) + } + + fn serialize_i64(self, v: i64) -> Result<()> { + self.add_value(v) + } + + fn serialize_f32(self, v: f32) -> Result<()> { + self.add_value(v) + } + + fn serialize_f64(self, v: f64) -> Result<()> { + self.add_value(v) + } + + fn serialize_str(self, v: &str) -> Result<()> { + try!(self.add_value(0 as u64)); + self.add_raw(v.len() as u64) + } + + fn serialize_char(self, c: char) -> Result<()> { + self.add_raw(encode_utf8(c).as_slice().len() as u64) + } + + fn serialize_bytes(self, v: &[u8]) -> Result<()> { + try!(self.add_value(0 as u64)); + self.add_raw(v.len() as u64) + } + + fn serialize_none(self) -> Result<()> { + self.add_value(0 as u8) + } + + 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(self, len: Option<usize>) -> Result<Self::SerializeSeq> { + let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength)); + + try!(self.serialize_u64(len as u64)); + Ok(SizeCompound {ser: self}) + } + + fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { + Ok(SizeCompound {ser: self}) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { + Ok(SizeCompound {ser: self}) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + _len: usize) -> Result<Self::SerializeTupleVariant> + { + try!(self.add_value(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: u32, + _variant: &'static str, + _len: usize) -> Result<Self::SerializeStructVariant> + { + try!(self.add_value(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: u32, + _variant: &'static str) -> Result<()> { + self.add_value(variant_index) + } + + fn serialize_newtype_variant<V: serde::Serialize + ?Sized>(self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + value: &V) -> Result<()> + { + try!(self.add_value(variant_index)); + value.serialize(self) + } +} + +#[doc(hidden)] +pub struct Compound<'a, W: 'a, E: ByteOrder + 'a> { + ser: &'a mut Serializer<W, E>, +} + +impl<'a, W, E> serde::ser::SerializeSeq for Compound<'a, W, E> + where W: Write, E: ByteOrder +{ + 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, E> serde::ser::SerializeTuple for Compound<'a, W, E> + where W: Write, E: ByteOrder +{ + 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, E> serde::ser::SerializeTupleStruct for Compound<'a, W, E> + where W: Write, E: ByteOrder +{ + 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, E> serde::ser::SerializeTupleVariant for Compound<'a, W, E> + where W: Write, E: ByteOrder +{ + 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, E> serde::ser::SerializeMap for Compound<'a, W, E> + where W: Write, E: ByteOrder +{ + 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, E> serde::ser::SerializeStruct for Compound<'a, W, E> + where W: Write, E: ByteOrder +{ + 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, E> serde::ser::SerializeStructVariant for Compound<'a, W, E> + where W: Write, E: ByteOrder +{ + 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, S: SizeLimit + 'a> { + ser: &'a mut SizeChecker<S>, +} + +impl<'a, S: SizeLimit> serde::ser::SerializeSeq for SizeCompound<'a, S> +{ + 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, S: SizeLimit> serde::ser::SerializeTuple for SizeCompound<'a, S> +{ + 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, S: SizeLimit> serde::ser::SerializeTupleStruct for SizeCompound<'a, S> +{ + 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, S: SizeLimit> serde::ser::SerializeTupleVariant for SizeCompound<'a, S> +{ + 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, S: SizeLimit + 'a> serde::ser::SerializeMap for SizeCompound<'a, S> +{ + 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, S: SizeLimit> serde::ser::SerializeStruct for SizeCompound<'a, S> +{ + 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, S: SizeLimit> serde::ser::SerializeStructVariant for SizeCompound<'a, S> +{ + 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; + +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 } +} + +struct EncodeUtf8 { + buf: [u8; 4], + pos: usize, +} + +impl EncodeUtf8 { + fn as_slice(&self) -> &[u8] { + &self.buf[self.pos..] + } +}
deleted file mode 100644 --- a/third_party/rust/bincode/src/serde/mod.rs +++ /dev/null @@ -1,235 +0,0 @@ -//! 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; -use byteorder::{ByteOrder}; - -pub use self::reader::{ - Deserializer, -}; - -pub use self::writer::{ - Serializer, -}; - -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 `Error` (other than SizeLimit), assume that the -/// writer is in an invalid state, as writing could bail out in the middle of -/// serializing. -pub fn serialize_into<W: ?Sized, T: ?Sized, S, E>(writer: &mut W, value: &T, size_limit: S) -> Result<()> - where W: Write, T: serde::Serialize, S: SizeLimit, E: ByteOrder -{ - if let Some(limit) = size_limit.limit() { - try!(serialized_size_bounded(value, limit).ok_or(ErrorKind::SizeLimit)); - } - - let mut serializer = Serializer::<_, E>::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: ?Sized, S, E>(value: &T, size_limit: S) -> Result<Vec<u8>> - where T: serde::Serialize, S: SizeLimit, E: ByteOrder -{ - // Since we are putting values directly into a vector, we can do size - // computation out here and pre-allocate a buffer of *exactly* - // the right size. - let mut writer = match size_limit.limit() { - Some(size_limit) => { - let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(ErrorKind::SizeLimit)); - Vec::with_capacity(actual_size as usize) - } - None => Vec::new() - }; - - try!(serialize_into::<_, _, _, E>(&mut writer, value, super::Infinite)); - Ok(writer) -} - - -struct CountSize { - total: u64, - limit: Option<u64>, -} - -impl SizeLimit for CountSize { - fn add(&mut self, c: u64) -> Result<()> { - self.total += c; - if let Some(limit) = self.limit { - if self.total > limit { - return Err(Box::new(ErrorKind::SizeLimit)) - } - } - Ok(()) - } - - fn limit(&self) -> Option<u64> { - unreachable!(); - } -} - -/// 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: ?Sized>(value: &T) -> u64 - where T: serde::Serialize -{ - let mut size_counter = SizeChecker { - size_limit: CountSize { total: 0, limit: None } - }; - - value.serialize(&mut size_counter).ok(); - size_counter.size_limit.total -} - -/// 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: ?Sized>(value: &T, max: u64) -> Option<u64> - where T: serde::Serialize -{ - let mut size_counter = SizeChecker { - size_limit: CountSize { total: 0, limit: Some(max) } - }; - - match value.serialize(&mut size_counter) { - Ok(_) => Some(size_counter.size_limit.total), - Err(_) => None, - } -} - -/// 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 `Error`, assume that the buffer that you passed -/// in is in an invalid state, as the error could be returned during any point -/// in the reading. -pub fn deserialize_from<R: ?Sized, T, S, E>(reader: &mut R, size_limit: S) -> Result<T> - where R: Read, T: serde::Deserialize, S: SizeLimit, E: ByteOrder -{ - let mut deserializer = Deserializer::<_, S, E>::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, E: ByteOrder>(bytes: &[u8]) -> Result<T> - where T: serde::Deserialize, -{ - let mut reader = bytes; - deserialize_from::<_, _, _, E>(&mut reader, super::Infinite) -}
deleted file mode 100644 --- a/third_party/rust/bincode/src/serde/reader.rs +++ /dev/null @@ -1,439 +0,0 @@ -use std::cmp; -use std::io::Read; -use std::marker::PhantomData; - -use byteorder::{ReadBytesExt, ByteOrder}; -use serde_crate as serde; -use serde_crate::de::value::ValueDeserializer; -use serde_crate::de::Error as DeError; -use ::SizeLimit; -use super::{Result, Error, ErrorKind}; - -const BLOCK_SIZE: usize = 65536; - -/// 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<R, S: SizeLimit, E: ByteOrder> { - reader: R, - size_limit: S, - read: u64, - _phantom: PhantomData<E>, -} - -impl<R: Read, E: ByteOrder, S: SizeLimit> Deserializer<R, S, E> { - pub fn new(r: R, size_limit: S) -> Deserializer<R, S, E> { - Deserializer { - reader: r, - size_limit: size_limit, - read: 0, - _phantom: PhantomData - } - } - - /// Returns the number of bytes read from the contained Reader. - pub fn bytes_read(&self) -> u64 { - self.read - } - - fn read_bytes(&mut self, count: u64) -> Result<()> { - self.size_limit.add(count) - } - - fn read_type<T>(&mut self) -> Result<()> { - use std::mem::size_of; - self.read_bytes(size_of::<T>() as u64) - } - - fn read_vec(&mut self) -> Result<Vec<u8>> { - let mut len: usize = try!(serde::Deserialize::deserialize(&mut *self)); - - let mut result = Vec::new(); - let mut off = 0; - while len > 0 { - let reserve = cmp::min(len, BLOCK_SIZE); - try!(self.read_bytes(reserve as u64)); - unsafe { - result.reserve(reserve); - result.set_len(off + reserve); - } - try!(self.reader.read_exact(&mut result[off..])); - len -= reserve; - off += reserve; - } - Ok(result) - } - - fn read_string(&mut self) -> Result<String> { - String::from_utf8(try!(self.read_vec())).map_err(|err| - 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>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - try!(self.read_type::<$ty>()); - let value = try!(self.reader.$reader_method::<E>()); - visitor.$visitor_method(value) - } - } -} - -impl<'a, R, S, E> serde::Deserializer for &'a mut Deserializer<R, S, E> -where R: Read, S: SizeLimit, E: ByteOrder { - type Error = Error; - - #[inline] - fn deserialize<V>(self, _visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - let message = "bincode does not support Deserializer::deserialize"; - Err(Error::custom(message)) - } - - fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - let value: u8 = try!(serde::Deserialize::deserialize(self)); - match value { - 1 => visitor.visit_bool(true), - 0 => visitor.visit_bool(false), - value => { - 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>(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_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())) - } - - fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - visitor.visit_unit() - } - - fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - use std::str; - - let error = || { - ErrorKind::InvalidEncoding{ - desc: "Invalid char encoding", - detail: None, - }.into() - }; - - let mut buf = [0u8; 4]; - - // Look at the first byte to see how many bytes must be read - let _ = try!(self.reader.read_exact(&mut buf[..1])); - let width = utf8_char_width(buf[0]); - if width == 1 { return visitor.visit_char(buf[0] as char) } - if width == 0 { return Err(error())} - - if self.reader.read_exact(&mut buf[1..width]).is_err() { - return Err(error()); - } - - let res = try!(str::from_utf8(&buf[..width]).ok().and_then(|s| s.chars().next()).ok_or(error())); - visitor.visit_char(res) - } - - 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>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - visitor.visit_string(try!(self.read_string())) - } - - fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - visitor.visit_bytes(&try!(self.read_vec())) - } - - fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - visitor.visit_byte_buf(try!(self.read_vec())) - } - - fn deserialize_enum<V>(self, - _enum: &'static str, - _variants: &'static [&'static str], - visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - impl<'a, R: 'a, S, E> serde::de::EnumVisitor for &'a mut Deserializer<R, S, E> - where R: Read, S: SizeLimit, E: ByteOrder { - type Error = Error; - type Variant = Self; - - fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)> - where V: serde::de::DeserializeSeed, - { - let idx: u32 = try!(serde::de::Deserialize::deserialize(&mut *self)); - let val: Result<_> = seed.deserialize(idx.into_deserializer()); - Ok((try!(val), self)) - } - } - - visitor.visit_enum(self) - } - - fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - struct TupleVisitor<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a>(&'a mut Deserializer<R, S, E>); - - impl<'a, 'b: 'a, R: Read + 'b, S: SizeLimit, E: ByteOrder> serde::de::SeqVisitor for TupleVisitor<'a, R, S, E> { - type Error = Error; - - fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> - where T: serde::de::DeserializeSeed, - { - let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.0)); - Ok(Some(value)) - } - } - - visitor.visit_seq(TupleVisitor(self)) - } - - fn deserialize_seq_fixed_size<V>(self, - len: usize, - visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - struct SeqVisitor<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> { - deserializer: &'a mut Deserializer<R, S, E>, - len: usize, - } - - impl<'a, 'b: 'a, R: Read + 'b, S: SizeLimit, E: ByteOrder> serde::de::SeqVisitor for SeqVisitor<'a, R, S, E> { - type Error = Error; - - 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::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)); - Ok(Some(value)) - } else { - Ok(None) - } - } - } - - visitor.visit_seq(SeqVisitor { deserializer: self, len: len }) - } - - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - 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, S: SizeLimit + 'a, E: ByteOrder + 'a> { - deserializer: &'a mut Deserializer<R, S, E>, - len: usize, - } - - impl<'a, 'b: 'a, R: Read + 'b, S: SizeLimit, E: ByteOrder> serde::de::MapVisitor for MapVisitor<'a, R, S, E> { - type Error = Error; - - 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::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)); - Ok(Some(key)) - } else { - Ok(None) - } - } - - fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value> - where V: serde::de::DeserializeSeed, - { - let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)); - Ok(value) - } - } - - let len = try!(serde::Deserialize::deserialize(&mut *self)); - - visitor.visit_map(MapVisitor { deserializer: self, len: len }) - } - - fn deserialize_struct<V>(self, - _name: &str, - fields: &'static [&'static str], - visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - self.deserialize_tuple(fields.len(), visitor) - } - - 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(Error::custom(message)) - } - - fn deserialize_newtype_struct<V>(self, - _name: &str, - visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - visitor.visit_newtype_struct(self) - } - - fn deserialize_unit_struct<V>(self, - _name: &'static str, - visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - visitor.visit_unit() - } - - fn deserialize_tuple_struct<V>(self, - _name: &'static str, - len: usize, - visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - self.deserialize_tuple(len, visitor) - } - - 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(Error::custom(message)) - } -} - -impl<'a, R, S, E> serde::de::VariantVisitor for &'a mut Deserializer<R, S, E> -where R: Read, S: SizeLimit, E: ByteOrder { - type Error = Error; - - fn visit_unit(self) -> Result<()> { - Ok(()) - } - - fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value> - where T: serde::de::DeserializeSeed, - { - serde::de::DeserializeSeed::deserialize(seed, self) - } - - fn visit_tuple<V>(self, - len: usize, - visitor: V) -> Result<V::Value> - where V: serde::de::Visitor, - { - serde::de::Deserializer::deserialize_tuple(self, len, visitor) - } - - fn visit_struct<V>(self, - fields: &'static [&'static str], - 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 -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/serde/writer.rs +++ /dev/null @@ -1,707 +0,0 @@ -use std::io::Write; -use std::u32; -use std::marker::PhantomData; - -use serde_crate as serde; - -use byteorder::{WriteBytesExt, ByteOrder}; - -use super::{Result, Error, ErrorKind}; -use super::super::SizeLimit; - -/// 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<W, E: ByteOrder> { - writer: W, - _phantom: PhantomData<E>, -} - -impl<W: Write, E: ByteOrder> Serializer<W, E> { - pub fn new(w: W) -> Serializer<W, E> { - Serializer { - writer: w, - _phantom: PhantomData, - } - } - - fn add_enum_tag(&mut self, tag: usize) -> Result<()> { - if tag > u32::MAX as usize { - panic!("Variant tag doesn't fit in a u32") - } - - serde::Serializer::serialize_u32(self, tag as u32) - } -} - -impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E> { - type Ok = (); - type Error = Error; - type SerializeSeq = Compound<'a, W, E>; - type SerializeTuple = Compound<'a, W, E>; - type SerializeTupleStruct = Compound<'a, W, E>; - type SerializeTupleVariant = Compound<'a, W, E>; - type SerializeMap = Compound<'a, W, E>; - type SerializeStruct = Compound<'a, W, E>; - type SerializeStructVariant = Compound<'a, W, E>; - - fn serialize_unit(self) -> Result<()> { Ok(()) } - - fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) } - - fn serialize_bool(self, v: bool) -> Result<()> { - self.writer.write_u8(if v {1} else {0}).map_err(Into::into) - } - - fn serialize_u8(self, v: u8) -> Result<()> { - self.writer.write_u8(v).map_err(Into::into) - } - - fn serialize_u16(self, v: u16) -> Result<()> { - self.writer.write_u16::<E>(v).map_err(Into::into) - } - - fn serialize_u32(self, v: u32) -> Result<()> { - self.writer.write_u32::<E>(v).map_err(Into::into) - } - - fn serialize_u64(self, v: u64) -> Result<()> { - self.writer.write_u64::<E>(v).map_err(Into::into) - } - - fn serialize_i8(self, v: i8) -> Result<()> { - self.writer.write_i8(v).map_err(Into::into) - } - - fn serialize_i16(self, v: i16) -> Result<()> { - self.writer.write_i16::<E>(v).map_err(Into::into) - } - - fn serialize_i32(self, v: i32) -> Result<()> { - self.writer.write_i32::<E>(v).map_err(Into::into) - } - - fn serialize_i64(self, v: i64) -> Result<()> { - self.writer.write_i64::<E>(v).map_err(Into::into) - } - - fn serialize_f32(self, v: f32) -> Result<()> { - self.writer.write_f32::<E>(v).map_err(Into::into) - } - - fn serialize_f64(self, v: f64) -> Result<()> { - self.writer.write_f64::<E>(v).map_err(Into::into) - } - - 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_char(self, c: char) -> Result<()> { - self.writer.write_all(encode_utf8(c).as_slice()).map_err(Into::into) - } - - 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(self) -> Result<()> { - self.writer.write_u8(0).map_err(Into::into) - } - - fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()> - where T: serde::Serialize, - { - try!(self.writer.write_u8(1)); - v.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_fixed_size(self, _len: usize) -> Result<Self::SerializeSeq> { - Ok(Compound {ser: self}) - } - - fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { - Ok(Compound {ser: self}) - } - - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { - Ok(Compound {ser: self}) - } - - fn serialize_tuple_variant(self, - _name: &'static str, - variant_index: usize, - _variant: &'static str, - _len: usize) -> Result<Self::SerializeTupleVariant> - { - try!(self.add_enum_tag(variant_index)); - Ok(Compound {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(Compound {ser: self}) - } - - fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { - Ok(Compound {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(Compound {ser: self}) - } - - fn serialize_newtype_struct<T: ?Sized>(self, - _name: &'static str, - value: &T) -> Result<()> - where T: serde::ser::Serialize, - { - value.serialize(self) - } - - fn serialize_newtype_variant<T: ?Sized>(self, - _name: &'static str, - variant_index: usize, - _variant: &'static str, - value: &T) -> Result<()> - where T: serde::ser::Serialize, - { - try!(self.add_enum_tag(variant_index)); - value.serialize(self) - } - - fn serialize_unit_variant(self, - _name: &'static str, - variant_index: usize, - _variant: &'static str) -> Result<()> { - self.add_enum_tag(variant_index) - } -} - -pub struct SizeChecker<S: SizeLimit> { - pub size_limit: S, -} - -impl <S: SizeLimit> SizeChecker<S> { - pub fn new(size_limit: S) -> SizeChecker<S> { - SizeChecker { - size_limit: size_limit - } - } - - fn add_raw(&mut self, size: u64) -> Result<()> { - self.size_limit.add(size) - } - - fn add_value<T>(&mut self, t: T) -> Result<()> { - use std::mem::size_of_val; - self.add_raw(size_of_val(&t) as u64) - } - - fn add_enum_tag(&mut self, tag: usize) -> Result<()> { - if tag > u32::MAX as usize { - panic!("Variant tag doesn't fit in a u32") - } - - self.add_value(tag as u32) - } -} - -impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> { - type Ok = (); - type Error = Error; - type SerializeSeq = SizeCompound<'a, S>; - type SerializeTuple = SizeCompound<'a, S>; - type SerializeTupleStruct = SizeCompound<'a, S>; - type SerializeTupleVariant = SizeCompound<'a, S>; - type SerializeMap = SizeCompound<'a, S>; - type SerializeStruct = SizeCompound<'a, S>; - type SerializeStructVariant = SizeCompound<'a, S>; - - fn serialize_unit(self) -> Result<()> { Ok(()) } - - fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) } - - fn serialize_bool(self, _: bool) -> Result<()> { - self.add_value(0 as u8) - } - - fn serialize_u8(self, v: u8) -> Result<()> { - self.add_value(v) - } - - fn serialize_u16(self, v: u16) -> Result<()> { - self.add_value(v) - } - - fn serialize_u32(self, v: u32) -> Result<()> { - self.add_value(v) - } - - fn serialize_u64(self, v: u64) -> Result<()> { - self.add_value(v) - } - - fn serialize_i8(self, v: i8) -> Result<()> { - self.add_value(v) - } - - fn serialize_i16(self, v: i16) -> Result<()> { - self.add_value(v) - } - - fn serialize_i32(self, v: i32) -> Result<()> { - self.add_value(v) - } - - fn serialize_i64(self, v: i64) -> Result<()> { - self.add_value(v) - } - - fn serialize_f32(self, v: f32) -> Result<()> { - self.add_value(v) - } - - fn serialize_f64(self, v: f64) -> Result<()> { - self.add_value(v) - } - - fn serialize_str(self, v: &str) -> Result<()> { - try!(self.add_value(0 as u64)); - self.add_raw(v.len() as u64) - } - - fn serialize_char(self, c: char) -> Result<()> { - self.add_raw(encode_utf8(c).as_slice().len() as u64) - } - - fn serialize_bytes(self, v: &[u8]) -> Result<()> { - try!(self.add_value(0 as u64)); - self.add_raw(v.len() as u64) - } - - fn serialize_none(self) -> Result<()> { - self.add_value(0 as u8) - } - - 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(self, len: Option<usize>) -> Result<Self::SerializeSeq> { - let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength)); - - try!(self.serialize_u64(len as u64)); - Ok(SizeCompound {ser: self}) - } - - fn serialize_seq_fixed_size(self, _len: usize) -> Result<Self::SerializeSeq> { - Ok(SizeCompound {ser: self}) - } - - fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { - Ok(SizeCompound {ser: self}) - } - - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> { - Ok(SizeCompound {ser: self}) - } - - fn serialize_tuple_variant(self, - _name: &'static str, - variant_index: usize, - _variant: &'static str, - _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_newtype_variant<V: serde::Serialize + ?Sized>(self, - _name: &'static str, - variant_index: usize, - _variant: &'static str, - value: &V) -> Result<()> - { - try!(self.add_enum_tag(variant_index)); - value.serialize(self) - } -} - -#[doc(hidden)] -pub struct Compound<'a, W: 'a, E: ByteOrder + 'a> { - ser: &'a mut Serializer<W, E>, -} - -impl<'a, W, E> serde::ser::SerializeSeq for Compound<'a, W, E> - where W: Write, E: ByteOrder -{ - 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, E> serde::ser::SerializeTuple for Compound<'a, W, E> - where W: Write, E: ByteOrder -{ - 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, E> serde::ser::SerializeTupleStruct for Compound<'a, W, E> - where W: Write, E: ByteOrder -{ - 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, E> serde::ser::SerializeTupleVariant for Compound<'a, W, E> - where W: Write, E: ByteOrder -{ - 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, E> serde::ser::SerializeMap for Compound<'a, W, E> - where W: Write, E: ByteOrder -{ - 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, E> serde::ser::SerializeStruct for Compound<'a, W, E> - where W: Write, E: ByteOrder -{ - 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, E> serde::ser::SerializeStructVariant for Compound<'a, W, E> - where W: Write, E: ByteOrder -{ - 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, S: SizeLimit + 'a> { - ser: &'a mut SizeChecker<S>, -} - -impl<'a, S: SizeLimit> serde::ser::SerializeSeq for SizeCompound<'a, S> -{ - 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, S: SizeLimit> serde::ser::SerializeTuple for SizeCompound<'a, S> -{ - 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, S: SizeLimit> serde::ser::SerializeTupleStruct for SizeCompound<'a, S> -{ - 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, S: SizeLimit> serde::ser::SerializeTupleVariant for SizeCompound<'a, S> -{ - 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, S: SizeLimit + 'a> serde::ser::SerializeMap for SizeCompound<'a, S> -{ - 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, S: SizeLimit> serde::ser::SerializeStruct for SizeCompound<'a, S> -{ - 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, S: SizeLimit> serde::ser::SerializeStructVariant for SizeCompound<'a, S> -{ - 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; - -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 } -} - -struct EncodeUtf8 { - buf: [u8; 4], - pos: usize, -} - -impl EncodeUtf8 { - fn as_slice(&self) -> &[u8] { - &self.buf[self.pos..] - } -}
--- a/third_party/rust/bincode/tests/test.rs +++ b/third_party/rust/bincode/tests/test.rs @@ -1,64 +1,49 @@ #[macro_use] extern crate serde_derive; extern crate bincode; extern crate serde; +extern crate serde_bytes; extern crate byteorder; use std::fmt::Debug; use std::collections::HashMap; -use std::ops::Deref; - -use bincode::refbox::{RefBox, StrBox, SliceBox}; +use std::borrow::Cow; use bincode::{Infinite, Bounded}; use bincode::{serialized_size, ErrorKind, Result}; -use bincode::endian_choice::{serialize, deserialize}; +use bincode::internal::{serialize, deserialize, deserialize_from}; use bincode::serialize as serialize_little; use bincode::deserialize as deserialize_little; use bincode::deserialize_from as deserialize_from_little; fn the_same<V>(element: V) - where V: serde::Serialize+serde::Deserialize+PartialEq+Debug+'static + where V: serde::Serialize+serde::de::DeserializeOwned+PartialEq+Debug+'static { - // Make sure that the bahavior isize correct when wrapping with a RefBox. - fn ref_box_correct<V>(v: &V) -> bool - where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static - { - let rf = RefBox::new(v); - let encoded = serialize_little(&rf, Infinite).unwrap(); - let decoded: RefBox<'static, V> = deserialize_little(&encoded[..]).unwrap(); + let size = serialized_size(&element); - decoded.take().deref() == v - } - - let size = serialized_size(&element); { - let encoded = serialize_little(&element, Infinite); - let encoded = encoded.unwrap(); - let decoded = deserialize_little(&encoded[..]); - let decoded = decoded.unwrap(); + let encoded = serialize_little(&element, Infinite).unwrap(); + let decoded = deserialize_little(&encoded[..]).unwrap(); assert_eq!(element, decoded); assert_eq!(size, encoded.len() as u64); - assert!(ref_box_correct(&element)); } { - let encoded = serialize::<_, _, byteorder::BigEndian>(&element, Infinite); - let encoded = encoded.unwrap(); - let decoded = deserialize::<_, byteorder::BigEndian>(&encoded[..]); - let decoded = decoded.unwrap(); + let encoded = serialize::<_, _, byteorder::BigEndian>(&element, Infinite).unwrap(); + let decoded = deserialize::<_, byteorder::BigEndian>(&encoded[..]).unwrap(); + let decoded_reader = deserialize_from::<_, _, _, byteorder::BigEndian>(&mut &encoded[..], Infinite).unwrap(); assert_eq!(element, decoded); + assert_eq!(element, decoded_reader); assert_eq!(size, encoded.len() as u64); - assert!(ref_box_correct(&element)); } } #[test] fn test_numbers() { // unsigned positive the_same(5u8); the_same(5u16); @@ -299,110 +284,136 @@ fn test_serialized_size() { } #[test] fn encode_box() { the_same(Box::new(5)); } #[test] -fn test_refbox_serialize() { +fn test_cow_serialize() { let large_object = vec![1u32,2,3,4,5,6]; let mut large_map = HashMap::new(); large_map.insert(1, 2); #[derive(Serialize, Deserialize, Debug)] enum Message<'a> { - M1(RefBox<'a, Vec<u32>>), - M2(RefBox<'a, HashMap<u32, u32>>) + M1(Cow<'a, Vec<u32>>), + M2(Cow<'a, HashMap<u32, u32>>) } // Test 1 { - let serialized = serialize_little(&Message::M1(RefBox::new(&large_object)), Infinite).unwrap(); + let serialized = serialize_little(&Message::M1(Cow::Borrowed(&large_object)), Infinite).unwrap(); let deserialized: Message<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap(); match deserialized { - Message::M1(b) => assert!(b.take().deref() == &large_object), + Message::M1(b) => assert!(&b.into_owned() == &large_object), _ => assert!(false) } } // Test 2 { - let serialized = serialize_little(&Message::M2(RefBox::new(&large_map)), Infinite).unwrap(); + let serialized = serialize_little(&Message::M2(Cow::Borrowed(&large_map)), Infinite).unwrap(); let deserialized: Message<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap(); match deserialized { - Message::M2(b) => assert!(b.take().deref() == &large_map), + Message::M2(b) => assert!(&b.into_owned() == &large_map), _ => assert!(false) } } } #[test] fn test_strbox_serialize() { let strx: &'static str = "hello world"; - let serialized = serialize_little(&StrBox::new(strx), Infinite).unwrap(); - let deserialized: StrBox<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap(); - let stringx: String = deserialized.take(); + let serialized = serialize_little(&Cow::Borrowed(strx), Infinite).unwrap(); + let deserialized: Cow<'static, String> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap(); + let stringx: String = deserialized.into_owned(); assert!(strx == &stringx[..]); } #[test] fn test_slicebox_serialize() { let slice = [1u32, 2, 3 ,4, 5]; - let serialized = serialize_little(&SliceBox::new(&slice), Infinite).unwrap(); - let deserialized: SliceBox<'static, u32> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap(); + let serialized = serialize_little(&Cow::Borrowed(&slice[..]), Infinite).unwrap(); + println!("{:?}", serialized); + let deserialized: Cow<'static, Vec<u32>> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap(); { let sb: &[u32] = &deserialized; assert!(slice == sb); } - let vecx: Vec<u32> = deserialized.take(); + let vecx: Vec<u32> = deserialized.into_owned(); assert!(slice == &vecx[..]); } #[test] fn test_multi_strings_serialize() { assert!(serialize_little(&("foo", "bar", "baz"), Infinite).is_ok()); } -/* #[test] fn test_oom_protection() { use std::io::Cursor; + #[derive(Serialize, Deserialize, PartialEq, Debug)] struct FakeVec { len: u64, byte: u8 } - let x = bincode::rustc_serialize::encode(&FakeVec { len: 0xffffffffffffffffu64, byte: 1 }, bincode::SizeLimit::Bounded(10)).unwrap(); - let y : Result<Vec<u8>, _> = bincode::rustc_serialize::decode_from(&mut Cursor::new(&x[..]), bincode::SizeLimit::Bounded(10)); + let x = serialize_little(&FakeVec { len: 0xffffffffffffffffu64, byte: 1 }, Bounded(10)).unwrap(); + let y: Result<Vec<u8>> = deserialize_from_little(&mut Cursor::new(&x[..]), Bounded(10)); assert!(y.is_err()); -}*/ +} #[test] fn path_buf() { use std::path::{Path, PathBuf}; let path = Path::new("foo").to_path_buf(); let serde_encoded = serialize_little(&path, Infinite).unwrap(); let decoded: PathBuf = deserialize_little(&serde_encoded).unwrap(); assert!(path.to_str() == decoded.to_str()); } #[test] fn bytes() { - use serde::bytes::Bytes; + use serde_bytes::Bytes; let data = b"abc\0123"; - let s = serialize_little(&data, Infinite).unwrap(); + let s = serialize_little(&data[..], Infinite).unwrap(); let s2 = serialize_little(&Bytes::new(data), Infinite).unwrap(); - assert_eq!(s[..], s2[8..]); + assert_eq!(s[..], s2[..]); +} + +#[test] +fn serde_bytes() { + use serde_bytes::ByteBuf; + the_same(ByteBuf::from(vec![1,2,3,4,5])); } #[test] fn endian_difference() { let x = 10u64; let little = serialize_little(&x, Infinite).unwrap(); let big = serialize::<_, _, byteorder::BigEndian>(&x, Infinite).unwrap(); assert_ne!(little, big); } + +#[test] +fn test_zero_copy_parse() { + #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)] + struct Foo<'a> { + borrowed_str: &'a str, + borrowed_bytes: &'a [u8], + } + + let f = Foo { + borrowed_str: "hi", + borrowed_bytes: &[0, 1, 2, 3], + }; + { + let encoded = serialize_little(&f, Infinite).unwrap(); + let out: Foo = deserialize_little(&encoded[..]).unwrap(); + assert_eq!(out, f); + } +}
--- 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":"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 +{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"b71b9a6f84b9263b2b89be6ec90dff5920ee68cf9e5768d73ed71957de2d0670","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"5b53cadf8fadf693d9d96d43d135a9fe0f3a3eea0742971e4cba9400fb4d6981","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"4a45abeb1e684e30bb361dfa7db59189423348e18d310cbae694b7c8c57cd86a","src/base.rs":"3f3d5d69bd79b146cc3c0402de6260f7531c04e6a44b080f4ec7c8cedebd1337","src/color_space.rs":"7d447e774e85cc33de574637a93c9a8550b681c8d4b94e99f95261ea9740e288","src/context.rs":"6ca07886ad2c3c488f440b95cbffc4cefce212625799e9f1bb9f83f2b9985538","src/data_provider.rs":"b20cbff65a960409abfc1e3eb8145db892c6f9f0294805e5425a4186b88d32c3","src/display.rs":"b63f3a6d5971ad216edf8e961dcd201b84b4028d6bc3eebcfc6371300d841629","src/event.rs":"8b188320702836bd1d6fe18db0deb4415755c5a10e2c44afa691fec02f1e3ce2","src/event_source.rs":"6d1c1378dab8988c46dd3bf20639913716418980b9b490a37a0d5120c60ad580","src/font.rs":"a763205dbab72498a60e62ca7e63fc23bcb05cce0bfe5eacb1189a5783f18314","src/geometry.rs":"d452bbfe443d26b80a54ae8dc9eccb68fd03e35f846eba37618ee0c295af122d","src/image.rs":"08a61e703577bcebe5102e3382a777b319b0e9b063dfefb00982094e56525011","src/lib.rs":"62efb6fccbc8a26ea855cb509e649d83b92573941ce7ef4b9a90b2be926a0b91","src/private.rs":"87c96ed2002bd567bf02535b4c6e8e3f22827afb2dd92ee17d91cfb45bc6072c"},"package":"a9f841e9637adec70838c537cae52cb4c751cc6514ad05669b51d107c2021c79"} \ 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.7.0" +version = "0.8.1" authors = ["The Servo Project Developers"] license = "MIT / Apache-2.0" [features] default = [] elcapitan = [] [dependencies] libc = "0.2" core-foundation = "0.3" -serde = "0.9" +bitflags = "0.8"
--- a/third_party/rust/core-graphics/src/context.rs +++ b/third_party/rust/core-graphics/src/context.rs @@ -5,21 +5,22 @@ // 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 base::CGFloat; use color_space::{CGColorSpace, CGColorSpaceRef}; use core_foundation::base::{CFRelease, CFRetain, CFTypeID, CFTypeRef, TCFType}; -use libc::{c_void, size_t}; +use libc::{c_void, c_int, size_t}; use std::mem; use std::ptr; use std::slice; use geometry::CGRect; +use image::{CGImage, CGImageRef}; #[repr(C)] pub enum CGTextDrawingMode { CGTextFill, CGTextStroke, CGTextFillStroke, CGTextInvisible, CGTextFillClip, @@ -82,25 +83,26 @@ impl TCFType<CGContextRef> for CGContext fn type_id() -> CFTypeID { unsafe { CGContextGetTypeID() } } } impl CGContext { - pub fn create_bitmap_context(width: size_t, + pub fn create_bitmap_context(data: Option<*mut c_void>, + width: size_t, height: size_t, bits_per_component: size_t, bytes_per_row: size_t, space: &CGColorSpace, bitmap_info: u32) -> CGContext { unsafe { - let result = CGBitmapContextCreate(ptr::null_mut(), + let result = CGBitmapContextCreate(data.unwrap_or(ptr::null_mut()), width, height, bits_per_component, bytes_per_row, space.as_concrete_TypeRef(), bitmap_info); TCFType::wrap_under_create_rule(result) } @@ -139,16 +141,22 @@ impl CGContext { } pub fn set_allows_font_smoothing(&self, allows_font_smoothing: bool) { unsafe { CGContextSetAllowsFontSmoothing(self.as_concrete_TypeRef(), allows_font_smoothing) } } + pub fn set_font_smoothing_style(&self, style: i32) { + unsafe { + CGContextSetFontSmoothingStyle(self.as_concrete_TypeRef(), style as _); + } + } + pub fn set_should_smooth_fonts(&self, should_smooth_fonts: bool) { unsafe { CGContextSetShouldSmoothFonts(self.as_concrete_TypeRef(), should_smooth_fonts) } } pub fn set_allows_antialiasing(&self, allows_antialiasing: bool) { unsafe { @@ -192,35 +200,52 @@ impl CGContext { } } pub fn fill_rect(&self, rect: CGRect) { unsafe { CGContextFillRect(self.as_concrete_TypeRef(), rect) } } + + pub fn draw_image(&self, rect: CGRect, image: &CGImage) { + unsafe { + CGContextDrawImage(self.as_concrete_TypeRef(), rect, image.as_concrete_TypeRef()); + } + } + + pub fn create_image(&self) -> Option<CGImage> { + let image = unsafe { CGBitmapContextCreateImage(self.as_concrete_TypeRef()) }; + if image != ptr::null() { + Some(unsafe { CGImage::wrap_under_create_rule(image) }) + } else { + None + } + } } #[link(name = "ApplicationServices", kind = "framework")] extern { fn CGBitmapContextCreate(data: *mut c_void, width: size_t, height: size_t, bitsPerComponent: size_t, bytesPerRow: size_t, space: CGColorSpaceRef, bitmapInfo: u32) -> CGContextRef; fn CGBitmapContextGetData(context: CGContextRef) -> *mut c_void; fn CGBitmapContextGetWidth(context: CGContextRef) -> size_t; fn CGBitmapContextGetHeight(context: CGContextRef) -> size_t; fn CGBitmapContextGetBytesPerRow(context: CGContextRef) -> size_t; + fn CGBitmapContextCreateImage(context: CGContextRef) -> CGImageRef; fn CGContextGetTypeID() -> CFTypeID; fn CGContextSetAllowsFontSmoothing(c: CGContextRef, allowsFontSmoothing: bool); fn CGContextSetShouldSmoothFonts(c: CGContextRef, shouldSmoothFonts: bool); + fn CGContextSetFontSmoothingStyle(c: CGContextRef, style: c_int); fn CGContextSetAllowsAntialiasing(c: CGContextRef, allowsAntialiasing: bool); fn CGContextSetShouldAntialias(c: CGContextRef, shouldAntialias: bool); fn CGContextSetAllowsFontSubpixelQuantization(c: CGContextRef, allowsFontSubpixelQuantization: bool); fn CGContextSetShouldSubpixelQuantizeFonts(c: CGContextRef, shouldSubpixelQuantizeFonts: bool); fn CGContextSetAllowsFontSubpixelPositioning(c: CGContextRef, allowsFontSubpixelPositioning: bool); @@ -229,10 +254,11 @@ extern { fn CGContextSetTextDrawingMode(c: CGContextRef, mode: CGTextDrawingMode); fn CGContextSetRGBFillColor(context: CGContextRef, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat); fn CGContextFillRect(context: CGContextRef, rect: CGRect); + fn CGContextDrawImage(c: CGContextRef, rect: CGRect, image: CGImageRef); }
--- a/third_party/rust/core-graphics/src/data_provider.rs +++ b/third_party/rust/core-graphics/src/data_provider.rs @@ -3,32 +3,33 @@ // // 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 core_foundation::base::{CFRelease, CFRetain, CFTypeID, CFTypeRef, TCFType}; +use core_foundation::data::{CFData, CFDataRef}; -use libc::{c_void, size_t}; +use libc::{c_void, size_t, off_t}; use std::mem; use std::ptr; -pub type CGDataProviderGetBytesCallback = *const u8; -pub type CGDataProviderReleaseInfoCallback = *const u8; -pub type CGDataProviderRewindCallback = *const u8; -pub type CGDataProviderSkipBytesCallback = *const u8; -pub type CGDataProviderSkipForwardCallback = *const u8; +pub type CGDataProviderGetBytesCallback = Option<unsafe extern fn (*mut c_void, *mut c_void, size_t) -> size_t>; +pub type CGDataProviderReleaseInfoCallback = Option<unsafe extern fn (*mut c_void)>; +pub type CGDataProviderRewindCallback = Option<unsafe extern fn (*mut c_void)>; +pub type CGDataProviderSkipBytesCallback = Option<unsafe extern fn (*mut c_void, size_t)>; +pub type CGDataProviderSkipForwardCallback = Option<unsafe extern fn (*mut c_void, off_t) -> off_t>; -pub type CGDataProviderGetBytePointerCallback = *const u8; -pub type CGDataProviderGetBytesAtOffsetCallback = *const u8; -pub type CGDataProviderReleaseBytePointerCallback = *const u8; -pub type CGDataProviderReleaseDataCallback = *const u8; -pub type CGDataProviderGetBytesAtPositionCallback = *const u8; +pub type CGDataProviderGetBytePointerCallback = Option<unsafe extern fn (*mut c_void) -> *mut c_void>; +pub type CGDataProviderGetBytesAtOffsetCallback = Option<unsafe extern fn (*mut c_void, *mut c_void, size_t, size_t)>; +pub type CGDataProviderReleaseBytePointerCallback = Option<unsafe extern fn (*mut c_void, *const c_void)>; +pub type CGDataProviderReleaseDataCallback = Option<unsafe extern fn (*mut c_void, *const c_void, size_t)>; +pub type CGDataProviderGetBytesAtPositionCallback = Option<unsafe extern fn (*mut c_void, *mut c_void, off_t, size_t)>; #[repr(C)] pub struct __CGDataProvider; pub type CGDataProviderRef = *const __CGDataProvider; pub struct CGDataProvider { obj: CGDataProviderRef, @@ -77,25 +78,30 @@ impl TCFType<CGDataProviderRef> for CGDa } impl CGDataProvider { pub fn from_buffer(buffer: &[u8]) -> CGDataProvider { unsafe { let result = CGDataProviderCreateWithData(ptr::null_mut(), buffer.as_ptr() as *const c_void, buffer.len() as size_t, - ptr::null()); + None); TCFType::wrap_under_create_rule(result) } } + + /// Creates a copy of the data from the underlying `CFDataProviderRef`. + pub fn copy_data(&self) -> CFData { + unsafe { CFData::wrap_under_create_rule(CGDataProviderCopyData(self.obj)) } + } } #[link(name = "ApplicationServices", kind = "framework")] extern { - //fn CGDataProviderCopyData + fn CGDataProviderCopyData(provider: CGDataProviderRef) -> CFDataRef; //fn CGDataProviderCreateDirect //fn CGDataProviderCreateSequential //fn CGDataProviderCreateWithCFData fn CGDataProviderCreateWithData(info: *mut c_void, data: *const c_void, size: size_t, releaseData: CGDataProviderReleaseDataCallback ) -> CGDataProviderRef;
--- a/third_party/rust/core-graphics/src/display.rs +++ b/third_party/rust/core-graphics/src/display.rs @@ -10,39 +10,52 @@ #![allow(non_upper_case_globals)] extern crate core_foundation; use libc; pub use base::{CGError, boolean_t}; pub use geometry::{CGRect, CGPoint, CGSize}; +use image::CGImageRef; + pub type CGDirectDisplayID = libc::uint32_t; pub type CGWindowID = libc::uint32_t; pub const kCGNullWindowID: CGWindowID = 0 as CGWindowID; pub type CGWindowListOption = libc::uint32_t; pub const kCGWindowListOptionAll: CGWindowListOption = 0; pub const kCGWindowListOptionOnScreenOnly: CGWindowListOption = 1 << 0; pub const kCGWindowListOptionOnScreenAboveWindow: CGWindowListOption = 1 << 1; pub const kCGWindowListOptionOnScreenBelowWindow: CGWindowListOption = 1 << 2; pub const kCGWindowListOptionIncludingWindow: CGWindowListOption = 1 << 3; pub const kCGWindowListExcludeDesktopElements: CGWindowListOption = 1 << 4; +pub type CGWindowImageOption = libc::uint32_t; + +pub const kCGWindowImageDefault: CGWindowImageOption = 0; +pub const kCGWindowImageBoundsIgnoreFraming: CGWindowImageOption = 1 << 0; +pub const kCGWindowImageShouldBeOpaque: CGWindowImageOption = 1 << 1; +pub const kCGWindowImageOnlyShadows: CGWindowImageOption = 1 << 2; +pub const kCGWindowImageBestResolution: CGWindowImageOption = 1 << 3; +pub const kCGWindowImageNominalResolution: CGWindowImageOption = 1 << 4; pub use core_foundation::dictionary::{ CFDictionary, CFDictionaryRef, CFDictionaryGetValueIfPresent }; pub use core_foundation::array::{ CFArray, CFArrayRef }; pub use core_foundation::array::{ CFArrayGetCount, CFArrayGetValueAtIndex }; pub use core_foundation::base::{ CFIndex, CFRelease, CFTypeRef }; #[link(name = "ApplicationServices", kind = "framework")] extern { + pub static CGRectNull: CGRect; + pub static CGRectInfinite: CGRect; + pub fn CGMainDisplayID() -> CGDirectDisplayID; pub fn CGDisplayIsActive(display: CGDirectDisplayID) -> boolean_t; pub fn CGDisplayIsAlwaysInMirrorSet(display: CGDirectDisplayID) -> boolean_t; pub fn CGDisplayIsAsleep(display: CGDirectDisplayID) -> boolean_t; pub fn CGDisplayIsBuiltin(display: CGDirectDisplayID) -> boolean_t; pub fn CGDisplayIsInHWMirrorSet(display: CGDirectDisplayID) -> boolean_t; pub fn CGDisplayIsInMirrorSet(display: CGDirectDisplayID) -> boolean_t; pub fn CGDisplayIsMain(display: CGDirectDisplayID) -> boolean_t; @@ -68,10 +81,14 @@ extern { pub fn CGDisplayHideCursor(display: CGDirectDisplayID) -> CGError; pub fn CGDisplayShowCursor(display: CGDirectDisplayID) -> CGError; pub fn CGDisplayMoveCursorToPoint(display: CGDirectDisplayID, point: CGPoint) -> CGError; pub fn CGWarpMouseCursorPosition(point: CGPoint) -> CGError; pub fn CGAssociateMouseAndMouseCursorPosition(connected: bool) -> CGError; // Window Services Reference pub fn CGWindowListCopyWindowInfo(option: CGWindowListOption, relativeToWindow: CGWindowID ) -> CFArrayRef; + pub fn CGWindowListCreateImage(screenBounds: CGRect, + listOptions: CGWindowListOption, + windowId: CGWindowID, + imageOptions: CGWindowImageOption) -> CGImageRef; }
--- a/third_party/rust/core-graphics/src/event.rs +++ b/third_party/rust/core-graphics/src/event.rs @@ -6,66 +6,68 @@ use libc; use std::mem; use std::ptr; pub type CGKeyCode = libc::uint16_t; /// Flags for events /// /// [Ref](http://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h) -#[repr(C)] -#[derive(Clone, Copy, Debug)] -pub enum CGEventFlags { - // Device-independent modifier key bits. - AlphaShift = 0x00010000, - Shift = 0x00020000, - Control = 0x00040000, - Alternate = 0x00080000, - Command = 0x00100000, +bitflags! { + pub flags CGEventFlags: u64 { + const CGEventFlagNull = 0, + + // Device-independent modifier key bits. + const CGEventFlagAlphaShift = 0x00010000, + const CGEventFlagShift = 0x00020000, + const CGEventFlagControl = 0x00040000, + const CGEventFlagAlternate = 0x00080000, + const CGEventFlagCommand = 0x00100000, - // Special key identifiers. - Help = 0x00400000, - SecondaryFn = 0x00800000, + // Special key identifiers. + const CGEventFlagHelp = 0x00400000, + const CGEventFlagSecondaryFn = 0x00800000, - // Identifies key events from numeric keypad area on extended keyboards. - NumericPad = 0x00200000, + // Identifies key events from numeric keypad area on extended keyboards. + const CGEventFlagNumericPad = 0x00200000, - // Indicates if mouse/pen movement events are not being coalesced - NonCoalesced = 0x00000100, + // Indicates if mouse/pen movement events are not being coalesced + const CGEventFlagNonCoalesced = 0x00000100, + } } /// Constants that specify the different types of input events. /// /// [Ref](http://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h) #[repr(C)] #[derive(Clone, Copy, Debug)] pub enum CGEventType { - Null = 1 << 0, + Null = 0, // Mouse events. - LeftMouseDown = 1 << 1, - LeftMouseUp = 1 << 2, - RightMouseDown = 1 << 3, - RightMouseUp = 1 << 4, - MouseMoved = 1 << 5, - LeftMouseDragged = 1 << 6, - RightMouseDragged = 1 << 7, + LeftMouseDown = 1, + LeftMouseUp = 2, + RightMouseDown = 3, + RightMouseUp = 4, + MouseMoved = 5, + LeftMouseDragged = 6, + RightMouseDragged = 7, // Keyboard events. - KeyDown = 1 << 10, - KeyUp = 1 << 11, - FlagsChanged = 1 << 12, + KeyDown = 10, + KeyUp = 11, + FlagsChanged = 12, // Specialized control devices. - ScrollWheel = 1 << 22, - TabletPointer = 1 << 23, - TabletProximity = 1 << 24, - OtherMouseDown = 1 << 25, - OtherMouseUp = 1 << 26, - OtherMouseDragged = 1 << 27, + ScrollWheel = 22, + TabletPointer = 23, + TabletProximity = 24, + OtherMouseDown = 25, + OtherMouseUp = 26, + OtherMouseDragged = 27, // Out of band event types. These are delivered to the event tap callback // to notify it of unusual conditions that disable the event tap. TapDisabledByTimeout = 0xFFFFFFFE, TapDisabledByUserInput = 0xFFFFFFFF, } // Constants that specify buttons on a one, two, or three-button mouse. @@ -217,16 +219,40 @@ impl CGEvent { } } pub fn get_flags(&self) -> CGEventFlags { unsafe { CGEventGetFlags(self.as_concrete_TypeRef()) } } + + pub fn set_type(&self, event_type: CGEventType) { + unsafe { + CGEventSetType(self.as_concrete_TypeRef(), event_type); + } + } + + pub fn get_type(&self) -> CGEventType { + unsafe { + CGEventGetType(self.as_concrete_TypeRef()) + } + } + + pub fn set_string_from_utf16_unchecked(&self, buf: &[u16]) { + let buflen = buf.len() as libc::c_ulong; + unsafe { + CGEventKeyboardSetUnicodeString(self.as_concrete_TypeRef(), buflen, buf.as_ptr()); + } + } + + pub fn set_string(&self, string: &str) { + let buf: Vec<u16> = string.encode_utf16().collect(); + self.set_string_from_utf16_unchecked(&buf); + } } #[link(name = "ApplicationServices", kind = "framework")] extern { /// Return the type identifier for the opaque type `CGEventRef'. fn CGEventGetTypeID() -> CFTypeID; /// Return a new event using the event source `source'. If `source' is NULL, @@ -277,9 +303,27 @@ extern { fn CGEventSetFlags(event: CGEventRef, flags: CGEventFlags); /// Return the event flags of an event. fn CGEventGetFlags(event: CGEventRef) -> CGEventFlags; /// Return the location of an event in global display coordinates. /// CGPointZero is returned if event is not a valid CGEventRef. fn CGEventGetLocation(event: CGEventRef) -> CGPoint; + + /// Set the event type of an event. + fn CGEventSetType(event: CGEventRef, eventType: CGEventType); + + /// Return the event type of an event (left mouse down, for example). + fn CGEventGetType(event: CGEventRef) -> CGEventType; + + /// Set the Unicode string associated with a keyboard event. + /// + /// By default, the system translates the virtual key code in a keyboard + /// event into a Unicode string based on the keyboard ID in the event + /// source. This function allows you to manually override this string. + /// Note that application frameworks may ignore the Unicode string in a + /// keyboard event and do their own translation based on the virtual + /// keycode and perceived event state. + fn CGEventKeyboardSetUnicodeString(event: CGEventRef, + length: libc::c_ulong, + string: *const u16); }
--- a/third_party/rust/core-graphics/src/font.rs +++ b/third_party/rust/core-graphics/src/font.rs @@ -7,18 +7,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. use core_foundation::base::{CFRelease, CFRetain, CFTypeID, CFTypeRef, TCFType}; use core_foundation::string::{CFString, CFStringRef}; use data_provider::{CGDataProvider, CGDataProviderRef}; use libc; -use serde::de::{self, Deserialize, Deserializer}; -use serde::ser::{Serialize, Serializer}; use std::mem; use std::ptr; pub type CGGlyph = libc::c_ushort; #[repr(C)] pub struct __CGFont; @@ -26,32 +24,16 @@ 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: S) -> Result<S::Ok, S::Error> where S: Serializer { - let postscript_name = self.postscript_name().to_string(); - postscript_name.serialize(serializer) - } -} - -impl Deserialize for CGFont { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer { - let postscript_name: String = try!(Deserialize::deserialize(deserializer)); - CGFont::from_name(&CFString::new(&*postscript_name)).map_err(|_| { - de::Error::custom("Couldn't find a font with that PostScript name!") - }) - } -} - impl Clone for CGFont { #[inline] fn clone(&self) -> CGFont { unsafe { TCFType::wrap_under_get_rule(self.obj) } } }
--- a/third_party/rust/core-graphics/src/geometry.rs +++ b/third_party/rust/core-graphics/src/geometry.rs @@ -3,16 +3,18 @@ // // 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 base::CGFloat; +use core_foundation::base::TCFType; +use core_foundation::dictionary::CFDictionary; pub const CG_ZERO_POINT: CGPoint = CGPoint { x: 0.0, y: 0.0, }; #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -65,20 +67,36 @@ impl CGRect { } #[inline] pub fn inset(&self, size: &CGSize) -> CGRect { unsafe { ffi::CGRectInset(*self, size.width, size.height) } } + + #[inline] + pub fn from_dict_representation(dict: &CFDictionary) -> Option<CGRect> { + let mut rect = CGRect::new(&CGPoint::new(0., 0.), &CGSize::new(0., 0.)); + let result = unsafe { + ffi::CGRectMakeWithDictionaryRepresentation(dict.as_concrete_TypeRef(), &mut rect) + }; + if result == 0 { + None + } else { + Some(rect) + } + } } mod ffi { - use base::CGFloat; + use base::{CGFloat, boolean_t}; use geometry::CGRect; + use core_foundation::dictionary::CFDictionaryRef; #[link(name = "ApplicationServices", kind = "framework")] extern { pub fn CGRectInset(rect: CGRect, dx: CGFloat, dy: CGFloat) -> CGRect; + pub fn CGRectMakeWithDictionaryRepresentation(dict: CFDictionaryRef, + rect: *mut CGRect) -> boolean_t; } }
new file mode 100644 --- /dev/null +++ b/third_party/rust/core-graphics/src/image.rs @@ -0,0 +1,161 @@ +use core_foundation::base::{CFRetain, CFTypeID, CFTypeRef, TCFType}; +use core_foundation::data::CFData; +use color_space::{CGColorSpace, CGColorSpaceRef}; +use data_provider::{CGDataProvider, CGDataProviderRef}; +use libc::size_t; +use std::ops::Deref; +use std::mem; + +#[repr(C)] +pub enum CGImageAlphaInfo { + CGImageAlphaNone, /* For example, RGB. */ + CGImageAlphaPremultipliedLast, /* For example, premultiplied RGBA */ + CGImageAlphaPremultipliedFirst, /* For example, premultiplied ARGB */ + CGImageAlphaLast, /* For example, non-premultiplied RGBA */ + CGImageAlphaFirst, /* For example, non-premultiplied ARGB */ + CGImageAlphaNoneSkipLast, /* For example, RBGX. */ + CGImageAlphaNoneSkipFirst, /* For example, XRBG. */ + CGImageAlphaOnly /* No color data, alpha data only */ +} + +#[repr(C)] +pub enum CGImageByteOrderInfo { + CGImageByteOrderMask = 0x7000, + CGImageByteOrder16Little = (1 << 12), + CGImageByteOrder32Little = (2 << 12), + CGImageByteOrder16Big = (3 << 12), + CGImageByteOrder32Big = (4 << 12) +} + +#[repr(C)] +pub struct __CGImage; + +pub type CGImageRef = *const __CGImage; + +pub struct CGImage { + obj: CGImageRef, +} + +impl Drop for CGImage { + fn drop(&mut self) { + unsafe { + CGImageRelease(self.as_concrete_TypeRef()) + } + } +} + +impl Clone for CGImage { + fn clone(&self) -> CGImage { + unsafe { + TCFType::wrap_under_get_rule(self.as_concrete_TypeRef()) + } + } +} + +// TODO: Replace all this stuff by simply using: +// impl_TCFType!(CGImage, CGImageRef, CGImageGetTypeID); +impl TCFType<CGImageRef> for CGImage { + #[inline] + fn as_concrete_TypeRef(&self) -> CGImageRef { + self.obj + } + + #[inline] + unsafe fn wrap_under_get_rule(reference: CGImageRef) -> CGImage { + let reference: CGImageRef = mem::transmute(CFRetain(mem::transmute(reference))); + TCFType::wrap_under_create_rule(reference) + } + + #[inline] + fn as_CFTypeRef(&self) -> CFTypeRef { + unsafe { + mem::transmute(self.as_concrete_TypeRef()) + } + } + + #[inline] + unsafe fn wrap_under_create_rule(obj: CGImageRef) -> CGImage { + CGImage { + obj: obj, + } + } + + #[inline] + fn type_id() -> CFTypeID { + unsafe { + CGImageGetTypeID() + } + } +} + +impl CGImage { + pub fn width(&self) -> size_t { + unsafe { + CGImageGetWidth(self.as_concrete_TypeRef()) + } + } + + pub fn height(&self) -> size_t { + unsafe { + CGImageGetHeight(self.as_concrete_TypeRef()) + } + } + + pub fn bits_per_component(&self) -> size_t { + unsafe { + CGImageGetBitsPerComponent(self.as_concrete_TypeRef()) + } + } + + pub fn bits_per_pixel(&self) -> size_t { + unsafe { + CGImageGetBitsPerPixel(self.as_concrete_TypeRef()) + } + } + + pub fn bytes_per_row(&self) -> size_t { + unsafe { + CGImageGetBytesPerRow(self.as_concrete_TypeRef()) + } + } + + pub fn color_space(&self) -> CGColorSpace { + unsafe { + TCFType::wrap_under_get_rule(CGImageGetColorSpace(self.as_concrete_TypeRef())) + } + } + + /// Returns the raw image bytes wrapped in `CFData`. Note, the returned `CFData` owns the + /// underlying buffer. + pub fn data(&self) -> CFData { + let data_provider = unsafe { + CGDataProvider::wrap_under_get_rule(CGImageGetDataProvider(self.as_concrete_TypeRef())) + }; + data_provider.copy_data() + } +} + +impl Deref for CGImage { + type Target = CGImageRef; + + #[inline] + fn deref(&self) -> &CGImageRef { + &self.obj + } +} + +#[link(name = "ApplicationServices", kind = "framework")] +extern { + fn CGImageGetTypeID() -> CFTypeID; + fn CGImageGetWidth(image: CGImageRef) -> size_t; + fn CGImageGetHeight(image: CGImageRef) -> size_t; + fn CGImageGetBitsPerComponent(image: CGImageRef) -> size_t; + fn CGImageGetBitsPerPixel(image: CGImageRef) -> size_t; + fn CGImageGetBytesPerRow(image: CGImageRef) -> size_t; + fn CGImageGetColorSpace(image: CGImageRef) -> CGColorSpaceRef; + fn CGImageGetDataProvider(image: CGImageRef) -> CGDataProviderRef; + fn CGImageRelease(image: CGImageRef); + + //fn CGImageGetAlphaInfo(image: CGImageRef) -> CGImageAlphaInfo; + //fn CGImageCreateCopyWithColorSpace(image: CGImageRef, space: CGColorSpaceRef) -> CGImageRef +}
--- a/third_party/rust/core-graphics/src/lib.rs +++ b/third_party/rust/core-graphics/src/lib.rs @@ -3,21 +3,25 @@ // // 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. extern crate libc; +#[macro_use] extern crate core_foundation; -extern crate serde; + +#[macro_use] +extern crate bitflags; pub mod base; pub mod color_space; pub mod context; pub mod data_provider; pub mod display; pub mod event; -pub mod event_source; +pub mod event_source; pub mod font; pub mod geometry; pub mod private; +pub mod image;
--- 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":"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 +{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"d0114f648b7f61e473b61c6d682fefaa4e3fadf2101aff056e2ffc52e9229d87",".travis.yml":"6aad961651169d31d79c0595624d1777b5c4cbb4cf2bed9a126c7e72d29411fd","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"c29ed6924aff33e32bf93f6e23e953aab825bd55e148069b7f7f01aaba212345","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"0c82015d302c9937e6376debd961350afeaeb6dde228aac95e3a3115c5813613","src/font.rs":"f6ddf0d3d136bd879e343a89df7b7b79ee45a2037b6807ef67eaf074973e5e8e","src/font_collection.rs":"d4ca7f741fd54b4b22b823833dfa1f1ccd78a26cf112119ae992572835e48df6","src/font_descriptor.rs":"42be4c958abef1dc914c2815193862e56a23729fe7df7e1483b1b32330d1b7bb","src/font_manager.rs":"de5e22620528322d6811d01f03975c53b676ec743297590de5e17a45393df0f1","src/lib.rs":"b1fc720a9ab7ae4f054f0767e05ba5640b2d9fc8c34d05ae04f25b9dd44f6b81"},"package":"74ba2a7abdccb94fb6c00822addef48504182b285aa45a30e78286487888fcb4"} \ 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 = "4.0.0" +version = "5.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.7" +core-graphics = "0.8"
--- a/third_party/rust/core-text/src/font.rs +++ b/third_party/rust/core-text/src/font.rs @@ -7,16 +7,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_upper_case_globals)] use font_descriptor::{CTFontDescriptor, CTFontDescriptorRef, CTFontOrientation}; use font_descriptor::{CTFontSymbolicTraits, CTFontTraits, SymbolicTraitAccessors, TraitAccessors}; +use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFIndex, CFOptionFlags, CFTypeID, CFRelease, CFRetain, CFTypeRef, TCFType}; use core_foundation::data::{CFData, CFDataRef}; use core_foundation::dictionary::CFDictionaryRef; use core_foundation::string::{CFString, CFStringRef, UniChar}; use core_foundation::url::{CFURL, CFURLRef}; use core_graphics::base::{CGAffineTransform, CGFloat}; use core_graphics::context::{CGContext, CGContextRef}; use core_graphics::font::{CGGlyph, CGFont, CGFontRef}; @@ -373,16 +374,25 @@ pub fn debug_font_traits(font: &CTFont) println!("kCTFontMonoSpaceTrait: {}", sym.is_monospace()); let traits = font.all_traits(); println!("kCTFontWeightTrait: {}", traits.normalized_weight()); // println!("kCTFontWidthTrait: {}", traits.normalized_width()); // println!("kCTFontSlantTrait: {}", traits.normalized_slant()); } +pub fn cascade_list_for_languages(font: &CTFont, language_pref_list: &CFArray) -> CFArray { + unsafe { + let font_collection_ref = + CTFontCopyDefaultCascadeListForLanguages(font.as_concrete_TypeRef(), + language_pref_list.as_concrete_TypeRef()); + TCFType::wrap_under_create_rule(font_collection_ref) + } +} + #[link(name = "ApplicationServices", kind = "framework")] extern { /* * CTFont.h */ /* Name Specifier Constants */ //static kCTFontCopyrightNameKey: CFStringRef; @@ -448,16 +458,18 @@ extern { /* Getting Font Names */ //fn CTFontCopyPostScriptName(font: CTFontRef) -> CFStringRef; //fn CTFontCopyFamilyName(font: CTFontRef) -> CFStringRef; //fn CTFontCopyFullName(font: CTFontRef) -> CFStringRef; //fn CTFontCopyDisplayName(font: CTFontRef) -> CFStringRef; fn CTFontCopyName(font: CTFontRef, nameKey: CFStringRef) -> CFStringRef; //fn CTFontCopyLocalizedName(font: CTFontRef, nameKey: CFStringRef, // language: *CFStringRef) -> CFStringRef; + fn CTFontCopyDefaultCascadeListForLanguages(font: CTFontRef, languagePrefList: CFArrayRef) -> CFArrayRef; + /* Working With Encoding */ //fn CTFontCopyCharacterSet //fn CTFontGetStringEncoding //fn CTFontCopySupportedLanguages /* Getting Font Metrics */ fn CTFontGetAscent(font: CTFontRef) -> CGFloat;
--- a/third_party/rust/core-text/src/font_descriptor.rs +++ b/third_party/rust/core-text/src/font_descriptor.rs @@ -266,25 +266,27 @@ impl CTFontDescriptor { value.expect("A font must have a non-null style name.") } pub fn display_name(&self) -> String { let value = self.get_string_attribute(kCTFontDisplayNameAttribute); value.expect("A font must have a non-null display name.") } - pub fn font_path(&self) -> String { + pub fn font_path(&self) -> Option<String> { unsafe { let value = CTFontDescriptorCopyAttribute(self.obj, kCTFontURLAttribute); - assert!(!value.is_null()); + if (value.is_null()) { + return None; + } let value: CFType = TCFType::wrap_under_get_rule(value); assert!(value.instance_of::<CFURLRef,CFURL>()); let url: CFURL = TCFType::wrap_under_get_rule(mem::transmute(value.as_CFTypeRef())); - format!("{:?}", url) + Some(format!("{:?}", url)) } } } pub fn new_from_attributes(attributes: &CFDictionary) -> CTFontDescriptor { unsafe { let result: CTFontDescriptorRef = CTFontDescriptorCreateWithAttributes(attributes.as_concrete_TypeRef()); @@ -292,17 +294,17 @@ pub fn new_from_attributes(attributes: & } } pub fn debug_descriptor(desc: &CTFontDescriptor) { println!("family: {}", desc.family_name()); println!("name: {}", desc.font_name()); println!("style: {}", desc.style_name()); println!("display: {}", desc.display_name()); - println!("path: {}", desc.font_path()); + println!("path: {:?}", desc.font_path()); desc.show(); } extern { /* * CTFontTraits.h */
--- a/third_party/rust/dwrote/.cargo-checksum.json +++ b/third_party/rust/dwrote/.cargo-checksum.json @@ -1,1 +1,1 @@ -{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"172610b244a5ee8a8e2f1f045058b8abf9291d84bb76bf8779d2fd420419c2d6","Cargo.toml":"c0894413ac3abce23bb93d1284031b29dd00ef7d2f5fcb8573208e0c33280538","README.md":"d69d75705e2582721cbfb2d3b4b2af052c71679057a0b2ac53a22c03f1755bba","appveyor.yml":"2c7b2468dc69bef84860b8900024cb6e1a1c52f6fe1232e8ccd83caaf7c231ca","src/bitmap_render_target.rs":"d3b229f85a9804ac52976431657727b410e7d5253283df046e46d98c196f0a3a","src/com_helpers.rs":"fccb4b36379ae3454a88aa32a8e5c09e46ef5f5626266dde1fe5f40a992de39c","src/comptr.rs":"218435689f505769686e07cfc5428852dda90b849a0d48e670f632307f5edc7c","src/font.rs":"9bdf3134c6ad3639eab3da4419c9b43aad2673797f6fdc65841da2c82e1f3af4","src/font_collection.rs":"969fa3abf141dc3504774886f4783fda4a74cd5a198c643f8a77fc1af4e75258","src/font_face.rs":"9506ca579345ab2b6b5615fc75f8f431e2bb0dbd93123d1d2a21a73c851a5427","src/font_family.rs":"403da9f8f9903cbe7f9f79636497b273f9885e200f53af99f9d4e483f11d6889","src/font_file.rs":"60ad02fc25765a2c113175ea372e98a2be0d84aa65fef9246b6a0192e63ff708","src/font_file_loader_impl.rs":"0d304ad99ff1e6874510a1498223329d798ff75b417e3db7e823a695003dfe92","src/gdi_interop.rs":"98922996afc5b8c8304cb65e7c965419003825dfa172a3e11fe69bf3d768551c","src/glyph_run_analysis.rs":"d30d8b41b047815ab5770c730b7a6d09939f2347b4a4257b87bebec08a5794fe","src/helpers.rs":"5d6f164468234ca8806dc1cea117b42dbfae80cc4c9ae965cb0556efdb364682","src/lib.rs":"07dae7e9a6b8e2970917eade968490e2af90110047a0e16f539647269b12f439","src/rendering_params.rs":"be1d1c433f76926c285d8ecdb747c5d9cc6a6c10c1a1890c0760cd99755ed471","src/test.rs":"d77e45f8866abeea070cbbafd4cbde62d875292e8d191310a04c70091978547c","src/types.rs":"784235c15d61fb0d001373575169aa473c92af18dcbc1709a5b2bbaa3a7ceb22"},"package":"74114b6b49d6731835da7a28a3642651451e315f7f9b9d04e907e65a45681796"} \ No newline at end of file +{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"172610b244a5ee8a8e2f1f045058b8abf9291d84bb76bf8779d2fd420419c2d6","Cargo.toml":"48059bb4b7efd1a6c2d659fa909888f2c8b5d34f0bd8027b4aefaae9b8d0586e","Cargo.toml.orig":"d5991dc02e8e88abd04b4df1a45c32b26c94b3b903d3fe32404097c012e74ea9","README.md":"d69d75705e2582721cbfb2d3b4b2af052c71679057a0b2ac53a22c03f1755bba","appveyor.yml":"2c7b2468dc69bef84860b8900024cb6e1a1c52f6fe1232e8ccd83caaf7c231ca","src/bitmap_render_target.rs":"d3b229f85a9804ac52976431657727b410e7d5253283df046e46d98c196f0a3a","src/com_helpers.rs":"fccb4b36379ae3454a88aa32a8e5c09e46ef5f5626266dde1fe5f40a992de39c","src/comptr.rs":"218435689f505769686e07cfc5428852dda90b849a0d48e670f632307f5edc7c","src/font.rs":"9bdf3134c6ad3639eab3da4419c9b43aad2673797f6fdc65841da2c82e1f3af4","src/font_collection.rs":"969fa3abf141dc3504774886f4783fda4a74cd5a198c643f8a77fc1af4e75258","src/font_face.rs":"9506ca579345ab2b6b5615fc75f8f431e2bb0dbd93123d1d2a21a73c851a5427","src/font_family.rs":"403da9f8f9903cbe7f9f79636497b273f9885e200f53af99f9d4e483f11d6889","src/font_file.rs":"60ad02fc25765a2c113175ea372e98a2be0d84aa65fef9246b6a0192e63ff708","src/font_file_loader_impl.rs":"0d304ad99ff1e6874510a1498223329d798ff75b417e3db7e823a695003dfe92","src/gdi_interop.rs":"98922996afc5b8c8304cb65e7c965419003825dfa172a3e11fe69bf3d768551c","src/glyph_run_analysis.rs":"d30d8b41b047815ab5770c730b7a6d09939f2347b4a4257b87bebec08a5794fe","src/helpers.rs":"5d6f164468234ca8806dc1cea117b42dbfae80cc4c9ae965cb0556efdb364682","src/lib.rs":"07dae7e9a6b8e2970917eade968490e2af90110047a0e16f539647269b12f439","src/rendering_params.rs":"be1d1c433f76926c285d8ecdb747c5d9cc6a6c10c1a1890c0760cd99755ed471","src/test.rs":"d77e45f8866abeea070cbbafd4cbde62d875292e8d191310a04c70091978547c","src/types.rs":"784235c15d61fb0d001373575169aa473c92af18dcbc1709a5b2bbaa3a7ceb22"},"package":"36e3b27cd0b8a68e00f07e8d8e1e4f4d8a6b8b873290a734f63bd56d792d23e1"} \ No newline at end of file
--- a/third_party/rust/dwrote/Cargo.toml +++ b/third_party/rust/dwrote/Cargo.toml @@ -1,19 +1,42 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + [package] name = "dwrote" +version = "0.4.0" +authors = ["Vladimir Vukicevic <vladimir@pobox.com>"] description = "Lightweight binding to DirectWrite." -repository = "https://github.com/vvuk/dwrote-rs" license = "MPL-2.0" -version = "0.3.0" -authors = ["Vladimir Vukicevic <vladimir@pobox.com>"] +repository = "https://github.com/servo/dwrote-rs" [lib] name = "dwrote" +[dependencies.serde_derive] +version = "1.0" -[dependencies] -libc = "0.2" -lazy_static = "0.2" -winapi = "0.2" -kernel32-sys = "0.2" -gdi32-sys = "0.2" -serde = "0.9" -serde_derive = "0.9" +[dependencies.kernel32-sys] +version = "0.2" + +[dependencies.serde] +version = "1.0" + +[dependencies.winapi] +version = "0.2" + +[dependencies.gdi32-sys] +version = "0.2" + +[dependencies.lazy_static] +version = "0.2" + +[dependencies.libc] +version = "0.2"
new file mode 100644 --- /dev/null +++ b/third_party/rust/dwrote/Cargo.toml.orig @@ -0,0 +1,19 @@ +[package] +name = "dwrote" +description = "Lightweight binding to DirectWrite." +repository = "https://github.com/servo/dwrote-rs" +license = "MPL-2.0" +version = "0.4.0" +authors = ["Vladimir Vukicevic <vladimir@pobox.com>"] + +[lib] +name = "dwrote" + +[dependencies] +libc = "0.2" +lazy_static = "0.2" +winapi = "0.2" +kernel32-sys = "0.2" +gdi32-sys = "0.2" +serde = "1.0" +serde_derive = "1.0"
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/.cargo-checksum.json +++ /dev/null @@ -1,1 +0,0 @@ -{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"118514fd9c4958df0d25584cda4917186c46011569f55ef350530c1ad3fbdb48",".travis.yml":"56843ecfd2b71797b648b8e537623e84af3c638ea4b8472ed27c55f097bce3dc","COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"596d3bcfc1684713b5c557e84b35b98250bebb3d4715e44741d227ab246a16ab","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"625bec69c76ce5423fdd05cfe46922b2680ec517f97c5854ce34798d1d8a9541","src/approxeq.rs":"6cf810ad389c73a27141a7a67454ed12d4b01c3c16605b9a7414b389bc0615dd","src/length.rs":"d7877ebc7ee2e85df2a1f5b9376011bdeeaa5cd7fa2fbdba0934df7456c0821e","src/lib.rs":"77b97c1d7889f037180b68344471ecf7c46b5412fe7c92504debc422c8739b61","src/macros.rs":"b63dabdb52df84ea170dc1dab5fe8d7a78c054562d1566bab416124708d2d7af","src/num.rs":"749b201289fc6663199160a2f9204e17925fd3053f8ab7779e7bfb377ad06227","src/point.rs":"42c1ee0997598d3482ac4c58f255e31b56a97a3a0aa1871b61f55074eecf1ae2","src/rect.rs":"e18811e3be9dba41976b611d52dbe13c5a27dc7db3e3e779daabeed7670b658f","src/scale_factor.rs":"61f979384316ae8a70e836b0d4b016ec5c26a952776037a65801152af4a247cb","src/side_offsets.rs":"fd95ffc9a74e9e84314875c388e763d0780486eb7f9034423e3a22048361e379","src/size.rs":"d9a6fb1f080a06e1332b2e804f8334e086e6d6f17a4288f35133d80b2e2da765","src/transform2d.rs":"4fe4fef7266b06b7790cd400d990ad02e6e605499a1a33c8e39b5e00364389ba","src/transform3d.rs":"cd8a08dd341fcea4c5b10e00d029424e382f3b0002dd8341f302be7f1c12c4fc","src/trig.rs":"ef290927af252ca90a29ba9f17158b591ed591604e66cb9df045dd47b9cfdca5","src/vector.rs":"c087700ad35c3e18e0f5722573f6a24ed2b0452e044c1f0bbb6466c993c560f1"},"package":"995b21c36b37e0f18ed9ba1714378a337e3ff19a6e5e952ea94b0f3dd4e12fbc"} \ No newline at end of file
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Cargo.lock -/target/
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: rust -rust: - - 1.15.1 - - stable - - beta - - nightly - -notifications: - webhooks: http://build.servo.org:54856/travis - -matrix: - include: - - rust: stable - env: FEATURES="" - - rust: beta - env: FEATURES="" - - rust: nightly - env: FEATURES="" - - rust: nightly - env: FEATURES="unstable" - -script: - - cargo build --verbose --features "$FEATURES" - - cargo test --verbose --features "$FEATURES"
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/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.14.4/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "euclid" -version = "0.14.4" -authors = ["The Servo Project Developers"] -description = "Geometry primitives" -documentation = "https://docs.rs/euclid/" -repository = "https://github.com/servo/euclid" -keywords = ["matrix", "vector", "linear-algebra", "geometry"] -categories = ["science"] -license = "MIT / Apache-2.0" - -[features] -unstable = [] - -[dependencies] -heapsize = "0.4" -num-traits = {version = "0.1.32", default-features = false} -log = "0.3.1" -serde = "0.9" - -[dev-dependencies] -rand = "0.3.7" -serde_test = "0.9"
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/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.14.4/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.14.4/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# euclid - -This is a small library for geometric types with a focus on 2d graphics and -layout. - -* [Documentation](https://docs.rs/euclid/) -* [Release notes](https://github.com/servo/euclid/releases) -* [crates.io](https://crates.io/crates/euclid)
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/approxeq.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - - -/// Trait for testing approximate equality -pub trait ApproxEq<Eps> { - fn approx_epsilon() -> Eps; - fn approx_eq(&self, other: &Self) -> bool; - fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool; -} - -macro_rules! approx_eq { - ($ty:ty, $eps:expr) => ( - impl ApproxEq<$ty> for $ty { - #[inline] - fn approx_epsilon() -> $ty { $eps } - #[inline] - fn approx_eq(&self, other: &$ty) -> bool { - self.approx_eq_eps(other, &$eps) - } - #[inline] - fn approx_eq_eps(&self, other: &$ty, approx_epsilon: &$ty) -> bool { - (*self - *other).abs() < *approx_epsilon - } - } - ) -} - -approx_eq!(f32, 1.0e-6); -approx_eq!(f64, 1.0e-6);
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/length.rs +++ /dev/null @@ -1,461 +0,0 @@ -// Copyright 2014 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -//! A one-dimensional length, tagged with its units. - -use scale_factor::ScaleFactor; -use num::Zero; - -use heapsize::HeapSizeOf; -use num_traits::{NumCast, Saturating}; -use num::One; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::cmp::Ordering; -use std::ops::{Add, Sub, Mul, Div, Neg}; -use std::ops::{AddAssign, SubAssign}; -use std::marker::PhantomData; -use std::fmt; - -/// A one-dimensional distance, with value represented by `T` and unit of measurement `Unit`. -/// -/// `T` can be any numeric type, for example a primitive type like `u64` or `f32`. -/// -/// `Unit` is not used in the representation of a `Length` value. It is used only at compile time -/// to ensure that a `Length` stored with one unit is converted explicitly before being used in an -/// expression that requires a different unit. It may be a type without values, such as an empty -/// enum. -/// -/// You can multiply a `Length` by a `scale_factor::ScaleFactor` to convert it from one unit to -/// another. See the `ScaleFactor` docs for an example. -// Uncomment the derive, and remove the macro call, once heapsize gets -// PhantomData<T> support. -#[repr(C)] -pub struct Length<T, Unit>(pub T, PhantomData<Unit>); - -impl<T: Clone, Unit> Clone for Length<T, Unit> { - fn clone(&self) -> Self { - Length(self.0.clone(), PhantomData) - } -} - -impl<T: Copy, Unit> Copy for Length<T, Unit> {} - -impl<Unit, T: HeapSizeOf> HeapSizeOf for Length<T, Unit> { - fn heap_size_of_children(&self) -> usize { - self.0.heap_size_of_children() - } -} - -impl<Unit, T> Deserialize for Length<T, Unit> where T: Deserialize { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where D: Deserializer { - Ok(Length(try!(Deserialize::deserialize(deserializer)), PhantomData)) - } -} - -impl<T, Unit> Serialize for Length<T, Unit> where T: Serialize { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { - self.0.serialize(serializer) - } -} - -impl<T, Unit> Length<T, Unit> { - pub fn new(x: T) -> Self { - Length(x, PhantomData) - } -} - -impl<Unit, T: Clone> Length<T, Unit> { - pub fn get(&self) -> T { - self.0.clone() - } -} - -impl<T: fmt::Debug + Clone, U> fmt::Debug for Length<T, U> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.get().fmt(f) - } -} - -impl<T: fmt::Display + Clone, U> fmt::Display for Length<T, U> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.get().fmt(f) - } -} - -// length + length -impl<U, T: Clone + Add<T, Output=T>> Add for Length<T, U> { - type Output = Length<T, U>; - fn add(self, other: Length<T, U>) -> Length<T, U> { - Length::new(self.get() + other.get()) - } -} - -// length += length -impl<U, T: Clone + AddAssign<T>> AddAssign for Length<T, U> { - fn add_assign(&mut self, other: Length<T, U>) { - self.0 += other.get(); - } -} - -// length - length -impl<U, T: Clone + Sub<T, Output=T>> Sub<Length<T, U>> for Length<T, U> { - type Output = Length<T, U>; - fn sub(self, other: Length<T, U>) -> <Self as Sub>::Output { - Length::new(self.get() - other.get()) - } -} - -// length -= length -impl<U, T: Clone + SubAssign<T>> SubAssign for Length<T, U> { - fn sub_assign(&mut self, other: Length<T, U>) { - self.0 -= other.get(); - } -} - -// Saturating length + length and length - length. -impl<U, T: Clone + Saturating> Saturating for Length<T, U> { - fn saturating_add(self, other: Length<T, U>) -> Length<T, U> { - Length::new(self.get().saturating_add(other.get())) - } - - fn saturating_sub(self, other: Length<T, U>) -> Length<T, U> { - Length::new(self.get().saturating_sub(other.get())) - } -} - -// length / length -impl<Src, Dst, T: Clone + Div<T, Output=T>> Div<Length<T, Src>> for Length<T, Dst> { - type Output = ScaleFactor<T, Src, Dst>; - #[inline] - fn div(self, other: Length<T, Src>) -> ScaleFactor<T, Src, Dst> { - ScaleFactor::new(self.get() / other.get()) - } -} - -// length * scaleFactor -impl<Src, Dst, T: Clone + Mul<T, Output=T>> Mul<ScaleFactor<T, Src, Dst>> for Length<T, Src> { - type Output = Length<T, Dst>; - #[inline] - fn mul(self, scale: ScaleFactor<T, Src, Dst>) -> Length<T, Dst> { - Length::new(self.get() * scale.get()) - } -} - -// length / scaleFactor -impl<Src, Dst, T: Clone + Div<T, Output=T>> Div<ScaleFactor<T, Src, Dst>> for Length<T, Dst> { - type Output = Length<T, Src>; - #[inline] - fn div(self, scale: ScaleFactor<T, Src, Dst>) -> Length<T, Src> { - Length::new(self.get() / scale.get()) - } -} - -// -length -impl <U, T:Clone + Neg<Output=T>> Neg for Length<T, U> { - type Output = Length<T, U>; - #[inline] - fn neg(self) -> Length<T, U> { - Length::new(-self.get()) - } -} - -impl<Unit, T0: NumCast + Clone> Length<T0, Unit> { - /// Cast from one numeric representation to another, preserving the units. - pub fn cast<T1: NumCast + Clone>(&self) -> Option<Length<T1, Unit>> { - NumCast::from(self.get()).map(Length::new) - } -} - -impl<Unit, T: Clone + PartialEq> PartialEq for Length<T, Unit> { - fn eq(&self, other: &Self) -> bool { self.get().eq(&other.get()) } -} - -impl<Unit, T: Clone + PartialOrd> PartialOrd for Length<T, Unit> { - fn partial_cmp(&self, other: &Self) -> Option<Ordering> { - self.get().partial_cmp(&other.get()) - } -} - -impl<Unit, T: Clone + Eq> Eq for Length<T, Unit> {} - -impl<Unit, T: Clone + Ord> Ord for Length<T, Unit> { - fn cmp(&self, other: &Self) -> Ordering { self.get().cmp(&other.get()) } -} - -impl<Unit, T: Zero> Zero for Length<T, Unit> { - fn zero() -> Self { - Length::new(Zero::zero()) - } -} - -impl<T, U> Length<T, U> -where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> { - /// Linearly interpolate between this length and another length. - /// - /// `t` is expected to be between zero and one. - #[inline] - pub fn lerp(&self, other: Self, t: T) -> Self { - let one_t = T::one() - t; - Length::new(one_t * self.get() + t * other.get()) - } -} - -#[cfg(test)] -mod tests { - use super::Length; - use num::Zero; - - use heapsize::HeapSizeOf; - use num_traits::Saturating; - use scale_factor::ScaleFactor; - use std::f32::INFINITY; - - extern crate serde_test; - use self::serde_test::Token; - use self::serde_test::assert_tokens; - - enum Inch {} - enum Mm {} - enum Cm {} - enum Second {} - - #[test] - fn test_clone() { - // A cloned Length is a separate length with the state matching the - // original Length at the point it was cloned. - let mut variable_length: Length<f32, Inch> = Length::new(12.0); - - let one_foot = variable_length.clone(); - variable_length.0 = 24.0; - - assert_eq!(one_foot.get(), 12.0); - assert_eq!(variable_length.get(), 24.0); - } - - #[test] - fn test_heapsizeof_builtins() { - // Heap size of built-ins is zero by default. - let one_foot: Length<f32, Inch> = Length::new(12.0); - - let heap_size_length_f32 = one_foot.heap_size_of_children(); - - assert_eq!(heap_size_length_f32, 0); - } - - #[test] - fn test_heapsizeof_length_vector() { - // Heap size of any Length is just the heap size of the length value. - for n in 0..5 { - let length: Length<Vec<f32>, Inch> = Length::new(Vec::with_capacity(n)); - - assert_eq!(length.heap_size_of_children(), length.0.heap_size_of_children()); - } - } - - #[test] - fn test_length_serde() { - let one_cm: Length<f32, Mm> = Length::new(10.0); - - assert_tokens(&one_cm, &[Token::F32(10.0)]); - } - - #[test] - fn test_get_clones_length_value() { - // Calling get returns a clone of the Length's value. - // To test this, we need something clone-able - hence a vector. - let mut length: Length<Vec<i32>, Inch> = Length::new(vec![1, 2, 3]); - - let value = length.get(); - length.0.push(4); - - assert_eq!(value, vec![1, 2, 3]); - assert_eq!(length.get(), vec![1, 2, 3, 4]); - } - - #[test] - fn test_fmt_debug() { - // Debug and display format the value only. - let one_cm: Length<f32, Mm> = Length::new(10.0); - - let result = format!("{:?}", one_cm); - - assert_eq!(result, "10"); - } - - #[test] - fn test_fmt_display() { - // Debug and display format the value only. - let one_cm: Length<f32, Mm> = Length::new(10.0); - - let result = format!("{}", one_cm); - - assert_eq!(result, "10"); - } - - #[test] - fn test_add() { - let length1: Length<u8, Mm> = Length::new(250); - let length2: Length<u8, Mm> = Length::new(5); - - let result = length1 + length2; - - assert_eq!(result.get(), 255); - } - - #[test] - fn test_addassign() { - let one_cm: Length<f32, Mm> = Length::new(10.0); - let mut measurement: Length<f32, Mm> = Length::new(5.0); - - measurement += one_cm; - - assert_eq!(measurement.get(), 15.0); - } - - #[test] - fn test_sub() { - let length1: Length<u8, Mm> = Length::new(250); - let length2: Length<u8, Mm> = Length::new(5); - - let result = length1 - length2; - - assert_eq!(result.get(), 245); - } - - #[test] - fn test_subassign() { - let one_cm: Length<f32, Mm> = Length::new(10.0); - let mut measurement: Length<f32, Mm> = Length::new(5.0); - - measurement -= one_cm; - - assert_eq!(measurement.get(), -5.0); - } - - #[test] - fn test_saturating_add() { - let length1: Length<u8, Mm> = Length::new(250); - let length2: Length<u8, Mm> = Length::new(6); - - let result = length1.saturating_add(length2); - - assert_eq!(result.get(), 255); - } - - #[test] - fn test_saturating_sub() { - let length1: Length<u8, Mm> = Length::new(5); - let length2: Length<u8, Mm> = Length::new(10); - - let result = length1.saturating_sub(length2); - - assert_eq!(result.get(), 0); - } - - #[test] - fn test_division_by_length() { - // Division results in a ScaleFactor from denominator units - // to numerator units. - let length: Length<f32, Cm> = Length::new(5.0); - let duration: Length<f32, Second> = Length::new(10.0); - - let result = length / duration; - - let expected: ScaleFactor<f32, Second, Cm> = ScaleFactor::new(0.5); - assert_eq!(result, expected); - } - - #[test] - fn test_multiplication() { - let length_mm: Length<f32, Mm> = Length::new(10.0); - let cm_per_mm: ScaleFactor<f32, Mm, Cm> = ScaleFactor::new(0.1); - - let result = length_mm * cm_per_mm; - - let expected: Length<f32, Cm> = Length::new(1.0); - assert_eq!(result, expected); - } - - #[test] - fn test_division_by_scalefactor() { - let length: Length<f32, Cm> = Length::new(5.0); - let cm_per_second: ScaleFactor<f32, Second, Cm> = ScaleFactor::new(10.0); - - let result = length / cm_per_second; - - let expected: Length<f32, Second> = Length::new(0.5); - assert_eq!(result, expected); - } - - #[test] - fn test_negation() { - let length: Length<f32, Cm> = Length::new(5.0); - - let result = -length; - - let expected: Length<f32, Cm> = Length::new(-5.0); - assert_eq!(result, expected); - } - - #[test] - fn test_cast() { - let length_as_i32: Length<i32, Cm> = Length::new(5); - - let result: Length<f32, Cm> = length_as_i32.cast().unwrap(); - - let length_as_f32: Length<f32, Cm> = Length::new(5.0); - assert_eq!(result, length_as_f32); - } - - #[test] - fn test_equality() { - let length_5_point_0: Length<f32, Cm> = Length::new(5.0); - let length_5_point_1: Length<f32, Cm> = Length::new(5.1); - let length_0_point_1: Length<f32, Cm> = Length::new(0.1); - - assert!(length_5_point_0 == length_5_point_1 - length_0_point_1); - assert!(length_5_point_0 != length_5_point_1); - } - - #[test] - fn test_order() { - let length_5_point_0: Length<f32, Cm> = Length::new(5.0); - let length_5_point_1: Length<f32, Cm> = Length::new(5.1); - let length_0_point_1: Length<f32, Cm> = Length::new(0.1); - - assert!(length_5_point_0 < length_5_point_1); - assert!(length_5_point_0 <= length_5_point_1); - assert!(length_5_point_0 <= length_5_point_1 - length_0_point_1); - assert!(length_5_point_1 > length_5_point_0); - assert!(length_5_point_1 >= length_5_point_0); - assert!(length_5_point_0 >= length_5_point_1 - length_0_point_1); - } - - #[test] - fn test_zero_add() { - type LengthCm = Length<f32, Cm>; - let length: LengthCm = Length::new(5.0); - - let result = length - LengthCm::zero(); - - assert_eq!(result, length); - } - - #[test] - fn test_zero_division() { - type LengthCm = Length<f32, Cm>; - let length: LengthCm = Length::new(5.0); - let length_zero: LengthCm = Length::zero(); - - let result = length / length_zero; - - let expected: ScaleFactor<f32, Cm, Cm> = ScaleFactor::new(INFINITY); - assert_eq!(result, expected); - } -}
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/lib.rs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![cfg_attr(feature = "unstable", feature(asm, repr_simd, test))] - -//! A collection of strongly typed math tools for computer graphics with an inclination -//! towards 2d graphics and layout. -//! -//! All types are generic over the scalar type of their component (`f32`, `i32`, etc.), -//! and tagged with a generic Unit parameter which is useful to prevent mixing -//! values from different spaces. For example it should not be legal to translate -//! a screen-space position by a world-space vector and this can be expressed using -//! the generic Unit parameter. -//! -//! This unit system is not mandatory and all Typed* structures have an alias -//! with the default unit: `UnknownUnit`. -//! for example ```Point2D<T>``` is equivalent to ```TypedPoint2D<T, UnknownUnit>```. -//! Client code typically creates a set of aliases for each type and doesn't need -//! to deal with the specifics of typed units further. For example: -//! -//! All euclid types are marked `#[repr(C)]` in order to facilitate exposing them to -//! foreign function interfaces (provided the underlying scalar type is also `repr(C)`). -//! -//! ```rust -//! use euclid::*; -//! pub struct ScreenSpace; -//! pub type ScreenPoint = TypedPoint2D<f32, ScreenSpace>; -//! pub type ScreenSize = TypedSize2D<f32, ScreenSpace>; -//! pub struct WorldSpace; -//! pub type WorldPoint = TypedPoint3D<f32, WorldSpace>; -//! pub type ProjectionMatrix = TypedMatrix4D<f32, WorldSpace, ScreenSpace>; -//! // etc... -//! ``` -//! -//! Components are accessed in their scalar form by default for convenience, and most -//! types additionally implement strongly typed accessors which return typed ```Length``` wrappers. -//! For example: -//! -//! ```rust -//! # use euclid::*; -//! # pub struct WorldSpace; -//! # pub type WorldPoint = TypedPoint3D<f32, WorldSpace>; -//! let p = WorldPoint::new(0.0, 1.0, 1.0); -//! // p.x is an f32. -//! println!("p.x = {:?} ", p.x); -//! // p.x is a Length<f32, WorldSpace>. -//! println!("p.x_typed() = {:?} ", p.x_typed()); -//! // Length::get returns the scalar value (f32). -//! assert_eq!(p.x, p.x_typed().get()); -//! ``` - -extern crate heapsize; - -#[cfg_attr(test, macro_use)] -extern crate log; -extern crate serde; - -#[cfg(test)] -extern crate rand; -#[cfg(feature = "unstable")] -extern crate test; -extern crate num_traits; - -pub use length::Length; -pub use scale_factor::ScaleFactor; -pub use transform2d::{Transform2D, TypedTransform2D}; -pub use transform3d::{Transform3D, TypedTransform3D}; -pub use point::{ - Point2D, TypedPoint2D, point2, - Point3D, TypedPoint3D, point3, -}; -pub use vector::{ - Vector2D, TypedVector2D, vec2, - Vector3D, TypedVector3D, vec3, -}; - -pub use rect::{Rect, TypedRect, rect}; -pub use side_offsets::{SideOffsets2D, TypedSideOffsets2D}; -#[cfg(feature = "unstable")] pub use side_offsets::SideOffsets2DSimdI32; -pub use size::{Size2D, TypedSize2D, size2}; -pub use trig::Trig; - -pub mod approxeq; -pub mod num; -mod length; -#[macro_use] -mod macros; -mod transform2d; -mod transform3d; -mod point; -mod rect; -mod scale_factor; -mod side_offsets; -mod size; -mod trig; -mod vector; - -/// The default unit. -#[derive(Clone, Copy)] -pub struct UnknownUnit; - -/// Unit for angles in radians. -pub struct Rad; - -/// Unit for angles in degrees. -pub struct Deg; - -/// A value in radians. -pub type Radians<T> = Length<T, Rad>; - -/// A value in Degrees. -pub type Degrees<T> = Length<T, Deg>; - -/// Temporary alias to facilitate the transition to the new naming scheme -#[deprecated] -pub type Matrix2D<T> = Transform2D<T>; - -/// Temporary alias to facilitate the transition to the new naming scheme -#[deprecated] -pub type TypedMatrix2D<T, Src, Dst> = TypedTransform2D<T, Src, Dst>; - -/// Temporary alias to facilitate the transition to the new naming scheme -#[deprecated] -pub type Matrix4D<T> = Transform3D<T>; - -/// Temporary alias to facilitate the transition to the new naming scheme -#[deprecated] -pub type TypedMatrix4D<T, Src, Dst> = TypedTransform3D<T, Src, Dst>; -
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/macros.rs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -macro_rules! define_matrix { - ( - $(#[$attr:meta])* - pub struct $name:ident<T, $($phantom:ident),+> { - $(pub $field:ident: T,)+ - } - ) => ( - #[repr(C)] - $(#[$attr])* - pub struct $name<T, $($phantom),+> { - $(pub $field: T,)+ - _unit: PhantomData<($($phantom),+)> - } - - impl<T: Clone, $($phantom),+> Clone for $name<T, $($phantom),+> { - fn clone(&self) -> Self { - $name { - $($field: self.$field.clone(),)+ - _unit: PhantomData, - } - } - } - - impl<T: Copy, $($phantom),+> Copy for $name<T, $($phantom),+> {} - - impl<T, $($phantom),+> ::heapsize::HeapSizeOf for $name<T, $($phantom),+> - where T: ::heapsize::HeapSizeOf - { - fn heap_size_of_children(&self) -> usize { - $(self.$field.heap_size_of_children() +)+ 0 - } - } - - impl<T, $($phantom),+> ::serde::Deserialize for $name<T, $($phantom),+> - where T: ::serde::Deserialize - { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where D: ::serde::Deserializer - { - let ($($field,)+) = - try!(::serde::Deserialize::deserialize(deserializer)); - Ok($name { - $($field: $field,)+ - _unit: PhantomData, - }) - } - } - - impl<T, $($phantom),+> ::serde::Serialize for $name<T, $($phantom),+> - where T: ::serde::Serialize - { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: ::serde::Serializer - { - ($(&self.$field,)+).serialize(serializer) - } - } - - impl<T, $($phantom),+> ::std::cmp::Eq for $name<T, $($phantom),+> - where T: ::std::cmp::Eq {} - - impl<T, $($phantom),+> ::std::cmp::PartialEq for $name<T, $($phantom),+> - where T: ::std::cmp::PartialEq - { - fn eq(&self, other: &Self) -> bool { - true $(&& self.$field == other.$field)+ - } - } - - impl<T, $($phantom),+> ::std::hash::Hash for $name<T, $($phantom),+> - where T: ::std::hash::Hash - { - fn hash<H: ::std::hash::Hasher>(&self, h: &mut H) { - $(self.$field.hash(h);)+ - } - } - ) -}
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/num.rs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2014 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -//! A one-dimensional length, tagged with its units. - -use num_traits; - - -pub trait Zero { - fn zero() -> Self; -} - -impl<T: num_traits::Zero> Zero for T { - fn zero() -> T { num_traits::Zero::zero() } -} - -pub trait One { - fn one() -> Self; -} - -impl<T: num_traits::One> One for T { - fn one() -> T { num_traits::One::one() } -} - - -pub trait Round : Copy { fn round(self) -> Self; } -pub trait Floor : Copy { fn floor(self) -> Self; } -pub trait Ceil : Copy { fn ceil(self) -> Self; } - -macro_rules! num_int { - ($ty:ty) => ( - impl Round for $ty { - #[inline] - fn round(self) -> $ty { self } - } - impl Floor for $ty { - #[inline] - fn floor(self) -> $ty { self } - } - impl Ceil for $ty { - #[inline] - fn ceil(self) -> $ty { self } - } - ) -} -macro_rules! num_float { - ($ty:ty) => ( - impl Round for $ty { - #[inline] - fn round(self) -> $ty { self.round() } - } - impl Floor for $ty { - #[inline] - fn floor(self) -> $ty { self.floor() } - } - impl Ceil for $ty { - #[inline] - fn ceil(self) -> $ty { self.ceil() } - } - ) -} - -num_int!(i16); -num_int!(u16); -num_int!(i32); -num_int!(u32); -num_int!(i64); -num_int!(u64); -num_int!(isize); -num_int!(usize); -num_float!(f32); -num_float!(f64);
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/point.rs +++ /dev/null @@ -1,796 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use super::UnknownUnit; -use approxeq::ApproxEq; -use length::Length; -use scale_factor::ScaleFactor; -use size::TypedSize2D; -use num::*; -use num_traits::{Float, NumCast}; -use vector::{TypedVector2D, TypedVector3D, vec2, vec3}; -use std::fmt; -use std::ops::{Add, Mul, Sub, Div, AddAssign, SubAssign, MulAssign, DivAssign}; -use std::marker::PhantomData; - -define_matrix! { - /// A 2d Point tagged with a unit. - pub struct TypedPoint2D<T, U> { - pub x: T, - pub y: T, - } -} - -/// Default 2d point type with no unit. -/// -/// `Point2D` provides the same methods as `TypedPoint2D`. -pub type Point2D<T> = TypedPoint2D<T, UnknownUnit>; - -impl<T: Copy + Zero, U> TypedPoint2D<T, U> { - /// Constructor, setting all components to zero. - #[inline] - pub fn origin() -> Self { - point2(Zero::zero(), Zero::zero()) - } - - #[inline] - pub fn zero() -> Self { - Self::origin() - } - - /// Convert into a 3d point. - #[inline] - pub fn to_3d(&self) -> TypedPoint3D<T, U> { - point3(self.x, self.y, Zero::zero()) - } -} - -impl<T: fmt::Debug, U> fmt::Debug for TypedPoint2D<T, U> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "({:?},{:?})", self.x, self.y) - } -} - -impl<T: fmt::Display, U> fmt::Display for TypedPoint2D<T, U> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "({},{})", self.x, self.y) - } -} - -impl<T: Copy, U> TypedPoint2D<T, U> { - /// Constructor taking scalar values directly. - #[inline] - pub fn new(x: T, y: T) -> Self { - TypedPoint2D { x: x, y: y, _unit: PhantomData } - } - - /// Constructor taking properly typed Lengths instead of scalar values. - #[inline] - pub fn from_lengths(x: Length<T, U>, y: Length<T, U>) -> Self { - point2(x.0, y.0) - } - - /// Create a 3d point from this one, using the specified z value. - #[inline] - pub fn extend(&self, z: T) -> TypedPoint3D<T, U> { - point3(self.x, self.y, z) - } - - /// Cast this point into a vector. - /// - /// Equivalent to substracting the origin to this point. - #[inline] - pub fn to_vector(&self) -> TypedVector2D<T, U> { - vec2(self.x, self.y) - } - - /// Returns self.x as a Length carrying the unit. - #[inline] - pub fn x_typed(&self) -> Length<T, U> { Length::new(self.x) } - - /// Returns self.y as a Length carrying the unit. - #[inline] - pub fn y_typed(&self) -> Length<T, U> { Length::new(self.y) } - - /// Drop the units, preserving only the numeric value. - #[inline] - pub fn to_untyped(&self) -> Point2D<T> { - point2(self.x, self.y) - } - - /// Tag a unitless value with units. - #[inline] - pub fn from_untyped(p: &Point2D<T>) -> Self { - point2(p.x, p.y) - } - - #[inline] - pub fn to_array(&self) -> [T; 2] { - [self.x, self.y] - } -} - -impl<T: Copy + Add<T, Output=T>, U> TypedPoint2D<T, U> { - #[inline] - pub fn add_size(&self, other: &TypedSize2D<T, U>) -> Self { - point2(self.x + other.width, self.y + other.height) - } -} - -impl<T: Copy + Add<T, Output=T>, U> Add<TypedSize2D<T, U>> for TypedPoint2D<T, U> { - type Output = Self; - #[inline] - fn add(self, other: TypedSize2D<T, U>) -> Self { - point2(self.x + other.width, self.y + other.height) - } -} - -impl<T: Copy + Add<T, Output=T>, U> AddAssign<TypedVector2D<T, U>> for TypedPoint2D<T, U> { - #[inline] - fn add_assign(&mut self, other: TypedVector2D<T, U>) { - *self = *self + other - } -} - -impl<T: Copy + Sub<T, Output=T>, U> SubAssign<TypedVector2D<T, U>> for TypedPoint2D<T, U> { - #[inline] - fn sub_assign(&mut self, other: TypedVector2D<T, U>) { - *self = *self - other - } -} - -impl<T: Copy + Add<T, Output=T>, U> Add<TypedVector2D<T, U>> for TypedPoint2D<T, U> { - type Output = Self; - #[inline] - fn add(self, other: TypedVector2D<T, U>) -> Self { - point2(self.x + other.x, self.y + other.y) - } -} - -impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedPoint2D<T, U> { - type Output = TypedVector2D<T, U>; - #[inline] - fn sub(self, other: Self) -> TypedVector2D<T, U> { - vec2(self.x - other.x, self.y - other.y) - } -} - -impl<T: Copy + Sub<T, Output=T>, U> Sub<TypedVector2D<T, U>> for TypedPoint2D<T, U> { - type Output = Self; - #[inline] - fn sub(self, other: TypedVector2D<T, U>) -> Self { - point2(self.x - other.x, self.y - other.y) - } -} - -impl<T: Float, U> TypedPoint2D<T, U> { - #[inline] - pub fn min(self, other: Self) -> Self { - point2(self.x.min(other.x), self.y.min(other.y)) - } - - #[inline] - pub fn max(self, other: Self) -> Self { - point2(self.x.max(other.x), self.y.max(other.y)) - } -} - -impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedPoint2D<T, U> { - type Output = Self; - #[inline] - fn mul(self, scale: T) -> Self { - point2(self.x * scale, self.y * scale) - } -} - -impl<T: Copy + Mul<T, Output=T>, U> MulAssign<T> for TypedPoint2D<T, U> { - #[inline] - fn mul_assign(&mut self, scale: T) { - *self = *self * scale - } -} - -impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedPoint2D<T, U> { - type Output = Self; - #[inline] - fn div(self, scale: T) -> Self { - point2(self.x / scale, self.y / scale) - } -} - -impl<T: Copy + Div<T, Output=T>, U> DivAssign<T> for TypedPoint2D<T, U> { - #[inline] - fn div_assign(&mut self, scale: T) { - *self = *self / scale - } -} - -impl<T: Copy + Mul<T, Output=T>, U1, U2> Mul<ScaleFactor<T, U1, U2>> for TypedPoint2D<T, U1> { - type Output = TypedPoint2D<T, U2>; - #[inline] - fn mul(self, scale: ScaleFactor<T, U1, U2>) -> TypedPoint2D<T, U2> { - point2(self.x * scale.get(), self.y * scale.get()) - } -} - -impl<T: Copy + Div<T, Output=T>, U1, U2> Div<ScaleFactor<T, U1, U2>> for TypedPoint2D<T, U2> { - type Output = TypedPoint2D<T, U1>; - #[inline] - fn div(self, scale: ScaleFactor<T, U1, U2>) -> TypedPoint2D<T, U1> { - point2(self.x / scale.get(), self.y / scale.get()) - } -} - -impl<T: Round, U> TypedPoint2D<T, U> { - /// Rounds each component to the nearest integer value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - /// For example `{ -0.1, -0.8 }.round() == { 0.0, -1.0 }`. - #[inline] - #[must_use] - pub fn round(&self) -> Self { - point2(self.x.round(), self.y.round()) - } -} - -impl<T: Ceil, U> TypedPoint2D<T, U> { - /// Rounds each component to the smallest integer equal or greater than the original value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - /// For example `{ -0.1, -0.8 }.ceil() == { 0.0, 0.0 }`. - #[inline] - #[must_use] - pub fn ceil(&self) -> Self { - point2(self.x.ceil(), self.y.ceil()) - } -} - -impl<T: Floor, U> TypedPoint2D<T, U> { - /// Rounds each component to the biggest integer equal or lower than the original value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - /// For example `{ -0.1, -0.8 }.floor() == { -1.0, -1.0 }`. - #[inline] - #[must_use] - pub fn floor(&self) -> Self { - point2(self.x.floor(), self.y.floor()) - } -} - -impl<T: NumCast + Copy, U> TypedPoint2D<T, U> { - /// Cast from one numeric representation to another, preserving the units. - /// - /// When casting from floating point to integer coordinates, the decimals are truncated - /// as one would expect from a simple cast, but this behavior does not always make sense - /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting. - #[inline] - pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedPoint2D<NewT, U>> { - match (NumCast::from(self.x), NumCast::from(self.y)) { - (Some(x), Some(y)) => Some(point2(x, y)), - _ => None - } - } - - // Convenience functions for common casts - - /// Cast into an `f32` point. - #[inline] - pub fn to_f32(&self) -> TypedPoint2D<f32, U> { - self.cast().unwrap() - } - - /// Cast into an `usize` point, truncating decimals if any. - /// - /// When casting from floating point points, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - #[inline] - pub fn to_usize(&self) -> TypedPoint2D<usize, U> { - self.cast().unwrap() - } - - /// Cast into an i32 point, truncating decimals if any. - /// - /// When casting from floating point points, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - #[inline] - pub fn to_i32(&self) -> TypedPoint2D<i32, U> { - self.cast().unwrap() - } - - /// Cast into an i64 point, truncating decimals if any. - /// - /// When casting from floating point points, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - #[inline] - pub fn to_i64(&self) -> TypedPoint2D<i64, U> { - self.cast().unwrap() - } -} - -impl<T, U> TypedPoint2D<T, U> -where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> { - /// Linearly interpolate between this point and another point. - /// - /// `t` is expected to be between zero and one. - #[inline] - pub fn lerp(&self, other: Self, t: T) -> Self { - let one_t = T::one() - t; - point2( - one_t * self.x + t * other.x, - one_t * self.y + t * other.y, - ) - } -} - -impl<T: Copy+ApproxEq<T>, U> ApproxEq<TypedPoint2D<T, U>> for TypedPoint2D<T, U> { - #[inline] - fn approx_epsilon() -> Self { - point2(T::approx_epsilon(), T::approx_epsilon()) - } - - #[inline] - fn approx_eq(&self, other: &Self) -> bool { - self.x.approx_eq(&other.x) && self.y.approx_eq(&other.y) - } - - #[inline] - fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool { - self.x.approx_eq_eps(&other.x, &eps.x) && self.y.approx_eq_eps(&other.y, &eps.y) - } -} - -impl<T: Copy, U> Into<[T; 2]> for TypedPoint2D<T, U> { - fn into(self) -> [T; 2] { - self.to_array() - } -} - -impl<T: Copy, U> From<[T; 2]> for TypedPoint2D<T, U> { - fn from(array: [T; 2]) -> Self { - point2(array[0], array[1]) - } -} - - -define_matrix! { - /// A 3d Point tagged with a unit. - pub struct TypedPoint3D<T, U> { - pub x: T, - pub y: T, - pub z: T, - } -} - -/// Default 3d point type with no unit. -/// -/// `Point3D` provides the same methods as `TypedPoint3D`. -pub type Point3D<T> = TypedPoint3D<T, UnknownUnit>; - -impl<T: Copy + Zero, U> TypedPoint3D<T, U> { - /// Constructor, setting all copmonents to zero. - #[inline] - pub fn origin() -> Self { - point3(Zero::zero(), Zero::zero(), Zero::zero()) - } -} - -impl<T: Copy + One, U> TypedPoint3D<T, U> { - #[inline] - pub fn to_array_4d(&self) -> [T; 4] { - [self.x, self.y, self.z, One::one()] - } -} - -impl<T, U> TypedPoint3D<T, U> -where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> { - /// Linearly interpolate between this point and another point. - /// - /// `t` is expected to be between zero and one. - #[inline] - pub fn lerp(&self, other: Self, t: T) -> Self { - let one_t = T::one() - t; - point3( - one_t * self.x + t * other.x, - one_t * self.y + t * other.y, - one_t * self.z + t * other.z, - ) - } -} - -impl<T: fmt::Debug, U> fmt::Debug for TypedPoint3D<T, U> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "({:?},{:?},{:?})", self.x, self.y, self.z) - } -} - -impl<T: fmt::Display, U> fmt::Display for TypedPoint3D<T, U> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "({},{},{})", self.x, self.y, self.z) - } -} - -impl<T: Copy, U> TypedPoint3D<T, U> { - /// Constructor taking scalar values directly. - #[inline] - pub fn new(x: T, y: T, z: T) -> Self { - TypedPoint3D { x: x, y: y, z: z, _unit: PhantomData } - } - - /// Constructor taking properly typed Lengths instead of scalar values. - #[inline] - pub fn from_lengths(x: Length<T, U>, y: Length<T, U>, z: Length<T, U>) -> Self { - point3(x.0, y.0, z.0) - } - - /// Cast this point into a vector. - /// - /// Equivalent to substracting the origin to this point. - #[inline] - pub fn to_vector(&self) -> TypedVector3D<T, U> { - vec3(self.x, self.y, self.z) - } - - /// Returns self.x as a Length carrying the unit. - #[inline] - pub fn x_typed(&self) -> Length<T, U> { Length::new(self.x) } - - /// Returns self.y as a Length carrying the unit. - #[inline] - pub fn y_typed(&self) -> Length<T, U> { Length::new(self.y) } - - /// Returns self.z as a Length carrying the unit. - #[inline] - pub fn z_typed(&self) -> Length<T, U> { Length::new(self.z) } - - #[inline] - pub fn to_array(&self) -> [T; 3] { [self.x, self.y, self.z] } - - /// Drop the units, preserving only the numeric value. - #[inline] - pub fn to_untyped(&self) -> Point3D<T> { - point3(self.x, self.y, self.z) - } - - /// Tag a unitless value with units. - #[inline] - pub fn from_untyped(p: &Point3D<T>) -> Self { - point3(p.x, p.y, p.z) - } - - /// Convert into a 2d point. - #[inline] - pub fn to_2d(&self) -> TypedPoint2D<T, U> { - point2(self.x, self.y) - } -} - -impl<T: Copy + Add<T, Output=T>, U> AddAssign<TypedVector3D<T, U>> for TypedPoint3D<T, U> { - #[inline] - fn add_assign(&mut self, other: TypedVector3D<T, U>) { - *self = *self + other - } -} - -impl<T: Copy + Sub<T, Output=T>, U> SubAssign<TypedVector3D<T, U>> for TypedPoint3D<T, U> { - #[inline] - fn sub_assign(&mut self, other: TypedVector3D<T, U>) { - *self = *self - other - } -} - -impl<T: Copy + Add<T, Output=T>, U> Add<TypedVector3D<T, U>> for TypedPoint3D<T, U> { - type Output = Self; - #[inline] - fn add(self, other: TypedVector3D<T, U>) -> Self { - point3(self.x + other.x, self.y + other.y, self.z + other.z) - } -} - -impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedPoint3D<T, U> { - type Output = TypedVector3D<T, U>; - #[inline] - fn sub(self, other: Self) -> TypedVector3D<T, U> { - vec3(self.x - other.x, self.y - other.y, self.z - other.z) - } -} - -impl<T: Copy + Sub<T, Output=T>, U> Sub<TypedVector3D<T, U>> for TypedPoint3D<T, U> { - type Output = Self; - #[inline] - fn sub(self, other: TypedVector3D<T, U>) -> Self { - point3(self.x - other.x, self.y - other.y, self.z - other.z) - } -} - -impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedPoint3D<T, U> { - type Output = Self; - #[inline] - fn mul(self, scale: T) -> Self { - point3(self.x * scale, self.y * scale, self.z * scale) - } -} - -impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedPoint3D<T, U> { - type Output = Self; - #[inline] - fn div(self, scale: T) -> Self { - point3(self.x / scale, self.y / scale, self.z / scale) - } -} - -impl<T: Float, U> TypedPoint3D<T, U> { - #[inline] - pub fn min(self, other: Self) -> Self { - point3(self.x.min(other.x), self.y.min(other.y), self.z.min(other.z)) - } - - #[inline] - pub fn max(self, other: Self) -> Self { - point3(self.x.max(other.x), self.y.max(other.y), self.z.max(other.z)) - } -} - -impl<T: Round, U> TypedPoint3D<T, U> { - /// Rounds each component to the nearest integer value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - #[inline] - #[must_use] - pub fn round(&self) -> Self { - point3(self.x.round(), self.y.round(), self.z.round()) - } -} - -impl<T: Ceil, U> TypedPoint3D<T, U> { - /// Rounds each component to the smallest integer equal or greater than the original value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - #[inline] - #[must_use] - pub fn ceil(&self) -> Self { - point3(self.x.ceil(), self.y.ceil(), self.z.ceil()) - } -} - -impl<T: Floor, U> TypedPoint3D<T, U> { - /// Rounds each component to the biggest integer equal or lower than the original value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - #[inline] - #[must_use] - pub fn floor(&self) -> Self { - point3(self.x.floor(), self.y.floor(), self.z.floor()) - } -} - -impl<T: NumCast + Copy, U> TypedPoint3D<T, U> { - /// Cast from one numeric representation to another, preserving the units. - /// - /// When casting from floating point to integer coordinates, the decimals are truncated - /// as one would expect from a simple cast, but this behavior does not always make sense - /// geometrically. Consider using round(), ceil or floor() before casting. - #[inline] - pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedPoint3D<NewT, U>> { - match (NumCast::from(self.x), - NumCast::from(self.y), - NumCast::from(self.z)) { - (Some(x), Some(y), Some(z)) => Some(point3(x, y, z)), - _ => None - } - } - - // Convenience functions for common casts - - /// Cast into an `f32` point. - #[inline] - pub fn to_f32(&self) -> TypedPoint3D<f32, U> { - self.cast().unwrap() - } - - /// Cast into an `usize` point, truncating decimals if any. - /// - /// When casting from floating point points, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - #[inline] - pub fn to_usize(&self) -> TypedPoint3D<usize, U> { - self.cast().unwrap() - } - - /// Cast into an `i32` point, truncating decimals if any. - /// - /// When casting from floating point points, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - #[inline] - pub fn to_i32(&self) -> TypedPoint3D<i32, U> { - self.cast().unwrap() - } - - /// Cast into an `i64` point, truncating decimals if any. - /// - /// When casting from floating point points, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - #[inline] - pub fn to_i64(&self) -> TypedPoint3D<i64, U> { - self.cast().unwrap() - } -} - -impl<T: Copy+ApproxEq<T>, U> ApproxEq<TypedPoint3D<T, U>> for TypedPoint3D<T, U> { - #[inline] - fn approx_epsilon() -> Self { - point3(T::approx_epsilon(), T::approx_epsilon(), T::approx_epsilon()) - } - - #[inline] - fn approx_eq(&self, other: &Self) -> bool { - self.x.approx_eq(&other.x) - && self.y.approx_eq(&other.y) - && self.z.approx_eq(&other.z) - } - - #[inline] - fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool { - self.x.approx_eq_eps(&other.x, &eps.x) - && self.y.approx_eq_eps(&other.y, &eps.y) - && self.z.approx_eq_eps(&other.z, &eps.z) - } -} - -impl<T: Copy, U> Into<[T; 3]> for TypedPoint3D<T, U> { - fn into(self) -> [T; 3] { - self.to_array() - } -} - -impl<T: Copy, U> From<[T; 3]> for TypedPoint3D<T, U> { - fn from(array: [T; 3]) -> Self { - point3(array[0], array[1], array[2]) - } -} - - -pub fn point2<T: Copy, U>(x: T, y: T) -> TypedPoint2D<T, U> { - TypedPoint2D::new(x, y) -} - -pub fn point3<T: Copy, U>(x: T, y: T, z: T) -> TypedPoint3D<T, U> { - TypedPoint3D::new(x, y, z) -} - -#[cfg(test)] -mod point2d { - use super::Point2D; - - #[test] - pub fn test_scalar_mul() { - let p1: Point2D<f32> = Point2D::new(3.0, 5.0); - - let result = p1 * 5.0; - - assert_eq!(result, Point2D::new(15.0, 25.0)); - } - - #[test] - pub fn test_min() { - let p1 = Point2D::new(1.0, 3.0); - let p2 = Point2D::new(2.0, 2.0); - - let result = p1.min(p2); - - assert_eq!(result, Point2D::new(1.0, 2.0)); - } - - #[test] - pub fn test_max() { - let p1 = Point2D::new(1.0, 3.0); - let p2 = Point2D::new(2.0, 2.0); - - let result = p1.max(p2); - - assert_eq!(result, Point2D::new(2.0, 3.0)); - } -} - -#[cfg(test)] -mod typedpoint2d { - use super::TypedPoint2D; - use scale_factor::ScaleFactor; - use vector::vec2; - - pub enum Mm {} - pub enum Cm {} - - pub type Point2DMm<T> = TypedPoint2D<T, Mm>; - pub type Point2DCm<T> = TypedPoint2D<T, Cm>; - - #[test] - pub fn test_add() { - let p1 = Point2DMm::new(1.0, 2.0); - let p2 = vec2(3.0, 4.0); - - let result = p1 + p2; - - assert_eq!(result, Point2DMm::new(4.0, 6.0)); - } - - #[test] - pub fn test_add_assign() { - let mut p1 = Point2DMm::new(1.0, 2.0); - p1 += vec2(3.0, 4.0); - - assert_eq!(p1, Point2DMm::new(4.0, 6.0)); - } - - #[test] - pub fn test_scalar_mul() { - let p1 = Point2DMm::new(1.0, 2.0); - let cm_per_mm: ScaleFactor<f32, Mm, Cm> = ScaleFactor::new(0.1); - - let result = p1 * cm_per_mm; - - assert_eq!(result, Point2DCm::new(0.1, 0.2)); - } - - #[test] - pub fn test_conv_vector() { - use {Point2D, point2}; - - for i in 0..100 { - // We don't care about these values as long as they are not the same. - let x = i as f32 *0.012345; - let y = i as f32 *0.987654; - let p: Point2D<f32> = point2(x, y); - assert_eq!(p.to_vector().to_point(), p); - } - } -} - -#[cfg(test)] -mod point3d { - use super::Point3D; - - #[test] - pub fn test_min() { - let p1 = Point3D::new(1.0, 3.0, 5.0); - let p2 = Point3D::new(2.0, 2.0, -1.0); - - let result = p1.min(p2); - - assert_eq!(result, Point3D::new(1.0, 2.0, -1.0)); - } - - #[test] - pub fn test_max() { - let p1 = Point3D::new(1.0, 3.0, 5.0); - let p2 = Point3D::new(2.0, 2.0, -1.0); - - let result = p1.max(p2); - - assert_eq!(result, Point3D::new(2.0, 3.0, 5.0)); - } - - #[test] - pub fn test_conv_vector() { - use point3; - for i in 0..100 { - // We don't care about these values as long as they are not the same. - let x = i as f32 *0.012345; - let y = i as f32 *0.987654; - let z = x * y; - let p: Point3D<f32> = point3(x, y, z); - assert_eq!(p.to_vector().to_point(), p); - } - } -}
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/rect.rs +++ /dev/null @@ -1,699 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use super::UnknownUnit; -use length::Length; -use scale_factor::ScaleFactor; -use num::*; -use point::TypedPoint2D; -use vector::TypedVector2D; -use size::TypedSize2D; - -use heapsize::HeapSizeOf; -use num_traits::NumCast; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::cmp::PartialOrd; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::ops::{Add, Sub, Mul, Div}; - -/// A 2d Rectangle optionally tagged with a unit. -pub struct TypedRect<T, U = UnknownUnit> { - pub origin: TypedPoint2D<T, U>, - pub size: TypedSize2D<T, U>, -} - -/// The default rectangle type with no unit. -pub type Rect<T> = TypedRect<T, UnknownUnit>; - -impl<T: HeapSizeOf, U> HeapSizeOf for TypedRect<T, U> { - fn heap_size_of_children(&self) -> usize { - self.origin.heap_size_of_children() + self.size.heap_size_of_children() - } -} - -impl<T: Copy + Deserialize, U> Deserialize for TypedRect<T, U> { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where D: Deserializer - { - let (origin, size) = try!(Deserialize::deserialize(deserializer)); - Ok(TypedRect::new(origin, size)) - } -} - -impl<T: Serialize, U> Serialize for TypedRect<T, U> { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: Serializer - { - (&self.origin, &self.size).serialize(serializer) - } -} - -impl<T: Hash, U> Hash for TypedRect<T, U> -{ - fn hash<H: Hasher>(&self, h: &mut H) { - self.origin.hash(h); - self.size.hash(h); - } -} - -impl<T: Copy, U> Copy for TypedRect<T, U> {} - -impl<T: Copy, U> Clone for TypedRect<T, U> { - fn clone(&self) -> Self { *self } -} - -impl<T: PartialEq, U> PartialEq<TypedRect<T, U>> for TypedRect<T, U> { - fn eq(&self, other: &Self) -> bool { - self.origin.eq(&other.origin) && self.size.eq(&other.size) - } -} - -impl<T: Eq, U> Eq for TypedRect<T, U> {} - -impl<T: fmt::Debug, U> fmt::Debug for TypedRect<T, U> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "TypedRect({:?} at {:?})", self.size, self.origin) - } -} - -impl<T: fmt::Display, U> fmt::Display for TypedRect<T, U> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "Rect({} at {})", self.size, self.origin) - } -} - -impl<T, U> TypedRect<T, U> { - /// Constructor. - pub fn new(origin: TypedPoint2D<T, U>, size: TypedSize2D<T, U>) -> Self { - TypedRect { - origin: origin, - size: size, - } - } -} - -impl<T, U> TypedRect<T, U> -where T: Copy + Clone + Zero + PartialOrd + PartialEq + Add<T, Output=T> + Sub<T, Output=T> { - #[inline] - pub fn intersects(&self, other: &Self) -> bool { - self.origin.x < other.origin.x + other.size.width && - other.origin.x < self.origin.x + self.size.width && - self.origin.y < other.origin.y + other.size.height && - other.origin.y < self.origin.y + self.size.height - } - - #[inline] - pub fn max_x(&self) -> T { - self.origin.x + self.size.width - } - - #[inline] - pub fn min_x(&self) -> T { - self.origin.x - } - - #[inline] - pub fn max_y(&self) -> T { - self.origin.y + self.size.height - } - - #[inline] - pub fn min_y(&self) -> T { - self.origin.y - } - - #[inline] - pub fn max_x_typed(&self) -> Length<T, U> { - Length::new(self.max_x()) - } - - #[inline] - pub fn min_x_typed(&self) -> Length<T, U> { - Length::new(self.min_x()) - } - - #[inline] - pub fn max_y_typed(&self) -> Length<T, U> { - Length::new(self.max_y()) - } - - #[inline] - pub fn min_y_typed(&self) -> Length<T, U> { - Length::new(self.min_y()) - } - - #[inline] - pub fn intersection(&self, other: &Self) -> Option<Self> { - if !self.intersects(other) { - return None; - } - - let upper_left = TypedPoint2D::new(max(self.min_x(), other.min_x()), - max(self.min_y(), other.min_y())); - let lower_right_x = min(self.max_x(), other.max_x()); - let lower_right_y = min(self.max_y(), other.max_y()); - - Some(TypedRect::new(upper_left, TypedSize2D::new(lower_right_x - upper_left.x, - lower_right_y - upper_left.y))) - } - - /// Returns the same rectangle, translated by a vector. - #[inline] - #[must_use] - pub fn translate(&self, by: &TypedVector2D<T, U>) -> Self { - Self::new(self.origin + *by, self.size) - } - - /// Returns true if this rectangle contains the point. Points are considered - /// in the rectangle if they are on the left or top edge, but outside if they - /// are on the right or bottom edge. - #[inline] - pub fn contains(&self, other: &TypedPoint2D<T, U>) -> bool { - self.origin.x <= other.x && other.x < self.origin.x + self.size.width && - self.origin.y <= other.y && other.y < self.origin.y + self.size.height - } - - /// Returns true if this rectangle contains the interior of rect. Always - /// returns true if rect is empty, and always returns false if rect is - /// nonempty but this rectangle is empty. - #[inline] - pub fn contains_rect(&self, rect: &Self) -> bool { - rect.is_empty() || - (self.min_x() <= rect.min_x() && rect.max_x() <= self.max_x() && - self.min_y() <= rect.min_y() && rect.max_y() <= self.max_y()) - } - - #[inline] - #[must_use] - pub fn inflate(&self, width: T, height: T) -> Self { - TypedRect::new( - TypedPoint2D::new(self.origin.x - width, self.origin.y - height), - TypedSize2D::new(self.size.width + width + width, self.size.height + height + height), - ) - } - - #[inline] - #[must_use] - pub fn inflate_typed(&self, width: Length<T, U>, height: Length<T, U>) -> Self { - self.inflate(width.get(), height.get()) - } - - #[inline] - pub fn top_right(&self) -> TypedPoint2D<T, U> { - TypedPoint2D::new(self.max_x(), self.origin.y) - } - - #[inline] - pub fn bottom_left(&self) -> TypedPoint2D<T, U> { - TypedPoint2D::new(self.origin.x, self.max_y()) - } - - #[inline] - pub fn bottom_right(&self) -> TypedPoint2D<T, U> { - TypedPoint2D::new(self.max_x(), self.max_y()) - } - - #[inline] - #[must_use] - pub fn translate_by_size(&self, size: &TypedSize2D<T, U>) -> Self { - self.translate(&size.to_vector()) - } - - /// Returns the smallest rectangle containing the four points. - pub fn from_points(points: &[TypedPoint2D<T, U>]) -> Self { - if points.len() == 0 { - return TypedRect::zero(); - } - let (mut min_x, mut min_y) = (points[0].x, points[0].y); - let (mut max_x, mut max_y) = (min_x, min_y); - for point in &points[1..] { - if point.x < min_x { - min_x = point.x - } - if point.x > max_x { - max_x = point.x - } - if point.y < min_y { - min_y = point.y - } - if point.y > max_y { - max_y = point.y - } - } - TypedRect::new(TypedPoint2D::new(min_x, min_y), - TypedSize2D::new(max_x - min_x, max_y - min_y)) - } -} - -impl<T, U> TypedRect<T, U> -where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> { - /// Linearly interpolate between this rectangle and another rectange. - /// - /// `t` is expected to be between zero and one. - #[inline] - pub fn lerp(&self, other: Self, t: T) -> Self { - Self::new( - self.origin.lerp(other.origin, t), - self.size.lerp(other.size, t), - ) - } -} - -impl<T, U> TypedRect<T, U> -where T: Copy + Clone + PartialOrd + Add<T, Output=T> + Sub<T, Output=T> + Zero { - #[inline] - pub fn union(&self, other: &Self) -> Self { - if self.size == Zero::zero() { - return *other; - } - if other.size == Zero::zero() { - return *self; - } - - let upper_left = TypedPoint2D::new(min(self.min_x(), other.min_x()), - min(self.min_y(), other.min_y())); - - let lower_right_x = max(self.max_x(), other.max_x()); - let lower_right_y = max(self.max_y(), other.max_y()); - - TypedRect::new( - upper_left, - TypedSize2D::new(lower_right_x - upper_left.x, lower_right_y - upper_left.y) - ) - } -} - -impl<T, U> TypedRect<T, U> { - #[inline] - pub fn scale<Scale: Copy>(&self, x: Scale, y: Scale) -> Self - where T: Copy + Clone + Mul<Scale, Output=T> { - TypedRect::new( - TypedPoint2D::new(self.origin.x * x, self.origin.y * y), - TypedSize2D::new(self.size.width * x, self.size.height * y) - ) - } -} - -impl<T: Copy + PartialEq + Zero, U> TypedRect<T, U> { - /// Constructor, setting all sides to zero. - pub fn zero() -> Self { - TypedRect::new( - TypedPoint2D::origin(), - TypedSize2D::zero(), - ) - } - - /// Returns true if the size is zero, regardless of the origin's value. - pub fn is_empty(&self) -> bool { - self.size.width == Zero::zero() || self.size.height == Zero::zero() - } -} - - -pub fn min<T: Clone + PartialOrd>(x: T, y: T) -> T { - if x <= y { x } else { y } -} - -pub fn max<T: Clone + PartialOrd>(x: T, y: T) -> T { - if x >= y { x } else { y } -} - -impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedRect<T, U> { - type Output = Self; - #[inline] - fn mul(self, scale: T) -> Self { - TypedRect::new(self.origin * scale, self.size * scale) - } -} - -impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedRect<T, U> { - type Output = Self; - #[inline] - fn div(self, scale: T) -> Self { - TypedRect::new(self.origin / scale, self.size / scale) - } -} - -impl<T: Copy + Mul<T, Output=T>, U1, U2> Mul<ScaleFactor<T, U1, U2>> for TypedRect<T, U1> { - type Output = TypedRect<T, U2>; - #[inline] - fn mul(self, scale: ScaleFactor<T, U1, U2>) -> TypedRect<T, U2> { - TypedRect::new(self.origin * scale, self.size * scale) - } -} - -impl<T: Copy + Div<T, Output=T>, U1, U2> Div<ScaleFactor<T, U1, U2>> for TypedRect<T, U2> { - type Output = TypedRect<T, U1>; - #[inline] - fn div(self, scale: ScaleFactor<T, U1, U2>) -> TypedRect<T, U1> { - TypedRect::new(self.origin / scale, self.size / scale) - } -} - -impl<T: Copy, Unit> TypedRect<T, Unit> { - /// Drop the units, preserving only the numeric value. - pub fn to_untyped(&self) -> Rect<T> { - TypedRect::new(self.origin.to_untyped(), self.size.to_untyped()) - } - - /// Tag a unitless value with units. - pub fn from_untyped(r: &Rect<T>) -> TypedRect<T, Unit> { - TypedRect::new(TypedPoint2D::from_untyped(&r.origin), TypedSize2D::from_untyped(&r.size)) - } -} - -impl<T0: NumCast + Copy, Unit> TypedRect<T0, Unit> { - /// Cast from one numeric representation to another, preserving the units. - /// - /// When casting from floating point to integer coordinates, the decimals are truncated - /// as one would expect from a simple cast, but this behavior does not always make sense - /// geometrically. Consider using round(), round_in or round_out() before casting. - pub fn cast<T1: NumCast + Copy>(&self) -> Option<TypedRect<T1, Unit>> { - match (self.origin.cast(), self.size.cast()) { - (Some(origin), Some(size)) => Some(TypedRect::new(origin, size)), - _ => None - } - } -} - -impl<T: Floor + Ceil + Round + Add<T, Output=T> + Sub<T, Output=T>, U> TypedRect<T, U> { - /// Return a rectangle with edges rounded to integer coordinates, such that - /// the returned rectangle has the same set of pixel centers as the original - /// one. - /// Edges at offset 0.5 round up. - /// Suitable for most places where integral device coordinates - /// are needed, but note that any translation should be applied first to - /// avoid pixel rounding errors. - /// Note that this is *not* rounding to nearest integer if the values are negative. - /// They are always rounding as floor(n + 0.5). - #[must_use] - pub fn round(&self) -> Self { - let origin = self.origin.round(); - let size = self.origin.add_size(&self.size).round() - origin; - TypedRect::new(origin, TypedSize2D::new(size.x, size.y)) - } - - /// Return a rectangle with edges rounded to integer coordinates, such that - /// the original rectangle contains the resulting rectangle. - #[must_use] - pub fn round_in(&self) -> Self { - let origin = self.origin.ceil(); - let size = self.origin.add_size(&self.size).floor() - origin; - TypedRect::new(origin, TypedSize2D::new(size.x, size.y)) - } - - /// Return a rectangle with edges rounded to integer coordinates, such that - /// the original rectangle is contained in the resulting rectangle. - #[must_use] - pub fn round_out(&self) -> Self { - let origin = self.origin.floor(); - let size = self.origin.add_size(&self.size).ceil() - origin; - TypedRect::new(origin, TypedSize2D::new(size.x, size.y)) - } -} - -// Convenience functions for common casts -impl<T: NumCast + Copy, Unit> TypedRect<T, Unit> { - /// Cast into an `f32` rectangle. - pub fn to_f32(&self) -> TypedRect<f32, Unit> { - self.cast().unwrap() - } - - /// Cast into an `usize` rectangle, truncating decimals if any. - /// - /// When casting from floating point rectangles, it is worth considering whether - /// to `round()`, `round_in()` or `round_out()` before the cast in order to - /// obtain the desired conversion behavior. - pub fn to_usize(&self) -> TypedRect<usize, Unit> { - self.cast().unwrap() - } - - /// Cast into an `i32` rectangle, truncating decimals if any. - /// - /// When casting from floating point rectangles, it is worth considering whether - /// to `round()`, `round_in()` or `round_out()` before the cast in order to - /// obtain the desired conversion behavior. - pub fn to_i32(&self) -> TypedRect<i32, Unit> { - self.cast().unwrap() - } - - /// Cast into an `i64` rectangle, truncating decimals if any. - /// - /// When casting from floating point rectangles, it is worth considering whether - /// to `round()`, `round_in()` or `round_out()` before the cast in order to - /// obtain the desired conversion behavior. - pub fn to_i64(&self) -> TypedRect<i64, Unit> { - self.cast().unwrap() - } -} - -/// Shorthand for `TypedRect::new(TypedPoint2D::new(x, y), TypedSize2D::new(w, h))`. -pub fn rect<T: Copy, U>(x: T, y: T, w: T, h: T) -> TypedRect<T, U> { - TypedRect::new(TypedPoint2D::new(x, y), TypedSize2D::new(w, h)) -} - -#[cfg(test)] -mod tests { - use point::Point2D; - use vector::vec2; - use size::Size2D; - use super::*; - - #[test] - fn test_min_max() { - assert!(min(0u32, 1u32) == 0u32); - assert!(min(-1.0f32, 0.0f32) == -1.0f32); - - assert!(max(0u32, 1u32) == 1u32); - assert!(max(-1.0f32, 0.0f32) == 0.0f32); - } - - #[test] - fn test_translate() { - let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32)); - let pp = p.translate(&vec2(10,15)); - - assert!(pp.size.width == 50); - assert!(pp.size.height == 40); - assert!(pp.origin.x == 10); - assert!(pp.origin.y == 15); - - - let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40)); - let rr = r.translate(&vec2(0,-10)); - - assert!(rr.size.width == 50); - assert!(rr.size.height == 40); - assert!(rr.origin.x == -10); - assert!(rr.origin.y == -15); - } - - #[test] - fn test_translate_by_size() { - let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32)); - let pp = p.translate_by_size(&Size2D::new(10,15)); - - assert!(pp.size.width == 50); - assert!(pp.size.height == 40); - assert!(pp.origin.x == 10); - assert!(pp.origin.y == 15); - - - let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40)); - let rr = r.translate_by_size(&Size2D::new(0,-10)); - - assert!(rr.size.width == 50); - assert!(rr.size.height == 40); - assert!(rr.origin.x == -10); - assert!(rr.origin.y == -15); - } - - #[test] - fn test_union() { - let p = Rect::new(Point2D::new(0, 0), Size2D::new(50, 40)); - let q = Rect::new(Point2D::new(20,20), Size2D::new(5, 5)); - let r = Rect::new(Point2D::new(-15, -30), Size2D::new(200, 15)); - let s = Rect::new(Point2D::new(20, -15), Size2D::new(250, 200)); - - let pq = p.union(&q); - assert!(pq.origin == Point2D::new(0, 0)); - assert!(pq.size == Size2D::new(50, 40)); - - let pr = p.union(&r); - assert!(pr.origin == Point2D::new(-15, -30)); - assert!(pr.size == Size2D::new(200, 70)); - - let ps = p.union(&s); - assert!(ps.origin == Point2D::new(0, -15)); - assert!(ps.size == Size2D::new(270, 200)); - - } - - #[test] - fn test_intersection() { - let p = Rect::new(Point2D::new(0, 0), Size2D::new(10, 20)); - let q = Rect::new(Point2D::new(5, 15), Size2D::new(10, 10)); - let r = Rect::new(Point2D::new(-5, -5), Size2D::new(8, 8)); - - let pq = p.intersection(&q); - assert!(pq.is_some()); - let pq = pq.unwrap(); - assert!(pq.origin == Point2D::new(5, 15)); - assert!(pq.size == Size2D::new(5, 5)); - - let pr = p.intersection(&r); - assert!(pr.is_some()); - let pr = pr.unwrap(); - assert!(pr.origin == Point2D::new(0, 0)); - assert!(pr.size == Size2D::new(3, 3)); - - let qr = q.intersection(&r); - assert!(qr.is_none()); - } - - #[test] - fn test_contains() { - let r = Rect::new(Point2D::new(-20, 15), Size2D::new(100, 200)); - - assert!(r.contains(&Point2D::new(0, 50))); - assert!(r.contains(&Point2D::new(-10, 200))); - - // The `contains` method is inclusive of the top/left edges, but not the - // bottom/right edges. - assert!(r.contains(&Point2D::new(-20, 15))); - assert!(!r.contains(&Point2D::new(80, 15))); - assert!(!r.contains(&Point2D::new(80, 215))); - assert!(!r.contains(&Point2D::new(-20, 215))); - - // Points beyond the top-left corner. - assert!(!r.contains(&Point2D::new(-25, 15))); - assert!(!r.contains(&Point2D::new(-15, 10))); - - // Points beyond the top-right corner. - assert!(!r.contains(&Point2D::new(85, 20))); - assert!(!r.contains(&Point2D::new(75, 10))); - - // Points beyond the bottom-right corner. - assert!(!r.contains(&Point2D::new(85, 210))); - assert!(!r.contains(&Point2D::new(75, 220))); - - // Points beyond the bottom-left corner. - assert!(!r.contains(&Point2D::new(-25, 210))); - assert!(!r.contains(&Point2D::new(-15, 220))); - - let r = Rect::new(Point2D::new(-20.0, 15.0), Size2D::new(100.0, 200.0)); - assert!(r.contains_rect(&r)); - assert!(!r.contains_rect(&r.translate(&vec2( 0.1, 0.0)))); - assert!(!r.contains_rect(&r.translate(&vec2(-0.1, 0.0)))); - assert!(!r.contains_rect(&r.translate(&vec2( 0.0, 0.1)))); - assert!(!r.contains_rect(&r.translate(&vec2( 0.0, -0.1)))); - // Empty rectangles are always considered as contained in other rectangles, - // even if their origin is not. - let p = Point2D::new(1.0, 1.0); - assert!(!r.contains(&p)); - assert!(r.contains_rect(&Rect::new(p, Size2D::zero()))); - } - - #[test] - fn test_scale() { - let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32)); - let pp = p.scale(10, 15); - - assert!(pp.size.width == 500); - assert!(pp.size.height == 600); - assert!(pp.origin.x == 0); - assert!(pp.origin.y == 0); - - let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40)); - let rr = r.scale(1, 20); - - assert!(rr.size.width == 50); - assert!(rr.size.height == 800); - assert!(rr.origin.x == -10); - assert!(rr.origin.y == -100); - } - - #[test] - fn test_inflate() { - let p = Rect::new(Point2D::new(0, 0), Size2D::new(10, 10)); - let pp = p.inflate(10, 20); - - assert!(pp.size.width == 30); - assert!(pp.size.height == 50); - assert!(pp.origin.x == -10); - assert!(pp.origin.y == -20); - - let r = Rect::new(Point2D::new(0, 0), Size2D::new(10, 20)); - let rr = r.inflate(-2, -5); - - assert!(rr.size.width == 6); - assert!(rr.size.height == 10); - assert!(rr.origin.x == 2); - assert!(rr.origin.y == 5); - } - - #[test] - fn test_min_max_x_y() { - let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32)); - assert!(p.max_y() == 40); - assert!(p.min_y() == 0); - assert!(p.max_x() == 50); - assert!(p.min_x() == 0); - - let r = Rect::new(Point2D::new(-10, -5), Size2D::new(50, 40)); - assert!(r.max_y() == 35); - assert!(r.min_y() == -5); - assert!(r.max_x() == 40); - assert!(r.min_x() == -10); - } - - #[test] - fn test_is_empty() { - assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(0u32, 0u32)).is_empty()); - assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(10u32, 0u32)).is_empty()); - assert!(Rect::new(Point2D::new(0u32, 0u32), Size2D::new(0u32, 10u32)).is_empty()); - assert!(!Rect::new(Point2D::new(0u32, 0u32), Size2D::new(1u32, 1u32)).is_empty()); - assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(0u32, 0u32)).is_empty()); - assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(10u32, 0u32)).is_empty()); - assert!(Rect::new(Point2D::new(10u32, 10u32), Size2D::new(0u32, 10u32)).is_empty()); - assert!(!Rect::new(Point2D::new(10u32, 10u32), Size2D::new(1u32, 1u32)).is_empty()); - } - - #[test] - fn test_round() { - let mut x = -2.0; - let mut y = -2.0; - let mut w = -2.0; - let mut h = -2.0; - while x < 2.0 { - while y < 2.0 { - while w < 2.0 { - while h < 2.0 { - let rect = Rect::new(Point2D::new(x, y), Size2D::new(w, h)); - - assert!(rect.contains_rect(&rect.round_in())); - assert!(rect.round_in().inflate(1.0, 1.0).contains_rect(&rect)); - - assert!(rect.round_out().contains_rect(&rect)); - assert!(rect.inflate(1.0, 1.0).contains_rect(&rect.round_out())); - - assert!(rect.inflate(1.0, 1.0).contains_rect(&rect.round())); - assert!(rect.round().inflate(1.0, 1.0).contains_rect(&rect)); - - h += 0.1; - } - w += 0.1; - } - y += 0.1; - } - x += 0.1 - } - } -}
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/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::ScaleFactor; -/// use euclid::Length; -/// enum Mm {}; -/// enum Inch {}; -/// -/// let mm_per_inch: ScaleFactor<f32, Inch, Mm> = ScaleFactor::new(25.4); -/// -/// let one_foot: Length<f32, Inch> = Length::new(12.0); -/// let one_foot_in_mm: Length<f32, Mm> = one_foot * mm_per_inch; -/// ``` -#[repr(C)] -pub struct ScaleFactor<T, Src, Dst>(pub T, PhantomData<(Src, Dst)>); - -impl<T: HeapSizeOf, Src, Dst> HeapSizeOf for ScaleFactor<T, Src, Dst> { - fn heap_size_of_children(&self) -> usize { - self.0.heap_size_of_children() - } -} - -impl<T, Src, Dst> Deserialize for ScaleFactor<T, Src, Dst> where T: Deserialize { - fn deserialize<D>(deserializer: D) -> Result<ScaleFactor<T, Src, Dst>, D::Error> - where D: Deserializer { - Ok(ScaleFactor(try!(Deserialize::deserialize(deserializer)), PhantomData)) - } -} - -impl<T, Src, Dst> Serialize for ScaleFactor<T, Src, Dst> where T: Serialize { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { - self.0.serialize(serializer) - } -} - -impl<T, Src, Dst> ScaleFactor<T, Src, Dst> { - pub fn new(x: T) -> ScaleFactor<T, Src, Dst> { - ScaleFactor(x, PhantomData) - } -} - -impl<T: Clone, Src, Dst> ScaleFactor<T, Src, Dst> { - pub fn get(&self) -> T { - self.0.clone() - } -} - -impl<T: Clone + One + Div<T, Output=T>, Src, Dst> ScaleFactor<T, Src, Dst> { - /// The inverse ScaleFactor (1.0 / self). - pub fn inv(&self) -> ScaleFactor<T, Dst, Src> { - let one: T = One::one(); - ScaleFactor::new(one / self.get()) - } -} - -// scale0 * scale1 -impl<T: Clone + Mul<T, Output=T>, A, B, C> -Mul<ScaleFactor<T, B, C>> for ScaleFactor<T, A, B> { - type Output = ScaleFactor<T, A, C>; - #[inline] - fn mul(self, other: ScaleFactor<T, B, C>) -> ScaleFactor<T, A, C> { - ScaleFactor::new(self.get() * other.get()) - } -} - -// scale0 + scale1 -impl<T: Clone + Add<T, Output=T>, Src, Dst> Add for ScaleFactor<T, Src, Dst> { - type Output = ScaleFactor<T, Src, Dst>; - #[inline] - fn add(self, other: ScaleFactor<T, Src, Dst>) -> ScaleFactor<T, Src, Dst> { - ScaleFactor::new(self.get() + other.get()) - } -} - -// scale0 - scale1 -impl<T: Clone + Sub<T, Output=T>, Src, Dst> Sub for ScaleFactor<T, Src, Dst> { - type Output = ScaleFactor<T, Src, Dst>; - #[inline] - fn sub(self, other: ScaleFactor<T, Src, Dst>) -> ScaleFactor<T, Src, Dst> { - ScaleFactor::new(self.get() - other.get()) - } -} - -impl<T: NumCast + Clone, Src, Dst0> ScaleFactor<T, Src, Dst0> { - /// Cast from one numeric representation to another, preserving the units. - pub fn cast<T1: NumCast + Clone>(&self) -> Option<ScaleFactor<T1, Src, Dst0>> { - NumCast::from(self.get()).map(ScaleFactor::new) - } -} - -// FIXME: Switch to `derive(PartialEq, Clone)` after this Rust issue is fixed: -// https://github.com/mozilla/rust/issues/7671 - -impl<T: PartialEq, Src, Dst> PartialEq for ScaleFactor<T, Src, Dst> { - fn eq(&self, other: &ScaleFactor<T, Src, Dst>) -> bool { - self.0 == other.0 - } -} - -impl<T: Clone, Src, Dst> Clone for ScaleFactor<T, Src, Dst> { - fn clone(&self) -> ScaleFactor<T, Src, Dst> { - ScaleFactor::new(self.get()) - } -} - -impl<T: Copy, Src, Dst> Copy for ScaleFactor<T, Src, Dst> {} - -impl<T: fmt::Debug, Src, Dst> fmt::Debug for ScaleFactor<T, Src, Dst> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.0.fmt(f) - } -} - -impl<T: fmt::Display, Src, Dst> fmt::Display for ScaleFactor<T, Src, Dst> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.0.fmt(f) - } -} - -#[cfg(test)] -mod tests { - use super::ScaleFactor; - - enum Inch {} - enum Cm {} - enum Mm {} - - #[test] - fn test_scale_factor() { - let mm_per_inch: ScaleFactor<f32, Inch, Mm> = ScaleFactor::new(25.4); - let cm_per_mm: ScaleFactor<f32, Mm, Cm> = ScaleFactor::new(0.1); - - let mm_per_cm: ScaleFactor<f32, Cm, Mm> = cm_per_mm.inv(); - assert_eq!(mm_per_cm.get(), 10.0); - - let cm_per_inch: ScaleFactor<f32, Inch, Cm> = mm_per_inch * cm_per_mm; - assert_eq!(cm_per_inch, ScaleFactor::new(2.54)); - - let a: ScaleFactor<isize, Inch, Inch> = ScaleFactor::new(2); - let b: ScaleFactor<isize, Inch, Inch> = ScaleFactor::new(3); - assert!(a != b); - assert_eq!(a, a.clone()); - assert_eq!(a.clone() + b.clone(), ScaleFactor::new(5)); - assert_eq!(a - b, ScaleFactor::new(-1)); - } -}
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/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) -> Self { - TypedSideOffsets2D { - top: top, - right: right, - bottom: bottom, - left: left, - _unit: PhantomData, - } - } - - /// Constructor taking a typed Length for each side. - pub fn from_lengths(top: Length<T, U>, - right: Length<T, U>, - bottom: Length<T, U>, - left: Length<T, U>) -> Self { - TypedSideOffsets2D::new(top.0, right.0, bottom.0, left.0) - } - - /// Access self.top as a typed Length instead of a scalar value. - pub fn top_typed(&self) -> Length<T, U> { Length::new(self.top) } - - /// Access self.right as a typed Length instead of a scalar value. - pub fn right_typed(&self) -> Length<T, U> { Length::new(self.right) } - - /// Access self.bottom as a typed Length instead of a scalar value. - pub fn bottom_typed(&self) -> Length<T, U> { Length::new(self.bottom) } - - /// Access self.left as a typed Length instead of a scalar value. - pub fn left_typed(&self) -> Length<T, U> { Length::new(self.left) } - - /// Constructor setting the same value to all sides, taking a scalar value directly. - pub fn new_all_same(all: T) -> Self { - TypedSideOffsets2D::new(all, all, all, all) - } - - /// Constructor setting the same value to all sides, taking a typed Length. - pub fn from_length_all_same(all: Length<T, U>) -> Self { - TypedSideOffsets2D::new_all_same(all.0) - } -} - -impl<T, U> TypedSideOffsets2D<T, U> where T: Add<T, Output=T> + Copy { - pub fn horizontal(&self) -> T { - self.left + self.right - } - - pub fn vertical(&self) -> T { - self.top + self.bottom - } - - pub fn horizontal_typed(&self) -> Length<T, U> { - Length::new(self.horizontal()) - } - - pub fn vertical_typed(&self) -> Length<T, U> { - Length::new(self.vertical()) - } -} - -impl<T, U> Add for TypedSideOffsets2D<T, U> where T : Copy + Add<T, Output=T> { - type Output = Self; - fn add(self, other: Self) -> Self { - TypedSideOffsets2D::new( - self.top + other.top, - self.right + other.right, - self.bottom + other.bottom, - self.left + other.left, - ) - } -} - -impl<T: Copy + Zero, U> TypedSideOffsets2D<T, U> { - /// Constructor, setting all sides to zero. - pub fn zero() -> Self { - TypedSideOffsets2D::new( - Zero::zero(), - Zero::zero(), - Zero::zero(), - Zero::zero(), - ) - } -} - -/// A SIMD enabled version of TypedSideOffsets2D specialized for i32. -#[cfg(feature = "unstable")] -#[derive(Clone, Copy, PartialEq)] -#[repr(simd)] -pub struct SideOffsets2DSimdI32 { - pub top: i32, - pub bottom: i32, - pub right: i32, - pub left: i32, -} - -#[cfg(feature = "unstable")] -impl HeapSizeOf for SideOffsets2DSimdI32 { - fn heap_size_of_children(&self) -> usize { 0 } -} - -#[cfg(feature = "unstable")] -impl SideOffsets2DSimdI32 { - #[inline] - pub fn new(top: i32, right: i32, bottom: i32, left: i32) -> SideOffsets2DSimdI32 { - SideOffsets2DSimdI32 { - top: top, - bottom: bottom, - right: right, - left: left, - } - } -} - -#[cfg(feature = "unstable")] -impl SideOffsets2DSimdI32 { - #[inline] - pub fn new_all_same(all: i32) -> SideOffsets2DSimdI32 { - SideOffsets2DSimdI32::new(all.clone(), all.clone(), all.clone(), all.clone()) - } -} - -#[cfg(feature = "unstable")] -impl SideOffsets2DSimdI32 { - #[inline] - pub fn horizontal(&self) -> i32 { - self.left + self.right - } - - #[inline] - pub fn vertical(&self) -> i32 { - self.top + self.bottom - } -} - -/*impl Add for SideOffsets2DSimdI32 { - type Output = SideOffsets2DSimdI32; - #[inline] - fn add(self, other: SideOffsets2DSimdI32) -> SideOffsets2DSimdI32 { - self + other // Use SIMD addition - } -}*/ - -#[cfg(feature = "unstable")] -impl SideOffsets2DSimdI32 { - #[inline] - pub fn zero() -> SideOffsets2DSimdI32 { - SideOffsets2DSimdI32 { - top: 0, - bottom: 0, - right: 0, - left: 0, - } - } - - #[cfg(not(target_arch = "x86_64"))] - #[inline] - pub fn is_zero(&self) -> bool { - self.top == 0 && self.right == 0 && self.bottom == 0 && self.left == 0 - } - - #[cfg(target_arch = "x86_64")] - #[inline] - pub fn is_zero(&self) -> bool { - let is_zero: bool; - unsafe { - asm! { - "ptest $1, $1 - setz $0" - : "=r"(is_zero) - : "x"(*self) - : - : "intel" - }; - } - is_zero - } -} - -#[cfg(feature = "unstable")] -#[cfg(test)] -mod tests { - use super::SideOffsets2DSimdI32; - - #[test] - fn test_is_zero() { - assert!(SideOffsets2DSimdI32::new_all_same(0).is_zero()); - assert!(!SideOffsets2DSimdI32::new_all_same(1).is_zero()); - assert!(!SideOffsets2DSimdI32::new(1, 0, 0, 0).is_zero()); - assert!(!SideOffsets2DSimdI32::new(0, 1, 0, 0).is_zero()); - assert!(!SideOffsets2DSimdI32::new(0, 0, 1, 0).is_zero()); - assert!(!SideOffsets2DSimdI32::new(0, 0, 0, 1).is_zero()); - } -} - -#[cfg(feature = "unstable")] -#[cfg(bench)] -mod bench { - use test::BenchHarness; - use std::num::Zero; - use rand::{XorShiftRng, Rng}; - use super::SideOffsets2DSimdI32; - - #[cfg(target_arch = "x86")] - #[cfg(target_arch = "x86_64")] - #[bench] - fn bench_naive_is_zero(bh: &mut BenchHarness) { - fn is_zero(x: &SideOffsets2DSimdI32) -> bool { - x.top.is_zero() && x.right.is_zero() && x.bottom.is_zero() && x.left.is_zero() - } - let mut rng = XorShiftRng::new().unwrap(); - bh.iter(|| is_zero(&rng.gen::<SideOffsets2DSimdI32>())) - } - - #[bench] - fn bench_is_zero(bh: &mut BenchHarness) { - let mut rng = XorShiftRng::new().unwrap(); - bh.iter(|| rng.gen::<SideOffsets2DSimdI32>().is_zero()) - } - - #[bench] - fn bench_naive_add(bh: &mut BenchHarness) { - fn add(x: &SideOffsets2DSimdI32, y: &SideOffsets2DSimdI32) -> SideOffsets2DSimdI32 { - SideOffsets2DSimdI32 { - top: x.top + y.top, - right: x.right + y.right, - bottom: x.bottom + y.bottom, - left: x.left + y.left, - } - } - let mut rng = XorShiftRng::new().unwrap(); - bh.iter(|| add(&rng.gen::<SideOffsets2DSimdI32>(), &rng.gen::<SideOffsets2DSimdI32>())) - } - - #[bench] - fn bench_add(bh: &mut BenchHarness) { - let mut rng = XorShiftRng::new().unwrap(); - bh.iter(|| rng.gen::<SideOffsets2DSimdI32>() + rng.gen::<SideOffsets2DSimdI32>()) - } -}
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/size.rs +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use super::UnknownUnit; -use length::Length; -use scale_factor::ScaleFactor; -use vector::{TypedVector2D, vec2}; -use num::*; - -use num_traits::NumCast; -use std::fmt; -use std::ops::{Add, Div, Mul, Sub}; -use std::marker::PhantomData; - -/// A 2d size tagged with a unit. -define_matrix! { - pub struct TypedSize2D<T, U> { - pub width: T, - pub height: T, - } -} - -/// Default 2d size type with no unit. -/// -/// `Size2D` provides the same methods as `TypedSize2D`. -pub type Size2D<T> = TypedSize2D<T, UnknownUnit>; - -impl<T: fmt::Debug, U> fmt::Debug for TypedSize2D<T, U> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}×{:?}", self.width, self.height) - } -} - -impl<T: fmt::Display, U> fmt::Display for TypedSize2D<T, U> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "({}x{})", self.width, self.height) - } -} - -impl<T, U> TypedSize2D<T, U> { - /// Constructor taking scalar values. - pub fn new(width: T, height: T) -> Self { - TypedSize2D { - width: width, - height: height, - _unit: PhantomData, - } - } -} - -impl<T: Clone, U> TypedSize2D<T, U> { - /// Constructor taking scalar strongly typed lengths. - pub fn from_lengths(width: Length<T, U>, height: Length<T, U>) -> Self { - TypedSize2D::new(width.get(), height.get()) - } -} - -impl<T: Round, U> TypedSize2D<T, U> { - /// Rounds each component to the nearest integer value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - pub fn round(&self) -> Self { - TypedSize2D::new(self.width.round(), self.height.round()) - } -} - -impl<T: Ceil, U> TypedSize2D<T, U> { - /// Rounds each component to the smallest integer equal or greater than the original value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - pub fn ceil(&self) -> Self { - TypedSize2D::new(self.width.ceil(), self.height.ceil()) - } -} - -impl<T: Floor, U> TypedSize2D<T, U> { - /// Rounds each component to the biggest integer equal or lower than the original value. - /// - /// This behavior is preserved for negative values (unlike the basic cast). - pub fn floor(&self) -> Self { - TypedSize2D::new(self.width.floor(), self.height.floor()) - } -} - -impl<T: Copy + Add<T, Output=T>, U> Add for TypedSize2D<T, U> { - type Output = Self; - fn add(self, other: Self) -> Self { - TypedSize2D::new(self.width + other.width, self.height + other.height) - } -} - -impl<T: Copy + Sub<T, Output=T>, U> Sub for TypedSize2D<T, U> { - type Output = Self; - fn sub(self, other: Self) -> Self { - TypedSize2D::new(self.width - other.width, self.height - other.height) - } -} - -impl<T: Copy + Clone + Mul<T, Output=U>, U> TypedSize2D<T, U> { - pub fn area(&self) -> U { self.width * self.height } -} - -impl<T, U> TypedSize2D<T, U> -where T: Copy + One + Add<Output=T> + Sub<Output=T> + Mul<Output=T> { - /// Linearly interpolate between this size and another size. - /// - /// `t` is expected to be between zero and one. - #[inline] - pub fn lerp(&self, other: Self, t: T) -> Self { - let one_t = T::one() - t; - size2( - one_t * self.width + t * other.width, - one_t * self.height + t * other.height, - ) - } -} - -impl<T: Zero, U> TypedSize2D<T, U> { - pub fn zero() -> Self { - TypedSize2D::new( - Zero::zero(), - Zero::zero(), - ) - } -} - -impl<T: Zero, U> Zero for TypedSize2D<T, U> { - fn zero() -> Self { - TypedSize2D::new( - Zero::zero(), - Zero::zero(), - ) - } -} - -impl<T: Copy + Mul<T, Output=T>, U> Mul<T> for TypedSize2D<T, U> { - type Output = Self; - #[inline] - fn mul(self, scale: T) -> Self { - TypedSize2D::new(self.width * scale, self.height * scale) - } -} - -impl<T: Copy + Div<T, Output=T>, U> Div<T> for TypedSize2D<T, U> { - type Output = Self; - #[inline] - fn div(self, scale: T) -> Self { - TypedSize2D::new(self.width / scale, self.height / scale) - } -} - -impl<T: Copy + Mul<T, Output=T>, U1, U2> Mul<ScaleFactor<T, U1, U2>> for TypedSize2D<T, U1> { - type Output = TypedSize2D<T, U2>; - #[inline] - fn mul(self, scale: ScaleFactor<T, U1, U2>) -> TypedSize2D<T, U2> { - TypedSize2D::new(self.width * scale.get(), self.height * scale.get()) - } -} - -impl<T: Copy + Div<T, Output=T>, U1, U2> Div<ScaleFactor<T, U1, U2>> for TypedSize2D<T, U2> { - type Output = TypedSize2D<T, U1>; - #[inline] - fn div(self, scale: ScaleFactor<T, U1, U2>) -> TypedSize2D<T, U1> { - TypedSize2D::new(self.width / scale.get(), self.height / scale.get()) - } -} - -impl<T: Copy, U> TypedSize2D<T, U> { - /// Returns self.width as a Length carrying the unit. - #[inline] - pub fn width_typed(&self) -> Length<T, U> { Length::new(self.width) } - - /// Returns self.height as a Length carrying the unit. - #[inline] - pub fn height_typed(&self) -> Length<T, U> { Length::new(self.height) } - - #[inline] - pub fn to_array(&self) -> [T; 2] { [self.width, self.height] } - - #[inline] - pub fn to_vector(&self) -> TypedVector2D<T, U> { vec2(self.width, self.height) } - - /// Drop the units, preserving only the numeric value. - pub fn to_untyped(&self) -> Size2D<T> { - TypedSize2D::new(self.width, self.height) - } - - /// Tag a unitless value with units. - pub fn from_untyped(p: &Size2D<T>) -> Self { - TypedSize2D::new(p.width, p.height) - } -} - -impl<T: NumCast + Copy, Unit> TypedSize2D<T, Unit> { - /// Cast from one numeric representation to another, preserving the units. - /// - /// When casting from floating point to integer coordinates, the decimals are truncated - /// as one would expect from a simple cast, but this behavior does not always make sense - /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting. - pub fn cast<NewT: NumCast + Copy>(&self) -> Option<TypedSize2D<NewT, Unit>> { - match (NumCast::from(self.width), NumCast::from(self.height)) { - (Some(w), Some(h)) => Some(TypedSize2D::new(w, h)), - _ => None - } - } - - // Convenience functions for common casts - - /// Cast into an `f32` size. - pub fn to_f32(&self) -> TypedSize2D<f32, Unit> { - self.cast().unwrap() - } - - /// Cast into an `uint` size, truncating decimals if any. - /// - /// When casting from floating point sizes, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - pub fn to_usize(&self) -> TypedSize2D<usize, Unit> { - self.cast().unwrap() - } - - /// Cast into an `i32` size, truncating decimals if any. - /// - /// When casting from floating point sizes, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - pub fn to_i32(&self) -> TypedSize2D<i32, Unit> { - self.cast().unwrap() - } - - /// Cast into an `i64` size, truncating decimals if any. - /// - /// When casting from floating point sizes, it is worth considering whether - /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain - /// the desired conversion behavior. - pub fn to_i64(&self) -> TypedSize2D<i64, Unit> { - self.cast().unwrap() - } -} - -/// Shorthand for `TypedSize2D::new(w, h)`. -pub fn size2<T, U>(w: T, h: T) -> TypedSize2D<T, U> { - TypedSize2D::new(w, h) -} - -#[cfg(test)] -mod size2d { - use super::Size2D; - - #[test] - pub fn test_add() { - let p1 = Size2D::new(1.0, 2.0); - let p2 = Size2D::new(3.0, 4.0); - assert_eq!(p1 + p2, Size2D::new(4.0, 6.0)); - - let p1 = Size2D::new(1.0, 2.0); - let p2 = Size2D::new(0.0, 0.0); - assert_eq!(p1 + p2, Size2D::new(1.0, 2.0)); - - let p1 = Size2D::new(1.0, 2.0); - let p2 = Size2D::new(-3.0, -4.0); - assert_eq!(p1 + p2, Size2D::new(-2.0, -2.0)); - - let p1 = Size2D::new(0.0, 0.0); - let p2 = Size2D::new(0.0, 0.0); - assert_eq!(p1 + p2, Size2D::new(0.0, 0.0)); - } - - #[test] - pub fn test_sub() { - let p1 = Size2D::new(1.0, 2.0); - let p2 = Size2D::new(3.0, 4.0); - assert_eq!(p1 - p2, Size2D::new(-2.0, -2.0)); - - let p1 = Size2D::new(1.0, 2.0); - let p2 = Size2D::new(0.0, 0.0); - assert_eq!(p1 - p2, Size2D::new(1.0, 2.0)); - - let p1 = Size2D::new(1.0, 2.0); - let p2 = Size2D::new(-3.0, -4.0); - assert_eq!(p1 - p2, Size2D::new(4.0, 6.0)); - - let p1 = Size2D::new(0.0, 0.0); - let p2 = Size2D::new(0.0, 0.0); - assert_eq!(p1 - p2, Size2D::new(0.0, 0.0)); - } -}
deleted file mode 100644 --- a/third_party/rust/euclid-0.14.4/src/transform2d.rs +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use super::{UnknownUnit, Radians}; -use num::{One, Zero}; -use point::TypedPoint2D; -use vector::{TypedVector2D, vec2}; -use rect::TypedRect; -use std::ops::{Add, Mul, Div, Sub}; -use std::marker::PhantomData; -use approxeq::ApproxEq; -use trig::Trig; -use std::fmt; - -define_matrix! { - /// A 2d transform stored as a 2 by 3 matrix in row-major order in memory. - /// - /// Transforms can be parametrized over the source and destination units, to describe a - /// transformation from a space to another. - /// For example, `TypedTransform2D<f32, WordSpace, ScreenSpace>::transform_point4d` - /// takes a `TypedPoint2D<f32, WordSpace>` and returns a `TypedPoint2D<f32, ScreenSpace>`. - /// - /// Transforms expose a set of convenience methods for pre- and post-transformations. - /// A pre-transformation corresponds to adding an operation that is applied before - /// the rest of the transformation, while a post-transformation adds an operation - /// that is applied after. - pub struct TypedTransform2D<T, Src, Dst> { - pub m11: T, pub m12: T, - pub m21: T, pub m22: T, - pub m31: T, pub m32: T, - } -} - -/// The default 2d transform type with no units. -pub type Transform2D<T> = TypedTransform2D<T, UnknownUnit, UnknownUnit>; - -impl<T: Copy, Src, Dst> TypedTransform2D<T, Src, Dst> { - /// Create a transform specifying its matrix elements in row-major order. - pub fn row_major(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> Self { - TypedTransform2D { - m11: m11, m12: m12, - m21: m21, m22: m22, - m31: m31, m32: m32, - _unit: PhantomData, - } - } - - /// Create a transform specifying its matrix elements in column-major order. - pub fn column_major(m11: T, m21: T, m31: T, m12: T, m22: T, m32: T) -> Self { - TypedTransform2D { - m11: m11, m12: m12, - m21: m21, m22: m22, - m31: m31, m32: m32, - _unit: PhantomData, - } - } - - /// Returns an array containing this transform's terms in row-major order (the order - /// in which the transform is actually laid out in memory). - pub fn to_row_major_array(&self) -> [T; 6] { - [ - self.m11, self.m12, - self.m21, self.m22, - self.m31, self.m32 - ] - }