Skip to content

Commit e1dad95

Browse files
committed
add enc/dec for bool
Signed-off-by: Dave Huseby <[email protected]>
1 parent 86513f1 commit e1dad95

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "multitrait"
3-
version = "0.1.4"
3+
version = "0.1.5"
44
edition = "2021"
55
authors = ["Dave Huseby <[email protected]>"]
66
description = "Multiformat traits"

src/enc_into.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,16 @@ pub trait EncodeInto {
66
fn encode_into(&self) -> Vec<u8>;
77
}
88

9+
/// Encode a bool into a compact varuint Vec<u8>
10+
impl EncodeInto for bool {
11+
fn encode_into(&self) -> Vec<u8> {
12+
match *self {
13+
true => vec![1u8],
14+
false => vec![0u8],
15+
}
16+
}
17+
}
18+
919
/// Encode a u8 into a compact varuint Vec<u8>
1020
impl EncodeInto for u8 {
1121
fn encode_into(&self) -> Vec<u8> {

src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ pub mod prelude {
2828
mod test {
2929
use super::prelude::*;
3030

31+
#[test]
32+
fn test_bool() {
33+
let tbuf = true.encode_into();
34+
let (tval, _) = bool::try_decode_from(&tbuf).unwrap();
35+
assert_eq!(true, tval);
36+
let fbuf = false.encode_into();
37+
let (fval, _) = bool::try_decode_from(&fbuf).unwrap();
38+
assert_eq!(false, fval);
39+
}
40+
3141
#[test]
3242
fn test_u8() {
3343
let buf = 0xff_u8.encode_into();

src/try_decode_from.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@ pub trait TryDecodeFrom<'a>: Sized {
1212
fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error>;
1313
}
1414

15+
/// Try to decode a varuint encoded bool
16+
impl<'a> TryDecodeFrom<'a> for bool {
17+
type Error = Error;
18+
19+
fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
20+
let (v, ptr) = decode::u8(bytes).map_err(|e| Self::Error::UnsignedVarintDecode(e))?;
21+
Ok(((v != 0), ptr))
22+
}
23+
}
24+
1525
/// Try to decode a varuint encoded u8
1626
impl<'a> TryDecodeFrom<'a> for u8 {
1727
type Error = Error;

0 commit comments

Comments
 (0)