Initial commit

This commit is contained in:
Tadeo Kondrak 2020-06-20 00:59:22 -06:00
commit 3478b85dc3
No known key found for this signature in database
GPG Key ID: D41E092CA43F1D8B
9 changed files with 1284 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
Cargo.lock

13
Cargo.toml Normal file
View File

@ -0,0 +1,13 @@
[package]
name = "serde_bare"
version = "0.1.0"
authors = ["Tadeo Kondrak <me@tadeo.ca>"]
license = "MIT OR Apache-2.0"
edition = "2018"
description = "An incomplete implementation of the BARE (https://git.sr.ht/~sircmpwn/bare) encoding format."
repository = "https://git.sr.ht/~tdeo/serde_bare"
keywords = ["serde", "bare"]
categories = ["encoding"]
[dependencies]
serde = "1.0"

201
LICENSE-APACHE Normal file
View File

@ -0,0 +1,201 @@
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.

23
LICENSE-MIT Normal file
View File

@ -0,0 +1,23 @@
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.

15
README Normal file
View File

@ -0,0 +1,15 @@
serde_bare
An incomplete implementation of the BARE (https://git.sr.ht/~sircmpwn/bare) encoding format.
Missing types:
- f16 (in BARE, not in Serde's data model)
- i128 (in Serde's data model, not in BARE)
- u128 (in Serde's data model, not in BARE)
- tagged unions (in BARE, not immediately clear how to integrate with Serde's data model)
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.

515
src/de.rs Normal file
View File

@ -0,0 +1,515 @@
use crate::error::Error;
use serde::de;
use std::{
i16, i32, i64, i8,
io::{Cursor, Read},
str, u16, u32, u64, u8,
};
pub struct Deserializer<R> {
reader: R,
}
impl<R> Deserializer<R> {
pub fn new(reader: R) -> Self {
Deserializer { reader }
}
}
impl<'de, 'a, R> de::Deserializer<'de> for &'a mut Deserializer<R>
where
R: Read,
{
type Error = Error;
/// Returns Error::AnyUnsupported.
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
Err(Error::AnyUnsupported)
}
/// BARE type: bool
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
self.deserialize_u8(visitor)
}
/// BARE type: i8
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 1];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_i8(i8::from_le_bytes(buf))
}
/// BARE type: i16
fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 2];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_i16(i16::from_le_bytes(buf))
}
/// BARE type: i32
fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_i32(i32::from_le_bytes(buf))
}
/// BARE type: i64
fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 8];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_i64(i64::from_le_bytes(buf))
}
/// BARE type: u8
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 1];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_u8(u8::from_le_bytes(buf))
}
/// BARE type: u16
fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 2];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_u16(u16::from_le_bytes(buf))
}
/// BARE type: u32
fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_u32(u32::from_le_bytes(buf))
}
/// BARE type: u64
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 8];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_u64(u64::from_le_bytes(buf))
}
/// BARE type: f32
fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_f32(f32::from_le_bytes(buf))
}
/// BARE type: f64
fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let mut buf = [0u8; 8];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_f64(f64::from_le_bytes(buf))
}
/// BARE type: u32
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
self.deserialize_u32(visitor)
}
/// BARE type: string
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let length = {
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
u32::from_le_bytes(buf) as usize
};
let mut buf = Vec::with_capacity(length);
buf.resize(length, 0);
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
let utf8 = str::from_utf8(&buf).map_err(|_| Error::InvalidUtf8)?;
visitor.visit_str(utf8)
}
/// BARE type: string
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let length = {
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
u32::from_le_bytes(buf) as usize
};
let mut buf = Vec::with_capacity(length);
buf.resize(length, 0);
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
let utf8 = String::from_utf8(buf).map_err(|_| Error::InvalidUtf8)?;
visitor.visit_string(utf8)
}
/// BARE type: data
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let length = {
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
u32::from_le_bytes(buf) as usize
};
let mut buf = Vec::with_capacity(length);
buf.resize(length, 0);
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_bytes(&buf)
}
/// BARE type: data
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let length = {
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
u32::from_le_bytes(buf) as usize
};
let mut buf = Vec::with_capacity(length);
buf.resize(length, 0);
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
visitor.visit_byte_buf(buf)
}
/// BARE type: optional<T>
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let is_present = {
let mut buf = [0u8; 1];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
match buf[0] {
0 => false,
1 => true,
_ => return Err(Error::InvalidBool),
}
};
if !is_present {
visitor.visit_none()
} else {
visitor.visit_some(self)
}
}
/// Unserialized type.
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_unit()
}
/// Unserialized type.
fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_unit()
}
/// Unserialized type.
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
/// BARE type: []T
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let length = {
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
u32::from_le_bytes(buf)
};
struct Seq<'a, R>(&'a mut Deserializer<R>, u32);
impl<'de, 'a, R> de::SeqAccess<'de> for Seq<'a, R>
where
R: Read,
{
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
if self.1 == 0 {
Ok(None)
} else {
self.1 -= 1;
Ok(Some(seed.deserialize(&mut *self.0)?))
}
}
}
visitor.visit_seq(Seq::<'a, R>(self, length))
}
/// BARE type: \[len\]T
fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
struct Seq<'a, R>(&'a mut Deserializer<R>);
impl<'de, 'a, R> de::SeqAccess<'de> for Seq<'a, R>
where
R: Read,
{
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
Ok(Some(seed.deserialize(&mut *self.0)?))
}
}
visitor.visit_seq(Seq::<'a, R>(self))
}
/// BARE type: struct
fn deserialize_tuple_struct<V>(
self,
_name: &'static str,
_len: usize,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
struct Seq<'a, R>(&'a mut Deserializer<R>);
impl<'de, 'a, R> de::SeqAccess<'de> for Seq<'a, R>
where
R: Read,
{
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
Ok(Some(seed.deserialize(&mut *self.0)?))
}
}
visitor.visit_seq(Seq::<'a, R>(self))
}
/// BARE type: map\[T\]U
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
let length = {
let mut buf = [0u8; 4];
self.reader.read_exact(&mut buf).map_err(|e| Error::Io(e))?;
u32::from_le_bytes(buf)
};
struct Map<'a, R>(&'a mut Deserializer<R>, u32);
impl<'de, 'a, R> de::MapAccess<'de> for Map<'a, R>
where
R: Read,
{
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: de::DeserializeSeed<'de>,
{
if self.1 == 0 {
Ok(None)
} else {
Ok(Some(seed.deserialize(&mut *self.0)?))
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: de::DeserializeSeed<'de>,
{
self.1 -= 1;
Ok(seed.deserialize(&mut *self.0)?)
}
}
visitor.visit_map(Map::<'a, R>(self, length))
}
/// BARE type: struct
fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
struct Seq<'a, R>(&'a mut Deserializer<R>);
impl<'de, 'a, R> de::SeqAccess<'de> for Seq<'a, R>
where
R: Read,
{
type Error = Error;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
Ok(Some(seed.deserialize(&mut *self.0)?))
}
}
visitor.visit_seq(Seq::<'a, R>(self))
}
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
struct Enum<'a, R>(&'a mut Deserializer<R>);
impl<'de, 'a, R> de::EnumAccess<'de> for Enum<'a, R>
where
R: Read,
{
type Error = Error;
type Variant = Variant<'a, R>;
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: de::DeserializeSeed<'de>,
{
let val = seed.deserialize(&mut *self.0)?;
Ok((val, Variant(self.0)))
}
}
struct Variant<'a, R>(&'a mut Deserializer<R>);
impl<'de, 'a, R> de::VariantAccess<'de> for Variant<'a, R>
where
R: Read,
{
type Error = Error;
fn unit_variant(self) -> Result<(), Self::Error> {
Ok(())
}
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
seed.deserialize(self.0)
}
fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
de::Deserializer::deserialize_tuple(self.0, len, visitor)
}
fn struct_variant<V>(
self,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
de::Deserializer::deserialize_struct(self.0, "", fields, visitor)
}
}
visitor.visit_enum(Enum::<'a, R>(self))
}
/// Returns Error::IdentifierUnsupported.
fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
Err(Error::IdentifierUnsupported)
}
/// Returns Error::AnyUnsupported.
fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
Err(Error::AnyUnsupported)
}
fn is_human_readable(&self) -> bool {
false
}
}
pub fn from_reader<R, T>(reader: R) -> Result<T, Error>
where
R: Read,
T: de::DeserializeOwned,
{
T::deserialize(&mut Deserializer { reader })
}
pub fn from_slice<T>(slice: &[u8]) -> Result<T, Error>
where
T: de::DeserializeOwned,
{
T::deserialize(&mut Deserializer {
reader: Cursor::new(slice),
})
}

