No bug - Revendor rust dependencies

This commit is contained in:
Servo VCS Sync 2018-04-02 15:33:49 +00:00
parent f846d0809d
commit e5c8a31abf
19 changed files with 0 additions and 1876 deletions

27
Cargo.lock generated
View File

@ -819,19 +819,6 @@ dependencies = [
"url 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "hyper_serde"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)",
"mime 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.35 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.38 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ident_case"
version = "1.0.0"
@ -979,14 +966,10 @@ dependencies = [
"cssparser 0.23.2 (registry+https://github.com/rust-lang/crates.io-index)",
"euclid 0.17.2 (registry+https://github.com/rust-lang/crates.io-index)",
"hashglobe 0.1.0",
"hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)",
"hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"selectors 0.19.0",
"serde 1.0.35 (registry+https://github.com/rust-lang/crates.io-index)",
"servo_arc 0.1.1",
"smallbitvec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
"smallvec 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.38 (registry+https://github.com/rust-lang/crates.io-index)",
"void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -1591,14 +1574,6 @@ dependencies = [
"serde_derive 1.0.35 (git+https://github.com/servo/serde?branch=deserialize_from_enums5)",
]
[[package]]
name = "serde_bytes"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"serde 1.0.35 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "serde_derive"
version = "1.0.35"
@ -2319,7 +2294,6 @@ dependencies = [
"checksum httparse 1.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "af2f2dd97457e8fb1ae7c5a420db346af389926e36f43768b96f101546b04a07"
"checksum humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0484fda3e7007f2a4a0d9c3a703ca38c71c54c55602ce4660c419fd32e188c9e"
"checksum hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)" = "368cb56b2740ebf4230520e2b90ebb0461e69034d85d1945febd9b3971426db2"
"checksum hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0997ad463f64ce6ba02cf5af320622bb9782e4f8355b650a2cc7ccca69a7cc2e"
"checksum ident_case 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c9826188e666f2ed92071d2dadef6edc430b11b158b5b2b3f4babbcc891eaaa"
"checksum idna 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "014b298351066f1512874135335d62a789ffe78a9974f94b43ed5621951eaf7d"
"checksum iovec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "29d062ee61fccdf25be172e70f34c9f6efc597e1fb8f6526e8437b2046ab26be"
@ -2394,7 +2368,6 @@ dependencies = [
"checksum semver 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a3186ec9e65071a2095434b1f5bb24838d4e8e130f584c790f6033c79943537"
"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
"checksum serde 1.0.35 (registry+https://github.com/rust-lang/crates.io-index)" = "800fdb0a894572994f3970035a8a5f65d8ec2cd40e6cdf7d8cd9001d7b30648e"
"checksum serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)" = "adb6e51a6b3696b301bc221d785f898b4457c619b51d7ce195a6d20baecb37b3"
"checksum serde_derive 1.0.35 (git+https://github.com/servo/serde?branch=deserialize_from_enums5)" = "<none>"
"checksum serde_derive_internals 0.22.1 (git+https://github.com/servo/serde?branch=deserialize_from_enums5)" = "<none>"
"checksum simd 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3dd0805c7363ab51a829a1511ad24b6ed0349feaa756c4bc2f977f9f496e6673"

View File

@ -1 +0,0 @@
{"files":{".travis.yml":"bdb52df624876cdf4a9214bb2a81cefcf7ed7176b7213045846a68ead3a5c56f","Cargo.toml":"5d897604ce6935387b66cb58cbd15af0fbf70a6f9aa18dc5a524d92946cb4fcb","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"d5b3226768e22b6dd11270c92e1e4bab9acdfa7e5b2fc1efaddcf3fbf00aff05","README.md":"e4d2cfe8f354ea78d25b51d817ed172c8569b434badaec74b4e8551f30be01e9","bors.toml":"1d8a7a56c5c76925a3daa8c50a40cc82cbfc638f521f864106bd60b1e8a219a2","rustfmt.toml":"cad0c47fc0d3c55c5c2144efc4935f830bf720190267c416b9ee484ebbc3604d","src/lib.rs":"1d58d926c22e1027f0037609176361b19a9693d582f9e5349440eebd72d62d79","tests/supported.rs":"29912bd33d6b6ea0b8985f23b75af4ef4419017ce5cd4b3bc1fc8349af2e0952","tests/tokens.rs":"d7effb9466553820a65bee2ed250c93d60cffe7065fdf6d389e967ef80297efc"},"package":"0997ad463f64ce6ba02cf5af320622bb9782e4f8355b650a2cc7ccca69a7cc2e"}

View File

@ -1,8 +0,0 @@
language: rust
rust:
- nightly
- beta
- stable
branches:
except:
- staging.tmp

View File

@ -1,50 +0,0 @@
# 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 = "hyper_serde"
version = "0.8.0"
authors = ["Anthony Ramine <n.oxyde@gmail.com>"]
description = "Serde support for Hyper types"
documentation = "https://docs.rs/hyper_serde"
keywords = ["serde", "serialization", "hyper", "cookie", "mime"]
categories = ["encoding", "web-programming"]
license = "MIT/Apache-2.0"
repository = "https://github.com/nox/hyper_serde"
[lib]
doctest = false
[dependencies.time]
version = "0.1"
[dependencies.cookie]
version = "0.10"
default-features = false
[dependencies.mime]
version = "0.2"
[dependencies.serde]
version = "1.0"
[dependencies.hyper]
version = "0.10"
[dependencies.serde_bytes]
version = "0.10"
[dev-dependencies.serde_test]
version = "1.0"
[dev-dependencies.time]
version = "0.1"
[badges.travis-ci]
repository = "nox/hyper_serde"

View File

@ -1,176 +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

View File

@ -1,19 +0,0 @@
Copyright (c) 2016 Anthony Ramine
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.

View File

@ -1,40 +0,0 @@
Serde support for Hyper types
=============================
This crate provides wrappers and convenience functions to support [Serde] for
some types defined in [cookie], [Hyper], [mime] and [time].
[cookie]: https://github.com/alexcrichton/cookie-rs
[Hyper]: https://github.com/hyperium/hyper
[mime]: https://github.com/hyperium/mime.rs
[Serde]: https://github.com/serde-rs/serde
[time]: https://github.com/rust-lang-deprecated/time
The supported types are:
* `cookie::Cookie`
* `hyper::header::ContentType`
* `hyper::header::Headers`
* `hyper::http::RawStatus`
* `hyper::method::Method`
* `mime::Mime`
* `time::Tm`
For more details, see the crate documentation.
## License
hyper_serde is licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in hyper_serde by you, as defined in the Apache-2.0 license,
shall be dual licensed as above, without any additional terms or conditions.

View File

@ -1 +0,0 @@
status = ["continuous-integration/travis-ci/push"]

View File

@ -1,8 +0,0 @@
match_block_trailing_comma = true
max_width = 80
newline_style = "Unix"
normalize_comments = true
reorder_imported_names = true
reorder_imports = true
use_try_shorthand = true
where_trailing_comma = true

View File

@ -1,536 +0,0 @@
//! This crate provides wrappers and convenience functions to make Hyper and
//! Serde work hand in hand.
//!
//! The supported types are:
//!
//! * `cookie::Cookie`
//! * `hyper::header::ContentType`
//! * `hyper::header::Headers`
//! * `hyper::http::RawStatus`
//! * `hyper::method::Method`
//! * `mime::Mime`
//! * `time::Tm`
//!
//! # How do I use a data type with a `Headers` member with Serde?
//!
//! Use the serde attributes `deserialize_with` and `serialize_with`.
//!
//! ```
//! struct MyStruct {
//! #[serde(deserialize_with = "hyper_serde::deserialize",
//! serialize_with = "hyper_serde::serialize")]
//! headers: Headers,
//! }
//! ```
//!
//! # How do I encode a `Headers` value with `serde_json::to_string`?
//!
//! Use the `Ser` wrapper.
//!
//! ```
//! serde_json::to_string(&Ser::new(&headers))
//! ```
//!
//! # How do I decode a `Method` value with `serde_json::parse`?
//!
//! Use the `De` wrapper.
//!
//! ```
//! serde_json::parse::<De<Method>>("\"PUT\"").map(De::into_inner)
//! ```
//!
//! # How do I send `Cookie` values as part of an IPC channel?
//!
//! Use the `Serde` wrapper. It implements `Deref` and `DerefMut` for
//! convenience.
//!
//! ```
//! ipc::channel::<Serde<Cookie>>()
//! ```
//!
//!
#![deny(missing_docs)]
#![deny(unsafe_code)]
extern crate cookie;
extern crate hyper;
extern crate mime;
extern crate serde;
extern crate serde_bytes;
extern crate time;
use cookie::Cookie;
use hyper::header::{ContentType, Headers};
use hyper::http::RawStatus;
use hyper::method::Method;
use mime::Mime;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_bytes::{ByteBuf, Bytes};
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::ser::{SerializeMap, SerializeSeq};
use std::cmp;
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::str;
use time::{Tm, strptime};
/// Deserialises a `T` value with a given deserializer.
///
/// This is useful to deserialize Hyper types used in structure fields or
/// tuple members with `#[serde(deserialize_with = "hyper_serde::deserialize")]`.
#[inline(always)]
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where D: Deserializer<'de>,
De<T>: Deserialize<'de>,
{
De::deserialize(deserializer).map(De::into_inner)
}
/// Serialises `value` with a given serializer.
///
/// This is useful to serialize Hyper types used in structure fields or
/// tuple members with `#[serde(serialize_with = "hyper_serde::serialize")]`.
#[inline(always)]
pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
for<'a> Ser<'a, T>: Serialize,
{
Ser::new(value).serialize(serializer)
}
/// Serialises `value` with a given serializer in a pretty way.
///
/// This does the same job as `serialize` but with a prettier format
/// for some combinations of types and serialisers.
///
/// For now, the only change from `serialize` is when serialising `Headers`,
/// where the items in the header values get serialised as strings instead
/// of sequences of bytes, if they represent UTF-8 text.
#[inline(always)]
pub fn serialize_pretty<T, S>(value: &T,
serializer: S)
-> Result<S::Ok, S::Error>
where S: Serializer,
for<'a> Ser<'a, T>: Serialize,
{
Ser::new_pretty(value).serialize(serializer)
}
/// A wrapper to deserialize Hyper types.
///
/// This is useful with functions such as `serde_json::from_str`.
///
/// Values of this type can only be obtained through
/// the `serde::Deserialize` trait.
#[derive(Debug)]
pub struct De<T> {
v: T,
}
impl<T> De<T> {
fn new(v: T) -> Self {
De { v: v }
}
}
impl<'de, T> De<T>
where De<T>: Deserialize<'de>,
{
/// Consumes this wrapper, returning the deserialized value.
#[inline(always)]
pub fn into_inner(self) -> T {
self.v
}
}
/// A wrapper to serialize Hyper types.
///
/// This is useful with functions such as `serde_json::to_string`.
///
/// Values of this type can only be passed to the `serde::Serialize` trait.
#[derive(Debug)]
pub struct Ser<'a, T: 'a> {
v: &'a T,
pretty: bool,
}
impl<'a, T> Ser<'a, T>
where Ser<'a, T>: serde::Serialize,
{
/// Returns a new `Ser` wrapper.
#[inline(always)]
pub fn new(value: &'a T) -> Self {
Ser {
v: value,
pretty: false,
}
}
/// Returns a new `Ser` wrapper, in pretty mode.
///
/// See `serialize_pretty`.
#[inline(always)]
pub fn new_pretty(value: &'a T) -> Self {
Ser {
v: value,
pretty: true,
}
}
}
/// A convenience wrapper to be used as a type parameter, for example when
/// a `Vec<T>` need to be passed to serde.
#[derive(Clone, PartialEq)]
pub struct Serde<T>(pub T)
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize;
impl<T> Serde<T>
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
{
/// Consumes this wrapper, returning the inner value.
#[inline(always)]
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> fmt::Debug for Serde<T>
where T: fmt::Debug,
for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.0.fmt(formatter)
}
}
impl<T> Deref for Serde<T>
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
{
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for Serde<T>
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
{
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T: PartialEq> PartialEq<T> for Serde<T>
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
{
fn eq(&self, other: &T) -> bool {
self.0 == *other
}
}
impl<'b, T> Deserialize<'b> for Serde<T>
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'b>,
{
De::deserialize(deserializer).map(De::into_inner).map(Serde)
}
}
impl<T> Serialize for Serde<T>
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
Ser::new(&self.0).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for De<ContentType> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
deserialize(deserializer).map(ContentType).map(De::new)
}
}
impl<'a> Serialize for Ser<'a, ContentType> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serialize(&self.v.0, serializer)
}
}
impl<'de> Deserialize<'de> for De<Cookie<'static>> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
struct CookieVisitor;
impl<'de> Visitor<'de> for CookieVisitor {
type Value = De<Cookie<'static>>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "an HTTP cookie header value")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: de::Error,
{
Cookie::parse(v)
.map(Cookie::into_owned)
.map(De::new)
.map_err(|e| E::custom(format!("{:?}", e)))
}
}
deserializer.deserialize_string(CookieVisitor)
}
}
impl<'a, 'cookie> Serialize for Ser<'a, Cookie<'cookie>> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serializer.serialize_str(&self.v.to_string())
}
}
impl<'de> Deserialize<'de> for De<Headers> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
struct HeadersVisitor;
impl<'de> Visitor<'de> for HeadersVisitor {
type Value = De<Headers>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a map from header names to header values")
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where E: de::Error,
{
Ok(De::new(Headers::new()))
}
fn visit_map<V>(self,
mut visitor: V)
-> Result<Self::Value, V::Error>
where V: MapAccess<'de>,
{
let mut headers = Headers::new();
while let Some((k, v)) = visitor.next_entry::<String, Value>()? {
headers.set_raw(k, v.0);
}
Ok(De::new(headers))
}
}
struct Value(Vec<Vec<u8>>);
impl<'de> Deserialize<'de> for Value {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
deserializer.deserialize_seq(ValueVisitor)
}
}
struct ValueVisitor;
impl<'de> Visitor<'de> for ValueVisitor {
type Value = Value;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "an array of strings and sequences of bytes")
}
fn visit_unit<E>(self) -> Result<Value, E>
where E: de::Error,
{
Ok(Value(vec![]))
}
fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error>
where V: SeqAccess<'de>,
{
// Clamp to not OOM on rogue values.
let capacity = cmp::min(visitor.size_hint().unwrap_or(0), 64);
let mut values = Vec::with_capacity(capacity);
while let Some(v) = visitor.next_element::<ByteBuf>()? {
values.push(v.into());
}
Ok(Value(values))
}
}
deserializer.deserialize_map(HeadersVisitor)
}
}
impl<'a> Serialize for Ser<'a, Headers> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
struct Value<'headers>(&'headers [Vec<u8>], bool);
impl<'headers> Serialize for Value<'headers> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut serializer =
serializer.serialize_seq(Some(self.0.len()))?;
for v in self.0 {
if self.1 {
if let Ok(v) = str::from_utf8(v) {
serializer.serialize_element(v)?;
continue;
}
}
serializer.serialize_element(&Bytes::new(v))?;
}
serializer.end()
}
}
let mut serializer = serializer.serialize_map(Some(self.v.len()))?;
for header in self.v.iter() {
let name = header.name();
let value = self.v.get_raw(name).unwrap();
serializer.serialize_entry(name, &Value(value, self.pretty))?;
}
serializer.end()
}
}
impl<'de> Deserialize<'de> for De<Method> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
struct MethodVisitor;
impl<'de> Visitor<'de> for MethodVisitor {
type Value = De<Method>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "an HTTP method")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: de::Error,
{
v.parse::<Method>().map(De::new).map_err(E::custom)
}
}
deserializer.deserialize_string(MethodVisitor)
}
}
impl<'a> Serialize for Ser<'a, Method> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
Serialize::serialize(self.v.as_ref(), serializer)
}
}
impl<'de> Deserialize<'de> for De<Mime> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
struct MimeVisitor;
impl<'de> Visitor<'de> for MimeVisitor {
type Value = De<Mime>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a mime type")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: de::Error,
{
v.parse::<Mime>().map(De::new).map_err(|()| {
E::custom("could not parse mime type")
})
}
}
deserializer.deserialize_string(MimeVisitor)
}
}
impl<'a> Serialize for Ser<'a, Mime> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serializer.serialize_str(&self.v.to_string())
}
}
impl<'de> Deserialize<'de> for De<RawStatus> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
let (code, reason) = Deserialize::deserialize(deserializer)?;
Ok(De::new(RawStatus(code, reason)))
}
}
impl<'a> Serialize for Ser<'a, RawStatus> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(self.v.0, &self.v.1).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for De<Tm> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,
{
struct TmVisitor;
impl<'de> Visitor<'de> for TmVisitor {
type Value = De<Tm>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a date and time according to RFC 3339")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: de::Error,
{
strptime(v, "%Y-%m-%dT%H:%M:%SZ").map(De::new).map_err(|e| {
E::custom(e.to_string())
})
}
}
deserializer.deserialize_string(TmVisitor)
}
}
impl<'a> Serialize for Ser<'a, Tm> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serializer.serialize_str(&self.v.rfc3339().to_string())
}
}

