ssh-encoding-0.2.0/.cargo_vcs_info.json 0000644 00000000152 00000000001 0013412 0 ustar {
"git": {
"sha1": "49e514782d81d346167fcf62ec5925c75f805b0c"
},
"path_in_vcs": "ssh-encoding"
} ssh-encoding-0.2.0/CHANGELOG.md 0000644 0000000 0000000 00000001154 10461020230 0014016 0 ustar 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 0.2.0 (2023-08-11)
### Added
- `LabelError` ([#124])
- `bytes` feature ([#138])
### Changed
- Bump `pem-rfc7468` to v0.7 ([#84])
### Removed
- `Encoding::Error` ([#124])
[#84]: https://github.com/RustCrypto/SSH/pull/84
[#124]: https://github.com/RustCrypto/SSH/pull/124
[#138]: https://github.com/RustCrypto/SSH/pull/138
## 0.1.0 (2022-10-23)
- Initial release
ssh-encoding-0.2.0/Cargo.toml 0000644 00000003242 00000000001 0011413 0 ustar # 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 are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.60"
name = "ssh-encoding"
version = "0.2.0"
authors = ["RustCrypto Developers"]
description = """
Pure Rust implementation of SSH data type decoders/encoders as described
in RFC4251
"""
readme = "README.md"
keywords = [
"crypto",
"certificate",
"key",
"openssh",
"ssh",
]
categories = [
"authentication",
"cryptography",
"encoding",
"no-std",
"parser-implementations",
]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/RustCrypto/SSH/tree/master/ssh-encoding"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = [
"--cfg",
"docsrs",
]
[dependencies.base64]
version = "1.4"
optional = true
package = "base64ct"
[dependencies.bytes]
version = "1"
optional = true
default-features = false
[dependencies.pem]
version = "0.7"
optional = true
package = "pem-rfc7468"
[dependencies.sha2]
version = "0.10"
optional = true
default-features = false
[dev-dependencies.hex-literal]
version = "0.4.1"
[features]
alloc = [
"base64?/alloc",
"pem?/alloc",
]
bytes = [
"alloc",
"dep:bytes",
]
pem = [
"base64",
"dep:pem",
]
std = [
"alloc",
"base64?/std",
"pem?/std",
"sha2?/std",
]
ssh-encoding-0.2.0/Cargo.toml.orig 0000644 0000000 0000000 00000002113 10461020230 0015070 0 ustar 0000000 0000000 [package]
name = "ssh-encoding"
version = "0.2.0"
description = """
Pure Rust implementation of SSH data type decoders/encoders as described
in RFC4251
"""
authors = ["RustCrypto Developers"]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/RustCrypto/SSH/tree/master/ssh-encoding"
categories = ["authentication", "cryptography", "encoding", "no-std", "parser-implementations"]
keywords = ["crypto", "certificate", "key", "openssh", "ssh"]
readme = "README.md"
edition = "2021"
rust-version = "1.60"
[dependencies]
base64 = { package = "base64ct", version = "1.4", optional = true }
bytes = { version = "1", optional = true, default-features = false }
pem = { package = "pem-rfc7468", version = "0.7", optional = true }
sha2 = { version = "0.10", optional = true, default-features = false }
[dev-dependencies]
hex-literal = "0.4.1"
[features]
alloc = ["base64?/alloc", "pem?/alloc"]
std = ["alloc", "base64?/std", "pem?/std", "sha2?/std"]
bytes = ["alloc", "dep:bytes"]
pem = ["base64", "dep:pem"]
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
ssh-encoding-0.2.0/LICENSE-APACHE 0000644 0000000 0000000 00000025141 10461020230 0014133 0 ustar 0000000 0000000 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.
ssh-encoding-0.2.0/LICENSE-MIT 0000644 0000000 0000000 00000002072 10461020230 0013641 0 ustar 0000000 0000000 Copyright (c) 2021-2023 The RustCrypto 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.
ssh-encoding-0.2.0/README.md 0000644 0000000 0000000 00000003376 10461020230 0013474 0 ustar 0000000 0000000 # [RustCrypto]: SSH Encoding
[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
[Documentation][docs-link]
## About
Pure Rust implementation of SSH data type decoders/encoders as described
in [RFC4251].
## Minimum Supported Rust Version
This crate requires **Rust 1.60** at a minimum.
We may change the MSRV in the future, but it will be accompanied by a minor
version bump.
## License
Licensed under either of:
* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
* [MIT license](http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
[//]: # (badges)
[crate-image]: https://buildstats.info/crate/ssh-encoding
[crate-link]: https://crates.io/crates/ssh-encoding
[docs-image]: https://docs.rs/ssh-encoding/badge.svg
[docs-link]: https://docs.rs/ssh-encoding/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
[rustc-image]: https://img.shields.io/badge/rustc-1.60+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/346919-SSH
[build-image]: https://github.com/RustCrypto/SSH/actions/workflows/ssh-encoding.yml/badge.svg
[build-link]: https://github.com/RustCrypto/SSH/actions/workflows/ssh-encoding.yml
[//]: # (links)
[RustCrypto]: https://github.com/rustcrypto
[RFC4251]: https://datatracker.ietf.org/doc/html/rfc4251
ssh-encoding-0.2.0/src/checked.rs 0000644 0000000 0000000 00000001076 10461020230 0014733 0 ustar 0000000 0000000 //! Checked arithmetic helpers.
use crate::{Error, Result};
/// Extension trait for providing checked [`Iterator::sum`]-like functionality.
pub trait CheckedSum: Sized {
/// Iterate over the values of this type, computing a checked sum.
///
/// Returns [`Error::Length`] on overflow.
fn checked_sum(self) -> Result;
}
impl CheckedSum for T
where
T: IntoIterator- ,
{
fn checked_sum(self) -> Result {
self.into_iter()
.try_fold(0, usize::checked_add)
.ok_or(Error::Length)
}
}
ssh-encoding-0.2.0/src/decode.rs 0000644 0000000 0000000 00000013730 10461020230 0014570 0 ustar 0000000 0000000 //! Decoder-side implementation of the SSH protocol's data type representations
//! as described in [RFC4251 § 5].
//!
//! [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
use crate::{reader::Reader, Error, Result};
#[cfg(feature = "alloc")]
use alloc::{string::String, vec::Vec};
#[cfg(feature = "bytes")]
use bytes::Bytes;
#[cfg(feature = "pem")]
use {crate::PEM_LINE_WIDTH, pem::PemLabel};
/// Maximum size of a `usize` this library will accept.
const MAX_SIZE: usize = 0xFFFFF;
/// Decoding trait.
///
/// This trait describes how to decode a given type.
pub trait Decode: Sized {
/// Type returned in the event of a decoding error.
type Error: From;
/// Attempt to decode a value of this type using the provided [`Reader`].
fn decode(reader: &mut impl Reader) -> core::result::Result;
}
/// Decoding trait for PEM documents.
///
/// This is an extension trait which is auto-impl'd for types which impl the
/// [`Decode`], [`PemLabel`], and [`Sized`] traits.
#[cfg(feature = "pem")]
pub trait DecodePem: Decode + PemLabel + Sized {
/// Decode the provided PEM-encoded string, interpreting the Base64-encoded
/// body of the document using the [`Decode`] trait.
fn decode_pem(pem: impl AsRef<[u8]>) -> core::result::Result;
}
#[cfg(feature = "pem")]
impl DecodePem for T {
fn decode_pem(pem: impl AsRef<[u8]>) -> core::result::Result {
let mut reader =
pem::Decoder::new_wrapped(pem.as_ref(), PEM_LINE_WIDTH).map_err(Error::from)?;
Self::validate_pem_label(reader.type_label()).map_err(Error::from)?;
let ret = Self::decode(&mut reader)?;
Ok(reader.finish(ret)?)
}
}
/// Decode a single `byte` from the input data.
impl Decode for u8 {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
let mut buf = [0];
reader.read(&mut buf)?;
Ok(buf[0])
}
}
/// Decode a `uint32` as described in [RFC4251 § 5]:
///
/// > Represents a 32-bit unsigned integer. Stored as four bytes in the
/// > order of decreasing significance (network byte order).
/// > For example: the value 699921578 (0x29b7f4aa) is stored as 29 b7 f4 aa.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Decode for u32 {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
let mut bytes = [0u8; 4];
reader.read(&mut bytes)?;
Ok(u32::from_be_bytes(bytes))
}
}
/// Decode a `uint64` as described in [RFC4251 § 5]:
///
/// > Represents a 64-bit unsigned integer. Stored as eight bytes in
/// > the order of decreasing significance (network byte order).
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Decode for u64 {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
let mut bytes = [0u8; 8];
reader.read(&mut bytes)?;
Ok(u64::from_be_bytes(bytes))
}
}
/// Decode a `usize`.
///
/// Uses [`Decode`] impl on `u32` and then converts to a `usize`, handling
/// potential overflow if `usize` is smaller than `u32`.
///
/// Enforces a library-internal limit of 1048575, as the main use case for
/// `usize` is length prefixes.
impl Decode for usize {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
let n = usize::try_from(u32::decode(reader)?)?;
if n <= MAX_SIZE {
Ok(n)
} else {
Err(Error::Overflow)
}
}
}
/// Decodes a byte array from `byte[n]` as described in [RFC4251 § 5]:
///
/// > A byte represents an arbitrary 8-bit value (octet). Fixed length
/// > data is sometimes represented as an array of bytes, written
/// > `byte[n]`, where n is the number of bytes in the array.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Decode for [u8; N] {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
reader.read_prefixed(|reader| {
let mut result = [(); N].map(|_| 0);
reader.read(&mut result)?;
Ok(result)
})
}
}
/// Decodes `Vec` from `byte[n]` as described in [RFC4251 § 5]:
///
/// > A byte represents an arbitrary 8-bit value (octet). Fixed length
/// > data is sometimes represented as an array of bytes, written
/// > `byte[n]`, where n is the number of bytes in the array.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
#[cfg(feature = "alloc")]
impl Decode for Vec {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
reader.read_prefixed(|reader| {
let mut result = vec![0u8; reader.remaining_len()];
reader.read(&mut result)?;
Ok(result)
})
}
}
#[cfg(feature = "alloc")]
impl Decode for String {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
String::from_utf8(Vec::decode(reader)?).map_err(|_| Error::CharacterEncoding)
}
}
#[cfg(feature = "alloc")]
impl Decode for Vec {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
reader.read_prefixed(|reader| {
let mut entries = Self::new();
while !reader.is_finished() {
entries.push(String::decode(reader)?);
}
Ok(entries)
})
}
}
/// Decodes `Bytes` from `byte[n]` as described in [RFC4251 § 5]:
///
/// > A byte represents an arbitrary 8-bit value (octet). Fixed length
/// > data is sometimes represented as an array of bytes, written
/// > `byte[n]`, where n is the number of bytes in the array.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
#[cfg(feature = "bytes")]
impl Decode for Bytes {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
Vec::::decode(reader).map(Into::into)
}
}
ssh-encoding-0.2.0/src/encode.rs 0000644 0000000 0000000 00000020615 10461020230 0014602 0 ustar 0000000 0000000 //! Encoder-side implementation of the SSH protocol's data type representations
//! as described in [RFC4251 § 5].
//!
//! [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
use crate::{checked::CheckedSum, writer::Writer, Error};
use core::str;
#[cfg(feature = "alloc")]
use alloc::{string::String, vec::Vec};
#[cfg(feature = "bytes")]
use bytes::Bytes;
#[cfg(feature = "pem")]
use {
crate::PEM_LINE_WIDTH,
pem::{LineEnding, PemLabel},
};
/// Encoding trait.
///
/// This trait describes how to encode a given type.
pub trait Encode {
/// Get the length of this type encoded in bytes, prior to Base64 encoding.
fn encoded_len(&self) -> Result;
/// Encode this value using the provided [`Writer`].
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error>;
/// Return the length of this type after encoding when prepended with a
/// `uint32` length prefix.
fn encoded_len_prefixed(&self) -> Result {
[4, self.encoded_len()?].checked_sum()
}
/// Encode this value, first prepending a `uint32` length prefix
/// set to [`Encode::encoded_len`].
fn encode_prefixed(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.encoded_len()?.encode(writer)?;
self.encode(writer)
}
}
/// Encoding trait for PEM documents.
///
/// This is an extension trait which is auto-impl'd for types which impl the
/// [`Encode`] and [`PemLabel`] traits.
#[cfg(feature = "pem")]
pub trait EncodePem: Encode + PemLabel {
/// Encode this type using the [`Encode`] trait, writing the resulting PEM
/// document into the provided `out` buffer.
fn encode_pem<'o>(&self, line_ending: LineEnding, out: &'o mut [u8]) -> Result<&'o str, Error>;
/// Encode this type using the [`Encode`] trait, writing the resulting PEM
/// document to a returned [`String`].
#[cfg(feature = "alloc")]
fn encode_pem_string(&self, line_ending: LineEnding) -> Result;
}
#[cfg(feature = "pem")]
impl EncodePem for T {
fn encode_pem<'o>(&self, line_ending: LineEnding, out: &'o mut [u8]) -> Result<&'o str, Error> {
let mut writer =
pem::Encoder::new_wrapped(Self::PEM_LABEL, PEM_LINE_WIDTH, line_ending, out)
.map_err(Error::from)?;
self.encode(&mut writer)?;
let encoded_len = writer.finish().map_err(Error::from)?;
str::from_utf8(&out[..encoded_len]).map_err(Error::from)
}
#[cfg(feature = "alloc")]
fn encode_pem_string(&self, line_ending: LineEnding) -> Result {
let encoded_len = pem::encapsulated_len_wrapped(
Self::PEM_LABEL,
PEM_LINE_WIDTH,
line_ending,
self.encoded_len()?,
)
.map_err(Error::from)?;
let mut buf = vec![0u8; encoded_len];
let actual_len = self.encode_pem(line_ending, &mut buf)?.len();
buf.truncate(actual_len);
String::from_utf8(buf).map_err(Error::from)
}
}
/// Encode a single `byte` to the writer.
impl Encode for u8 {
fn encoded_len(&self) -> Result {
Ok(1)
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
writer.write(&[*self])
}
}
/// Encode a `uint32` as described in [RFC4251 § 5]:
///
/// > Represents a 32-bit unsigned integer. Stored as four bytes in the
/// > order of decreasing significance (network byte order).
/// > For example: the value 699921578 (0x29b7f4aa) is stored as 29 b7 f4 aa.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Encode for u32 {
fn encoded_len(&self) -> Result {
Ok(4)
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
writer.write(&self.to_be_bytes())
}
}
/// Encode a `uint64` as described in [RFC4251 § 5]:
///
/// > Represents a 64-bit unsigned integer. Stored as eight bytes in
/// > the order of decreasing significance (network byte order).
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Encode for u64 {
fn encoded_len(&self) -> Result {
Ok(8)
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
writer.write(&self.to_be_bytes())
}
}
/// Encode a `usize` as a `uint32` as described in [RFC4251 § 5].
///
/// Uses [`Encode`] impl on `u32` after converting from a `usize`, handling
/// potential overflow if `usize` is bigger than `u32`.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Encode for usize {
fn encoded_len(&self) -> Result {
Ok(4)
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
u32::try_from(*self)?.encode(writer)
}
}
/// Encodes `[u8]` into `byte[n]` as described in [RFC4251 § 5]:
///
/// > A byte represents an arbitrary 8-bit value (octet). Fixed length
/// > data is sometimes represented as an array of bytes, written
/// > `byte[n]`, where n is the number of bytes in the array.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Encode for [u8] {
fn encoded_len(&self) -> Result {
[4, self.len()].checked_sum()
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.len().encode(writer)?;
writer.write(self)
}
}
/// Encodes `[u8; N]` into `byte[n]` as described in [RFC4251 § 5]:
///
/// > A byte represents an arbitrary 8-bit value (octet). Fixed length
/// > data is sometimes represented as an array of bytes, written
/// > `byte[n]`, where n is the number of bytes in the array.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Encode for [u8; N] {
fn encoded_len(&self) -> Result {
self.as_slice().encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.as_slice().encode(writer)
}
}
/// Encode a `string` as described in [RFC4251 § 5]:
///
/// > Arbitrary length binary string. Strings are allowed to contain
/// > arbitrary binary data, including null characters and 8-bit
/// > characters. They are stored as a uint32 containing its length
/// > (number of bytes that follow) and zero (= empty string) or more
/// > bytes that are the value of the string. Terminating null
/// > characters are not used.
/// >
/// > Strings are also used to store text. In that case, US-ASCII is
/// > used for internal names, and ISO-10646 UTF-8 for text that might
/// > be displayed to the user. The terminating null character SHOULD
/// > NOT normally be stored in the string. For example: the US-ASCII
/// > string "testing" is represented as 00 00 00 07 t e s t i n g. The
/// > UTF-8 mapping does not alter the encoding of US-ASCII characters.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
impl Encode for &str {
fn encoded_len(&self) -> Result {
self.as_bytes().encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.as_bytes().encode(writer)
}
}
#[cfg(feature = "alloc")]
impl Encode for Vec {
fn encoded_len(&self) -> Result {
self.as_slice().encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.as_slice().encode(writer)
}
}
#[cfg(feature = "alloc")]
impl Encode for String {
fn encoded_len(&self) -> Result {
self.as_str().encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.as_str().encode(writer)
}
}
#[cfg(feature = "alloc")]
impl Encode for Vec {
fn encoded_len(&self) -> Result {
self.iter().try_fold(4usize, |acc, string| {
acc.checked_add(string.encoded_len()?).ok_or(Error::Length)
})
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.encoded_len()?
.checked_sub(4)
.ok_or(Error::Length)?
.encode(writer)?;
for entry in self {
entry.encode(writer)?;
}
Ok(())
}
}
#[cfg(feature = "bytes")]
impl Encode for Bytes {
fn encoded_len(&self) -> Result {
self.as_ref().encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.as_ref().encode(writer)
}
}
ssh-encoding-0.2.0/src/error.rs 0000644 0000000 0000000 00000005550 10461020230 0014477 0 ustar 0000000 0000000 //! Error types.
use crate::LabelError;
use core::fmt;
/// Result type with `ssh-encoding` crate's [`Error`] as the error type.
pub type Result = core::result::Result;
/// Error type.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
/// Base64-related errors.
#[cfg(feature = "base64")]
Base64(base64::Error),
/// Character encoding-related errors.
CharacterEncoding,
/// Invalid label.
Label(LabelError),
/// Invalid length.
Length,
/// Overflow errors.
Overflow,
/// PEM encoding errors.
#[cfg(feature = "pem")]
Pem(pem::Error),
/// Unexpected trailing data at end of message.
TrailingData {
/// Number of bytes of remaining data at end of message.
remaining: usize,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
#[cfg(feature = "base64")]
Error::Base64(err) => write!(f, "Base64 encoding error: {err}"),
Error::CharacterEncoding => write!(f, "character encoding invalid"),
Error::Label(err) => write!(f, "{}", err),
Error::Length => write!(f, "length invalid"),
Error::Overflow => write!(f, "internal overflow error"),
#[cfg(feature = "pem")]
Error::Pem(err) => write!(f, "{err}"),
Error::TrailingData { remaining } => write!(
f,
"unexpected trailing data at end of message ({remaining} bytes)",
),
}
}
}
impl From for Error {
fn from(err: LabelError) -> Error {
Error::Label(err)
}
}
impl From for Error {
fn from(_: core::num::TryFromIntError) -> Error {
Error::Overflow
}
}
impl From for Error {
fn from(_: core::str::Utf8Error) -> Error {
Error::CharacterEncoding
}
}
#[cfg(feature = "alloc")]
impl From for Error {
fn from(_: alloc::string::FromUtf8Error) -> Error {
Error::CharacterEncoding
}
}
#[cfg(feature = "base64")]
impl From for Error {
fn from(err: base64::Error) -> Error {
Error::Base64(err)
}
}
#[cfg(feature = "base64")]
impl From for Error {
fn from(_: base64::InvalidLengthError) -> Error {
Error::Length
}
}
#[cfg(feature = "pem")]
impl From for Error {
fn from(err: pem::Error) -> Error {
Error::Pem(err)
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
#[cfg(feature = "base64")]
Self::Base64(err) => Some(err),
#[cfg(feature = "pem")]
Self::Pem(err) => Some(err),
_ => None,
}
}
}
ssh-encoding-0.2.0/src/label.rs 0000644 0000000 0000000 00000004034 10461020230 0014421 0 ustar 0000000 0000000 //! Convenience trait for decoding/encoding string labels.
use crate::{Decode, Encode, Error, Reader, Writer};
use core::{fmt, str::FromStr};
#[cfg(feature = "alloc")]
use alloc::string::String;
/// Maximum size of any algorithm name/identifier.
const MAX_LABEL_SIZE: usize = 48;
/// Labels for e.g. cryptographic algorithms.
///
/// Receives a blanket impl of [`Decode`] and [`Encode`].
pub trait Label: AsRef + FromStr {}
impl Decode for T {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result {
let mut buf = [0u8; MAX_LABEL_SIZE];
Ok(reader.read_string(buf.as_mut())?.parse()?)
}
}
impl Encode for T {
fn encoded_len(&self) -> Result {
self.as_ref().encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.as_ref().encode(writer)
}
}
/// Errors related to labels.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct LabelError {
/// The label that was considered invalid.
#[cfg(feature = "alloc")]
label: String,
}
impl LabelError {
/// Create a new [`LabelError`] for the given invalid label.
#[cfg_attr(not(feature = "alloc"), allow(unused_variables))]
pub fn new(label: &str) -> Self {
Self {
#[cfg(feature = "alloc")]
label: label.into(),
}
}
/// The invalid label string (if available).
#[inline]
pub fn label(&self) -> &str {
#[cfg(not(feature = "alloc"))]
{
""
}
#[cfg(feature = "alloc")]
{
&self.label
}
}
}
impl fmt::Display for LabelError {
#[cfg(not(feature = "alloc"))]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("invalid label")
}
#[cfg(feature = "alloc")]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid label: '{}'", self.label)
}
}
#[cfg(feature = "std")]
impl std::error::Error for LabelError {}
ssh-encoding-0.2.0/src/lib.rs 0000644 0000000 0000000 00000002361 10461020230 0014111 0 ustar 0000000 0000000 #![no_std]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
#![forbid(unsafe_code)]
#![warn(
clippy::arithmetic_side_effects,
clippy::panic,
clippy::panic_in_result_fn,
clippy::unwrap_used,
missing_docs,
rust_2018_idioms,
unused_lifetimes,
unused_qualifications
)]
#[cfg(feature = "alloc")]
#[macro_use]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
mod checked;
mod decode;
mod encode;
mod error;
mod label;
mod reader;
mod writer;
pub use crate::{
checked::CheckedSum,
decode::Decode,
encode::Encode,
error::{Error, Result},
label::{Label, LabelError},
reader::{NestedReader, Reader},
writer::Writer,
};
#[cfg(feature = "base64")]
pub use {
crate::{reader::Base64Reader, writer::Base64Writer},
base64,
};
#[cfg(feature = "pem")]
pub use {
crate::{decode::DecodePem, encode::EncodePem},
pem::{self, LineEnding},
};
/// Line width used by the PEM encoding of OpenSSH documents.
#[cfg(feature = "pem")]
const PEM_LINE_WIDTH: usize = 70;
ssh-encoding-0.2.0/src/reader.rs 0000644 0000000 0000000 00000014403 10461020230 0014605 0 ustar 0000000 0000000 //! Reader trait and associated implementations.
use crate::{decode::Decode, Error, Result};
use core::str;
/// Constant-time Base64 reader implementation.
#[cfg(feature = "base64")]
pub type Base64Reader<'i> = base64::Decoder<'i, base64::Base64>;
/// Reader trait which decodes the binary SSH protocol serialization from
/// various inputs.
pub trait Reader: Sized {
/// Read as much data as is needed to exactly fill `out`.
///
/// This is the base decoding method on which the rest of the trait is
/// implemented in terms of.
///
/// # Returns
/// - `Ok(bytes)` if the expected amount of data was read
/// - `Err(Error::Length)` if the exact amount of data couldn't be read
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]>;
/// Get the length of the remaining data after Base64 decoding.
fn remaining_len(&self) -> usize;
/// Is decoding finished?
fn is_finished(&self) -> bool {
self.remaining_len() == 0
}
/// Decode length-prefixed data.
///
/// Decodes a `uint32` which identifies the length of some encapsulated
/// data, then calls the given reader function with the length of the
/// remaining data.
fn read_prefixed<'r, T, E, F>(&'r mut self, f: F) -> core::result::Result
where
E: From,
F: FnOnce(&mut NestedReader<'r, Self>) -> core::result::Result,
{
let len = usize::decode(self)?;
f(&mut NestedReader {
inner: self,
remaining_len: len,
})
}
/// Decodes `[u8]` from `byte[n]` as described in [RFC4251 § 5]:
///
/// > A byte represents an arbitrary 8-bit value (octet). Fixed length
/// > data is sometimes represented as an array of bytes, written
/// > `byte[n]`, where n is the number of bytes in the array.
///
/// Storage for the byte array must be provided as mutable byte slice in
/// order to accommodate `no_std` use cases.
///
/// The [`Decode`] impl on `Vec` can be used to allocate a buffer for
/// the result.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
fn read_byten<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
self.read_prefixed(|reader| {
let slice = out.get_mut(..reader.remaining_len()).ok_or(Error::Length)?;
reader.read(slice)?;
Ok(slice as &[u8])
})
}
/// Decode a `string` as described in [RFC4251 § 5]:
///
/// > Arbitrary length binary string. Strings are allowed to contain
/// > arbitrary binary data, including null characters and 8-bit
/// > characters. They are stored as a uint32 containing its length
/// > (number of bytes that follow) and zero (= empty string) or more
/// > bytes that are the value of the string. Terminating null
/// > characters are not used.
/// >
/// > Strings are also used to store text. In that case, US-ASCII is
/// > used for internal names, and ISO-10646 UTF-8 for text that might
/// > be displayed to the user. The terminating null character SHOULD
/// > NOT normally be stored in the string. For example: the US-ASCII
/// > string "testing" is represented as 00 00 00 07 t e s t i n g. The
/// > UTF-8 mapping does not alter the encoding of US-ASCII characters.
///
/// Storage for the string data must be provided as mutable byte slice in
/// order to accommodate `no_std` use cases.
///
/// The [`Decode`] impl on `String` can be used to allocate a buffer for
/// the result.
///
/// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
fn read_string<'o>(&mut self, buf: &'o mut [u8]) -> Result<&'o str> {
Ok(str::from_utf8(self.read_byten(buf)?)?)
}
/// Drain the given number of bytes from the reader, discarding them.
fn drain(&mut self, n_bytes: usize) -> Result<()> {
let mut byte = [0];
for _ in 0..n_bytes {
self.read(&mut byte)?;
}
Ok(())
}
/// Decode a `u32` length prefix, and then drain the length of the body.
///
/// Upon success, returns the number of bytes drained sans the length of
/// the `u32` length prefix (4-bytes).
fn drain_prefixed(&mut self) -> Result {
self.read_prefixed(|reader| {
let len = reader.remaining_len();
reader.drain(len)?;
Ok(len)
})
}
/// Finish decoding, returning the given value if there is no remaining
/// data, or an error otherwise.
fn finish(self, value: T) -> Result {
if self.is_finished() {
Ok(value)
} else {
Err(Error::TrailingData {
remaining: self.remaining_len(),
})
}
}
}
impl Reader for &[u8] {
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
if self.len() >= out.len() {
let (head, tail) = self.split_at(out.len());
*self = tail;
out.copy_from_slice(head);
Ok(out)
} else {
Err(Error::Length)
}
}
fn remaining_len(&self) -> usize {
self.len()
}
}
#[cfg(feature = "base64")]
impl Reader for Base64Reader<'_> {
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
Ok(self.decode(out)?)
}
fn remaining_len(&self) -> usize {
self.remaining_len()
}
}
#[cfg(feature = "pem")]
impl Reader for pem::Decoder<'_> {
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
Ok(self.decode(out)?)
}
fn remaining_len(&self) -> usize {
self.remaining_len()
}
}
/// Reader type used by [`Reader::read_prefixed`].
pub struct NestedReader<'r, R: Reader> {
/// Inner reader type.
inner: &'r mut R,
/// Remaining length in the prefixed reader.
remaining_len: usize,
}
impl<'r, R: Reader> Reader for NestedReader<'r, R> {
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
let remaining_len = self
.remaining_len
.checked_sub(out.len())
.ok_or(Error::Length)?;
let ret = self.inner.read(out)?;
self.remaining_len = remaining_len;
Ok(ret)
}
fn remaining_len(&self) -> usize {
self.remaining_len
}
}
ssh-encoding-0.2.0/src/writer.rs 0000644 0000000 0000000 00000002461 10461020230 0014660 0 ustar 0000000 0000000 //! Writer trait and associated implementations.
use crate::Result;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "sha2")]
use sha2::{Digest, Sha256, Sha512};
/// Constant-time Base64 writer implementation.
#[cfg(feature = "base64")]
pub type Base64Writer<'o> = base64::Encoder<'o, base64::Base64>;
/// Writer trait which encodes the SSH binary format to various output
/// encodings.
pub trait Writer: Sized {
/// Write the given bytes to the writer.
fn write(&mut self, bytes: &[u8]) -> Result<()>;
}
#[cfg(feature = "alloc")]
impl Writer for Vec {
fn write(&mut self, bytes: &[u8]) -> Result<()> {
self.extend_from_slice(bytes);
Ok(())
}
}
#[cfg(feature = "base64")]
impl Writer for Base64Writer<'_> {
fn write(&mut self, bytes: &[u8]) -> Result<()> {
Ok(self.encode(bytes)?)
}
}
#[cfg(feature = "pem")]
impl Writer for pem::Encoder<'_, '_> {
fn write(&mut self, bytes: &[u8]) -> Result<()> {
Ok(self.encode(bytes)?)
}
}
#[cfg(feature = "sha2")]
impl Writer for Sha256 {
fn write(&mut self, bytes: &[u8]) -> Result<()> {
self.update(bytes);
Ok(())
}
}
#[cfg(feature = "sha2")]
impl Writer for Sha512 {
fn write(&mut self, bytes: &[u8]) -> Result<()> {
self.update(bytes);
Ok(())
}
}
ssh-encoding-0.2.0/tests/decode.rs 0000644 0000000 0000000 00000003567 10461020230 0015152 0 ustar 0000000 0000000 //! Tests for the `Decode` trait.
use hex_literal::hex;
use ssh_encoding::{Decode, Error};
#[test]
fn decode_u8() {
let mut bytes = hex!("42").as_slice();
let ret = u8::decode(&mut bytes).unwrap();
assert_eq!(ret, 0x42u8);
}
#[test]
fn decode_u32() {
let mut bytes = hex!("DEADBEEF").as_slice();
let ret = u32::decode(&mut bytes).unwrap();
assert_eq!(ret, 0xDEADBEEFu32);
}
#[test]
fn decode_u64() {
let mut bytes = hex!("0000DEADBEEFCAFE").as_slice();
let ret = u64::decode(&mut bytes).unwrap();
assert_eq!(ret, 0xDEADBEEFCAFEu64);
}
#[test]
fn decode_usize() {
let mut bytes = hex!("000FFFFF").as_slice();
let ret = usize::decode(&mut bytes).unwrap();
assert_eq!(ret, 0xFFFFFusize);
}
/// `usize` decoder has a sanity limit of 0xFFFFF.
#[test]
fn reject_oversize_usize() {
let mut bytes = hex!("00100000").as_slice();
let err = usize::decode(&mut bytes).err().unwrap();
assert_eq!(err, Error::Overflow);
}
#[test]
fn decode_byte_slice() {
let mut bytes = hex!("000000076578616d706c65").as_slice();
let ret = <[u8; 7]>::decode(&mut bytes).unwrap();
assert_eq!(&ret, b"example");
}
#[cfg(feature = "alloc")]
#[test]
fn decode_byte_vec() {
let mut bytes = hex!("000000076578616d706c65").as_slice();
let ret = Vec::::decode(&mut bytes).unwrap();
assert_eq!(&ret, b"example");
}
#[cfg(feature = "alloc")]
#[test]
fn decode_string() {
let mut bytes = hex!("000000076578616d706c65").as_slice();
let ret = String::decode(&mut bytes).unwrap();
assert_eq!(&ret, "example");
}
#[cfg(feature = "alloc")]
#[test]
fn decode_string_vec() {
let mut bytes = hex!("0000001500000003666f6f000000036261720000000362617a").as_slice();
let ret = Vec::::decode(&mut bytes).unwrap();
assert_eq!(ret.len(), 3);
assert_eq!(ret[0], "foo");
assert_eq!(ret[1], "bar");
assert_eq!(ret[2], "baz");
}
ssh-encoding-0.2.0/tests/encode.rs 0000644 0000000 0000000 00000003211 10461020230 0015146 0 ustar 0000000 0000000 //! Tests for the `Encode` trait.
#![cfg(feature = "alloc")]
use hex_literal::hex;
use ssh_encoding::Encode;
#[test]
fn encode_u8() {
let mut out = Vec::new();
0x42u8.encode(&mut out).unwrap();
assert_eq!(out, hex!("42"));
}
#[test]
fn encode_u32() {
let mut out = Vec::new();
0xDEADBEEFu32.encode(&mut out).unwrap();
assert_eq!(out, hex!("DEADBEEF"));
}
#[test]
fn encode_u64() {
let mut out = Vec::new();
0xDEADBEEFCAFEu64.encode(&mut out).unwrap();
assert_eq!(out, hex!("0000DEADBEEFCAFE"));
}
#[test]
fn encode_usize() {
let mut out = Vec::new();
0xDEADBEEFusize.encode(&mut out).unwrap();
assert_eq!(out, hex!("DEADBEEF"));
}
#[test]
fn encode_byte_slice() {
let mut out = Vec::new();
b"example".encode(&mut out).unwrap();
assert_eq!(out, hex!("000000076578616d706c65"));
}
#[test]
fn encode_byte_vec() {
let mut out = Vec::new();
Vec::from(b"example".as_ref()).encode(&mut out).unwrap();
assert_eq!(out, hex!("000000076578616d706c65"));
}
#[test]
fn encode_str() {
let mut out = Vec::new();
"example".encode(&mut out).unwrap();
assert_eq!(out, hex!("000000076578616d706c65"));
}
#[test]
fn encode_string() {
let mut out = Vec::new();
String::from("example").encode(&mut out).unwrap();
assert_eq!(out, hex!("000000076578616d706c65"));
}
#[test]
fn encode_string_vec() {
let vec = ["foo", "bar", "baz"]
.iter()
.map(|&s| s.to_owned())
.collect::>();
let mut out = Vec::new();
vec.encode(&mut out).unwrap();
assert_eq!(
out,
hex!("0000001500000003666f6f000000036261720000000362617a")
);
}