50
src/error.rs Normal file
View File

@ -0,0 +1,50 @@
use serde::{de, ser};
use std::{
fmt::{self, Display},
io,
};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
Message(String),
Io(io::Error),
AnyUnsupported,
InvalidUtf8,
InvalidBool,
IdentifierUnsupported,
LengthOverflow,
MapLengthRequired,
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
impl de::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
impl Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Message(msg) => formatter.write_str(msg),
Error::Io(e) => e.fmt(formatter),
Error::AnyUnsupported => {
formatter.write_str("any is unsupported because BARE is not self-describing")
}
Error::InvalidUtf8 => formatter.write_str("invalid utf-8 in string"),
Error::InvalidBool => formatter.write_str("invalid bool, neither 0 or 1"),
Error::IdentifierUnsupported => formatter.write_str("identifier is not supported"),
Error::LengthOverflow => formatter.write_str("length above u32::MAX"),
Error::MapLengthRequired => formatter.write_str("map length required"),
}
}
}
impl std::error::Error for Error {}

23
src/lib.rs Normal file
View File

@ -0,0 +1,23 @@
#![forbid(unsafe_code)]
//!```text
//! serde_bare
//!
//! An incomplete implementation of the BARE (https://git.sr.ht/~sircmpwn/bare) encoding format.
//!
//! Missing types:
//! - f16 (in BARE, not in Serde's data model)
//! - i128 (in Serde's data model, not in BARE)
//! - u128 (in Serde's data model, not in BARE)
//! - tagged unions (in BARE, not immediately clear how to integrate with Serde's data model)
//!```
pub mod de;
pub mod error;
pub mod ser;
#[doc(inline)]
pub use de::{from_reader, from_slice, Deserializer};
#[doc(inline)]
pub use error::{Error, Result};
#[doc(inline)]
pub use ser::{to_vec, to_writer, Serializer};