View File

@ -1,33 +0,0 @@
extern crate cookie;
extern crate hyper;
extern crate hyper_serde;
extern crate mime;
extern crate serde;
extern crate time;
use cookie::Cookie;
use hyper::header::{ContentType, Headers};
use hyper::http::RawStatus;
use hyper::method::Method;
use hyper_serde::{De, Ser, Serde};
use mime::Mime;
use serde::{Deserialize, Serialize};
use time::Tm;
fn is_supported<T>()
where for<'de> De<T>: Deserialize<'de>,
for<'a> Ser<'a, T>: Serialize,
for <'de> Serde<T>: Deserialize<'de> + Serialize
{
}
#[test]
fn supported() {
is_supported::<Cookie>();
is_supported::<ContentType>();
is_supported::<Headers>();
is_supported::<Method>();
is_supported::<Mime>();
is_supported::<RawStatus>();
is_supported::<Tm>();
}

View File

@ -1,132 +0,0 @@
extern crate cookie;
extern crate hyper;
extern crate hyper_serde;
#[macro_use]
extern crate mime;
extern crate serde;
extern crate serde_test;
extern crate time;
use cookie::Cookie;
use hyper::header::{ContentType, Headers};
use hyper::http::RawStatus;
use hyper::method::Method;
use hyper_serde::{De, Ser, deserialize};
use serde::Deserialize;
use serde_test::{Deserializer, Token, assert_ser_tokens};
use std::fmt::Debug;
use time::Duration;
#[test]
fn test_content_type() {
let content_type = ContentType(mime!(Application / Json));
let tokens = &[Token::Str("application/json")];
assert_ser_tokens(&Ser::new(&content_type), tokens);
assert_de_tokens(&content_type, tokens);
}
#[test]
fn test_cookie() {
let cookie = Cookie::build("Hello", "World!")
.max_age(Duration::seconds(42))
.domain("servo.org")
.path("/")
.secure(true)
.http_only(false)
.finish();
let tokens = &[Token::Str("Hello=World!; Secure; Path=/; \
Domain=servo.org; Max-Age=42")];
assert_ser_tokens(&Ser::new(&cookie), tokens);
assert_de_tokens(&cookie, tokens);
}
#[test]
fn test_headers_empty() {
let headers = Headers::new();
let tokens = &[Token::Map { len: Some(0) }, Token::MapEnd];
assert_ser_tokens(&Ser::new(&headers), tokens);
assert_de_tokens(&headers, tokens);
}
#[test]
fn test_headers_not_empty() {
use hyper::header::Host;
let mut headers = Headers::new();
headers.set(Host {
hostname: "baguette".to_owned(),
port: None,
});
// In Hyper 0.9, Headers is internally a HashMap and thus testing this
// with multiple headers is non-deterministic.
let tokens = &[Token::Map{ len: Some(1) },
Token::Str("Host"),
Token::Seq{ len: Some(1) },
Token::Bytes(b"baguette"),
Token::SeqEnd,
Token::MapEnd];
assert_ser_tokens(&Ser::new(&headers), tokens);
assert_de_tokens(&headers, tokens);
let pretty = &[Token::Map{ len: Some(1) },
Token::Str("Host"),
Token::Seq{ len: Some(1) },
Token::Str("baguette"),
Token::SeqEnd,
Token::MapEnd];
assert_ser_tokens(&Ser::new_pretty(&headers), pretty);
assert_de_tokens(&headers, pretty);
}
#[test]
fn test_method() {
let method = Method::Put;
let tokens = &[Token::Str("PUT")];
assert_ser_tokens(&Ser::new(&method), tokens);
assert_de_tokens(&method, tokens);
}
#[test]
fn test_raw_status() {
use std::borrow::Cow;
let raw_status = RawStatus(200, Cow::Borrowed("OK"));
let tokens = &[Token::Tuple{ len: 2 },
Token::U16(200),
Token::Str("OK"),
Token::TupleEnd];
assert_ser_tokens(&Ser::new(&raw_status), tokens);
assert_de_tokens(&raw_status, tokens);
}
#[test]
fn test_tm() {
use time::strptime;
let time = strptime("2017-02-22T12:03:31Z", "%Y-%m-%dT%H:%M:%SZ").unwrap();
let tokens = &[Token::Str("2017-02-22T12:03:31Z")];
assert_ser_tokens(&Ser::new(&time), tokens);
assert_de_tokens(&time, tokens);
}
pub fn assert_de_tokens<T>(value: &T, tokens: &[Token])
where T: Debug + PartialEq,
for<'de> De<T>: Deserialize<'de>,
{
let mut deserializer = Deserializer::new(&tokens);
let v = deserialize::<T, _>(&mut deserializer).unwrap();
assert_eq!(&v, value);
assert_eq!(deserializer.next_token_opt(), None);
}

View File

@ -1 +0,0 @@
{"files":{"Cargo.toml":"acd21fe58d1af762230c1dec07b9e0131d65b1751f5e5d0aebb7cd6f79f56720","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"f0b7988c93ab594ca02b313b312b97a4c83669cd31aa0705711c113052130144","src/lib.rs":"cc5ff1cc84363022ac02e7291976b8d8d679cf5fbd021f192570c59e4011ddbd","src/value.rs":"911090aa5f4b0ee7ea00a8fe9d72e4df33dd4d9017689f0bdf97fa3a3d267817"},"package":"adb6e51a6b3696b301bc221d785f898b4457c619b51d7ce195a6d20baecb37b3"}

View File

@ -1,41 +0,0 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g. crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
name = "serde_bytes"
version = "0.10.4"
authors = ["David Tolnay <dtolnay@gmail.com>"]
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
description = "Optimized handling of `&[u8]` and `Vec<u8>` for Serde"
homepage = "https://serde.rs"
documentation = "https://docs.serde.rs/serde_bytes/"
readme = "README.md"
keywords = ["serde", "serialization", "no_std"]
categories = ["encoding"]
license = "MIT/Apache-2.0"
repository = "https://github.com/serde-rs/bytes"
[dependencies.serde]
version = "1.0"
default-features = false
[dev-dependencies.bincode]
version = "0.8"
[dev-dependencies.serde_derive]
version = "1.0"
[dev-dependencies.serde_test]
version = "1.0"
[features]
alloc = ["serde/alloc"]
default = ["std"]
std = ["serde/std"]

View File

@ -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.

View File

@ -1,25 +0,0 @@
Copyright (c) 2014 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,55 +0,0 @@
# serde\_bytes [![Build Status](https://api.travis-ci.org/serde-rs/bytes.svg?branch=master)](https://travis-ci.org/serde-rs/bytes) [![Latest Version](https://img.shields.io/crates/v/serde_bytes.svg)](https://crates.io/crates/serde_bytes)
Wrapper types to enable optimized handling of `&[u8]` and `Vec<u8>`.
Without specialization, Rust forces Serde to treat `&[u8]` just like any
other slice and `Vec<u8>` just like any other vector. In reality this
particular slice and vector can often be serialized and deserialized in a
more efficient, compact representation in many formats.
When working with such a format, you can opt into specialized handling of
`&[u8]` by wrapping it in `serde_bytes::Bytes` and `Vec<u8>` by wrapping it
in `serde_bytes::ByteBuf`.
This crate supports the Serde `with` attribute to enable efficient handling
of `&[u8]` and `Vec<u8>` in structs without needing a wrapper type.
```rust
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_bytes;
#[derive(Serialize)]
struct Efficient<'a> {
#[serde(with = "serde_bytes")]
bytes: &'a [u8],
#[serde(with = "serde_bytes")]
byte_buf: Vec<u8>,
}
#[derive(Serialize, Deserialize)]
struct Packet {
#[serde(with = "serde_bytes")]
payload: Vec<u8>,
}
```
## License
Serde is licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

View File

@ -1,431 +0,0 @@
//! Wrapper types to enable optimized handling of `&[u8]` and `Vec<u8>`.
//!
//! Without specialization, Rust forces Serde to treat `&[u8]` just like any
//! other slice and `Vec<u8>` just like any other vector. In reality this
//! particular slice and vector can often be serialized and deserialized in a
//! more efficient, compact representation in many formats.
//!
//! When working with such a format, you can opt into specialized handling of
//! `&[u8]` by wrapping it in `serde_bytes::Bytes` and `Vec<u8>` by wrapping it
//! in `serde_bytes::ByteBuf`.
//!
//! This crate supports the Serde `with` attribute to enable efficient handling
//! of `&[u8]` and `Vec<u8>` in structs without needing a wrapper type.
//!
//! ```rust
//! #[macro_use]
//! extern crate serde_derive;
//!
//! extern crate serde;
//! extern crate serde_bytes;
//!
//! #[derive(Serialize)]
//! struct Efficient<'a> {
//! #[serde(with = "serde_bytes")]
//! bytes: &'a [u8],
//!
//! #[serde(with = "serde_bytes")]
//! byte_buf: Vec<u8>,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct Packet {
//! #[serde(with = "serde_bytes")]
//! payload: Vec<u8>,
//! }
//! #
//! # fn main() {}
//! ```
#![doc(html_root_url = "https://docs.rs/serde_bytes/0.10.4")]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![deny(missing_docs)]
#[cfg(feature = "std")]
use std::{fmt, ops};
#[cfg(not(feature = "std"))]
use core::{fmt, ops};
use self::fmt::Debug;
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::Vec;
#[macro_use]
extern crate serde;
use serde::ser::{Serialize, Serializer};
use serde::de::{Deserialize, Deserializer, Visitor, Error};
#[cfg(any(feature = "std", feature = "alloc"))]
pub use self::bytebuf::ByteBuf;
mod value;
//////////////////////////////////////////////////////////////////////////////
/// Serde `serialize_with` function to serialize bytes efficiently.
///
/// This function can be used with either of the following Serde attributes:
///
/// - `#[serde(with = "serde_bytes")]`
/// - `#[serde(serialize_with = "serde_bytes::serialize")]`
///
/// ```rust
/// #[macro_use]
/// extern crate serde_derive;
///
/// extern crate serde;
/// extern crate serde_bytes;
///
/// #[derive(Serialize)]
/// struct Efficient<'a> {
/// #[serde(with = "serde_bytes")]
/// bytes: &'a [u8],
///
/// #[serde(with = "serde_bytes")]
/// byte_buf: Vec<u8>,
/// }
/// #
/// # fn main() {}
/// ```
pub fn serialize<T, S>(bytes: &T, serializer: S) -> Result<S::Ok, S::Error>
where T: ?Sized + AsRef<[u8]>,
S: Serializer
{
serializer.serialize_bytes(bytes.as_ref())
}
/// Serde `deserialize_with` function to deserialize bytes efficiently.
///
/// This function can be used with either of the following Serde attributes:
///
/// - `#[serde(with = "serde_bytes")]`
/// - `#[serde(deserialize_with = "serde_bytes::deserialize")]`
///
/// ```rust
/// #[macro_use]
/// extern crate serde_derive;
///
/// extern crate serde;
/// extern crate serde_bytes;
///
/// #[derive(Deserialize)]
/// struct Packet {
/// #[serde(with = "serde_bytes")]
/// payload: Vec<u8>,
/// }
/// #
/// # fn main() {}
/// ```
#[cfg(any(feature = "std", feature = "alloc"))]
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where T: From<Vec<u8>>,
D: Deserializer<'de>
{
ByteBuf::deserialize(deserializer).map(|buf| Into::<Vec<u8>>::into(buf).into())
}
//////////////////////////////////////////////////////////////////////////////
/// Wrapper around `&[u8]` to serialize and deserialize efficiently.
///
/// ```rust
/// extern crate bincode;
/// extern crate serde_bytes;
///
/// use std::collections::HashMap;
/// use std::io;
///
/// use serde_bytes::Bytes;
///
/// fn print_encoded_cache() -> Result<(), bincode::Error> {
/// let mut cache = HashMap::new();
/// cache.insert(3, Bytes::new(b"three"));
/// cache.insert(2, Bytes::new(b"two"));
/// cache.insert(1, Bytes::new(b"one"));
///
/// bincode::serialize_into(&mut io::stdout(), &cache, bincode::Infinite)
/// }
/// #
/// # fn main() {
/// # print_encoded_cache().unwrap();
/// # }
/// ```
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Bytes<'a> {
bytes: &'a [u8],
}
impl<'a> Bytes<'a> {
/// Wrap an existing `&[u8]`.
pub fn new(bytes: &'a [u8]) -> Self {
Bytes { bytes: bytes }
}
}
impl<'a> Debug for Bytes<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(self.bytes, f)
}
}
impl<'a> From<&'a [u8]> for Bytes<'a> {
fn from(bytes: &'a [u8]) -> Self {
Bytes::new(bytes)
}
}
impl<'a> From<Bytes<'a>> for &'a [u8] {
fn from(wrapper: Bytes<'a>) -> &'a [u8] {
wrapper.bytes
}
}
impl<'a> ops::Deref for Bytes<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.bytes
}
}
impl<'a> Serialize for Bytes<'a> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_bytes(self.bytes)
}
}
struct BytesVisitor;
impl<'de> Visitor<'de> for BytesVisitor {
type Value = Bytes<'de>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a borrowed byte array")
}
#[inline]
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Bytes<'de>, E>
where E: Error
{
Ok(Bytes::from(v))
}
#[inline]
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Bytes<'de>, E>
where E: Error
{
Ok(Bytes::from(v.as_bytes()))
}
}
impl<'a, 'de: 'a> Deserialize<'de> for Bytes<'a> {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Bytes<'a>, D::Error>
where D: Deserializer<'de>
{
deserializer.deserialize_bytes(BytesVisitor)
}
}
//////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "alloc"))]
mod bytebuf {
#[cfg(feature = "std")]
use std::{cmp, fmt, ops};
#[cfg(not(feature = "std"))]
use core::{cmp, fmt, ops};
use self::fmt::Debug;
#[cfg(feature = "alloc")]
use alloc::{String, Vec};
use serde::ser::{Serialize, Serializer};
use serde::de::{Deserialize, Deserializer, Visitor, SeqAccess, Error};
/// Wrapper around `Vec<u8>` to serialize and deserialize efficiently.
///
/// ```rust
/// extern crate bincode;
/// extern crate serde_bytes;
///
/// use std::collections::HashMap;
/// use std::io;
///
/// use serde_bytes::ByteBuf;
///
/// fn deserialize_bytebufs() -> Result<(), bincode::Error> {
/// let example_data = [
/// 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 116,
/// 119, 111, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 111, 110, 101];
///
/// let map: HashMap<u32, ByteBuf> =
/// bincode::deserialize_from(&mut &example_data[..], bincode::Infinite)?;
///
/// println!("{:?}", map);
///
/// Ok(())
/// }
/// #
/// # fn main() {
/// # deserialize_bytebufs().unwrap();
/// # }
/// ```
#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct ByteBuf {
bytes: Vec<u8>,
}
impl ByteBuf {
/// Construct a new, empty `ByteBuf`.
pub fn new() -> Self {
ByteBuf::from(Vec::new())
}
/// Construct a new, empty `ByteBuf` with the specified capacity.
pub fn with_capacity(cap: usize) -> Self {
ByteBuf::from(Vec::with_capacity(cap))
}
/// Wrap existing bytes in a `ByteBuf`.
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
ByteBuf { bytes: bytes.into() }
}
}
impl Debug for ByteBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.bytes, f)
}
}
impl From<ByteBuf> for Vec<u8> {
fn from(wrapper: ByteBuf) -> Vec<u8> {
wrapper.bytes
}
}
impl From<Vec<u8>> for ByteBuf {
fn from(bytes: Vec<u8>) -> Self {
ByteBuf::from(bytes)
}
}
impl AsRef<Vec<u8>> for ByteBuf {
fn as_ref(&self) -> &Vec<u8> {
&self.bytes
}
}
impl AsRef<[u8]> for ByteBuf {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
impl AsMut<Vec<u8>> for ByteBuf {
fn as_mut(&mut self) -> &mut Vec<u8> {
&mut self.bytes
}
}
impl AsMut<[u8]> for ByteBuf {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.bytes
}
}
impl ops::Deref for ByteBuf {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.bytes[..]
}
}
impl ops::DerefMut for ByteBuf {
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.bytes[..]
}
}
impl Serialize for ByteBuf {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_bytes(&self.bytes)
}
}
struct ByteBufVisitor;
impl<'de> Visitor<'de> for ByteBufVisitor {
type Value = ByteBuf;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("byte array")
}
#[inline]
fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error>
where V: SeqAccess<'de>
{
let len = cmp::min(visitor.size_hint().unwrap_or(0), 4096);
let mut values = Vec::with_capacity(len);
while let Some(value) = try!(visitor.next_element()) {
values.push(value);
}
Ok(ByteBuf::from(values))
}
#[inline]
fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E>
where E: Error
{
Ok(ByteBuf::from(v))
}
#[inline]
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E>
where E: Error
{
Ok(ByteBuf::from(v))
}
#[inline]
fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E>
where E: Error
{
Ok(ByteBuf::from(v))
}
#[inline]
fn visit_string<E>(self, v: String) -> Result<ByteBuf, E>
where E: Error
{
Ok(ByteBuf::from(v))
}
}
impl<'de> Deserialize<'de> for ByteBuf {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
where D: Deserializer<'de>
{
deserializer.deserialize_byte_buf(ByteBufVisitor)
}
}
}