442
src/ser.rs Normal file
View File

@ -0,0 +1,442 @@
use crate::error::Error;
use serde::{ser, Serialize};
use std::{convert::TryInto, io::Write};
pub struct Serializer<W> {
writer: W,
}
impl<W> Serializer<W> {
pub fn new(writer: W) -> Self {
Serializer { writer }
}
}
impl<'a, W> ser::Serializer for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
type SerializeSeq = Self;
type SerializeTuple = Self;
type SerializeTupleStruct = Self;
type SerializeTupleVariant = Self;
type SerializeMap = Self;
type SerializeStruct = Self;
type SerializeStructVariant = Self;
/// BARE type: bool
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
self.serialize_u8(v as u8)
}
/// BARE type: i8
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: i16
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: i32
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: i64
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: u8
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: u16
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: u32
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: u64
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: f32
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: f64
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
self.writer
.write_all(&v.to_le_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: u32
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
self.serialize_u32(v as u32)
}
/// BARE type: string
/// Restriction: len < u32::MAX
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
let len: u32 = v.len().try_into().map_err(|_| Error::LengthOverflow)?;
self.serialize_u32(len)?;
self.writer
.write_all(v.as_bytes())
.map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: data
/// Restriction: len < u32::MAX
fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
let len: u32 = v.len().try_into().map_err(|_| Error::LengthOverflow)?;
self.serialize_u32(len)?;
self.writer.write_all(v).map_err(|e| Error::Io(e))?;
Ok(())
}
/// BARE type: optional<T>
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
self.serialize_u8(0)
}
/// BARE type: optional<T>
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: Serialize,
{
self.serialize_u8(1)?;
value.serialize(self)
}
/// No-op.
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
/// No-op.
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
self.serialize_unit()
}
/// BARE type: u32
fn serialize_unit_variant(
self,
_name: &'static str,
variant_index: u32,
_variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
self.serialize_u32(variant_index)
}
/// BARE type: T
fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: Serialize,
{
value.serialize(self)
}
/// BARE type: { u32, T }
fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
variant_index: u32,
_variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: Serialize,
{
self.serialize_u32(variant_index)?;
value.serialize(self)
}
/// BARE type if len is None: []type
/// BARE type if len is Some: \[len\]type
/// Error::LengthOverflow if len > u32::MAX
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
if let Some(len) = len {
self.serialize_u32(len.try_into().map_err(|_| Error::LengthOverflow)?)?;
}
Ok(self)
}
/// BARE type: \[len\]type
/// Error::LengthOverflow if len > u32::MAX
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Ok(self)
}
/// BARE type: struct
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
Ok(self)
}
/// BARE type: { u32, struct }
fn serialize_tuple_variant(
self,
_name: &'static str,
variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
self.serialize_u32(variant_index)?;
Ok(self)
}
/// BARE type: map\[T\]U
/// Error::MapLengthRequired if len is None
/// Error::LengthOverflow if len > u32::MAX
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
self.serialize_u32(
len.ok_or(Error::MapLengthRequired)?
.try_into()
.map_err(|_| Error::LengthOverflow)?,
)?;
Ok(self)
}
/// BARE type: struct
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
Ok(self)
}
/// BARE type: { u32, struct }
fn serialize_struct_variant(
self,
_name: &'static str,
variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
self.serialize_u32(variant_index)?;
Ok(self)
}
/// Returns false.
fn is_human_readable(&self) -> bool {
false
}
}
impl<'a, W> ser::SerializeSeq for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
impl<'a, W> ser::SerializeTuple for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
impl<'a, W> ser::SerializeTupleStruct for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
impl<'a, W> ser::SerializeTupleVariant for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
impl<'a, W> ser::SerializeMap for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
fn serialize_key<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
impl<'a, W> ser::SerializeStruct for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
fn serialize_field<T: ?Sized>(
&mut self,
_key: &'static str,
value: &T,
) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
impl<'a, W> ser::SerializeStructVariant for &'a mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
fn serialize_field<T: ?Sized>(
&mut self,
_key: &'static str,
value: &T,
) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>, Error>
where
T: Serialize,
{
let mut vec = Vec::new();
let mut serializer = Serializer { writer: &mut vec };
value.serialize(&mut serializer)?;
Ok(vec)
}
pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<(), Error>
where
W: Write,
T: Serialize,
{
let mut serializer = Serializer { writer };
value.serialize(&mut serializer)?;
Ok(())
}