View File

@ -1,91 +0,0 @@
use serde::de::{Deserializer, IntoDeserializer, Visitor, Error};
#[cfg(feature = "std")]
use std::marker::PhantomData;
#[cfg(not(feature = "std"))]
use core::marker::PhantomData;
#[cfg(feature = "alloc")]
use alloc::Vec;
//////////////////////////////////////////////////////////////////////////////
impl<'de, 'a, E> IntoDeserializer<'de, E> for super::Bytes<'a>
where E: Error
{
type Deserializer = BytesDeserializer<'a, E>;
fn into_deserializer(self) -> Self::Deserializer {
BytesDeserializer {
value: self.into(),
error: PhantomData,
}
}
}
/// A deserializer that deserializes a `&[u8]`.
pub struct BytesDeserializer<'a, E> {
value: &'a [u8],
error: PhantomData<E>,
}
impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E>
where E: Error
{
type Error = E;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
visitor.visit_bytes(self.value)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
//////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de, E> IntoDeserializer<'de, E> for super::ByteBuf
where E: Error
{
type Deserializer = ByteBufDeserializer<E>;
fn into_deserializer(self) -> Self::Deserializer {
ByteBufDeserializer {
value: self.into(),
error: PhantomData,
}
}
}
/// A deserializer that deserializes a `Vec<u8>`.
#[cfg(any(feature = "std", feature = "alloc"))]
pub struct ByteBufDeserializer<E> {
value: Vec<u8>,
error: PhantomData<E>,
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de, E> Deserializer<'de> for ByteBufDeserializer<E>
where E: Error
{
type Error = E;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
visitor.visit_byte_buf(self.value)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}