Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for time::Time #43

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ bitcode_derive = { version = "0.6.3", path = "./bitcode_derive", optional = true
bytemuck = { version = "1.14", features = [ "min_const_generics", "must_cast" ] }
glam = { version = ">=0.21", default-features = false, optional = true }
serde = { version = "1.0", default-features = false, features = [ "alloc" ], optional = true }
time = { version = "0.3", default-features = false, features = [ "alloc" ], optional = true }

[dev-dependencies]
arrayvec = { version = "0.7", features = [ "serde" ] }
Expand All @@ -37,7 +38,7 @@ zstd = "0.13.0"

[features]
derive = [ "dep:bitcode_derive" ]
std = [ "serde?/std", "glam?/std", "arrayvec?/std" ]
std = [ "serde?/std", "glam?/std", "arrayvec?/std", "time?/std" ]
default = [ "derive", "std" ]

[package.metadata.docs.rs]
Expand Down
3 changes: 2 additions & 1 deletion fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ cargo-fuzz = true

[dependencies]
arrayvec = { version = "0.7", features = ["serde"] }
bitcode = { path = "..", features = [ "arrayvec", "serde" ] }
bitcode = { path = "..", features = [ "arrayvec", "serde", "time" ] }
libfuzzer-sys = "0.4"
serde = { version ="1.0", features = [ "derive" ] }
time = { version = "0.3", features = ["serde"]}

# Prevent this from interfering with workspaces
[workspace]
Expand Down
3 changes: 2 additions & 1 deletion fuzz/fuzz_targets/fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fmt::Debug;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::num::NonZeroU32;
use std::time::Duration;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddr, SocketAddrV6};

#[inline(never)]
fn test_derive<T: Debug + PartialEq + Encode + DecodeOwned>(data: &[u8]) {
Expand Down Expand Up @@ -216,5 +216,6 @@ fuzz_target!(|data: &[u8]| {
SocketAddrV4,
SocketAddrV6,
SocketAddr,
time::Time,
);
});
15 changes: 15 additions & 0 deletions src/derive/datetime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use bytemuck::CheckedBitPattern;

use crate::int::ranged_int;

use super::{
convert::{ConvertFrom, ConvertIntoEncoder},
Decode, Encode,
};

ranged_int!(Hour, u8, 0, 23);
ranged_int!(Minute, u8, 0, 59);
ranged_int!(Second, u8, 0, 59);
ranged_int!(Nanosecond, u32, 0, 999_999_999);

pub type TimeConversion = (Hour, Minute, Second, Nanosecond);
25 changes: 5 additions & 20 deletions src/derive/duration.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::coder::{Buffer, Decoder, Encoder, Result, View};
use crate::datetime::Nanosecond;
use crate::{Decode, Encode};
use alloc::vec::Vec;
use bytemuck::CheckedBitPattern;
Expand Down Expand Up @@ -32,26 +33,10 @@ impl Encode for Duration {
type Encoder = DurationEncoder;
}

/// A u32 guaranteed to be < 1 billion. Prevents Duration::new from panicking.
#[derive(Copy, Clone)]
#[repr(transparent)]
struct Nanoseconds(u32);
// Safety: u32 and Nanoseconds have the same layout since Nanoseconds is #[repr(transparent)].
unsafe impl CheckedBitPattern for Nanoseconds {
type Bits = u32;
#[inline(always)]
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
*bits < 1_000_000_000
}
}
impl<'a> Decode<'a> for Nanoseconds {
type Decoder = crate::int::CheckedIntDecoder<'a, Nanoseconds, u32>;
}

#[derive(Default)]
pub struct DurationDecoder<'a> {
secs: <u64 as Decode<'a>>::Decoder,
subsec_nanos: <Nanoseconds as Decode<'a>>::Decoder,
subsec_nanos: <Nanosecond as Decode<'a>>::Decoder,
}
impl<'a> View<'a> for DurationDecoder<'a> {
fn populate(&mut self, input: &mut &'a [u8], length: usize) -> Result<()> {
Expand All @@ -64,11 +49,11 @@ impl<'a> Decoder<'a, Duration> for DurationDecoder<'a> {
#[inline(always)]
fn decode(&mut self) -> Duration {
let secs = self.secs.decode();
let Nanoseconds(subsec_nanos) = self.subsec_nanos.decode();
let Nanosecond(subsec_nanos) = self.subsec_nanos.decode();
// Makes Duration::new 4x faster since it can skip checks and division.
// Safety: impl CheckedBitPattern for Nanoseconds guarantees this.
unsafe {
if !Nanoseconds::is_valid_bit_pattern(&subsec_nanos) {
if !Nanosecond::is_valid_bit_pattern(&subsec_nanos) {
core::hint::unreachable_unchecked();
}
}
Expand All @@ -95,5 +80,5 @@ mod tests {
.map(|(s, n): (_, u32)| Duration::new(s, n % 1_000_000_000))
.collect()
}
crate::bench_encode_decode!(duration_vec: Vec<_>);
crate::bench_encode_decode!(duration_vec: Vec<Duration>);
}
1 change: 1 addition & 0 deletions src/derive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use core::num::NonZeroUsize;

mod array;
pub(crate) mod convert;
pub(crate) mod datetime;
mod duration;
mod empty;
mod impls;
Expand Down
2 changes: 2 additions & 0 deletions src/ext/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ mod arrayvec;
#[cfg(feature = "glam")]
#[rustfmt::skip] // Makes impl_struct! calls way longer.
mod glam;
#[cfg(feature = "time")]
mod time_crate;

#[allow(unused)]
macro_rules! impl_struct {
Expand Down
8 changes: 8 additions & 0 deletions src/ext/time_crate/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mod time;

use crate::convert::impl_convert;
use crate::datetime::TimeConversion;
use crate::derive::{Decode, Encode};
use ::time::Time;

impl_convert!(Time, TimeConversion);
59 changes: 59 additions & 0 deletions src/ext/time_crate/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use crate::convert::ConvertFrom;
use crate::datetime::{Hour, Minute, Nanosecond, Second, TimeConversion};
use time::Time;

impl ConvertFrom<&Time> for TimeConversion {
fn convert_from(value: &Time) -> Self {
let (hour, minute, second, nanosecond) = value.as_hms_nano();
(
Hour(hour),
Minute(minute),
Second(second),
Nanosecond(nanosecond),
)
}
}

impl ConvertFrom<TimeConversion> for Time {
fn convert_from(value: (Hour, Minute, Second, Nanosecond)) -> Self {
let (Hour(hour), Minute(minute), Second(second), Nanosecond(nanosecond)) = value;
// Safety: should not fail because all input values are validated with CheckedBitPattern.
unsafe { Time::from_hms_nano(hour, minute, second, nanosecond).unwrap_unchecked() }
}
}

#[cfg(test)]
mod tests {
#[test]
fn test() {
assert!(crate::decode::<Time>(&crate::encode(
&Time::from_hms_nano(23, 59, 59, 999_999_999).unwrap()
))
.is_ok());
assert!(crate::decode::<Time>(&crate::encode(&(23u8, 59u8, 59u8, 999_999_999u32))).is_ok());
assert!(
crate::decode::<Time>(&crate::encode(&(24u8, 59u8, 59u8, 999_999_999u32))).is_err()
);
assert!(
crate::decode::<Time>(&crate::encode(&(23u8, 60u8, 59u8, 999_999_999u32))).is_err()
);
assert!(
crate::decode::<Time>(&crate::encode(&(23u8, 59u8, 60u8, 999_999_999u32))).is_err()
);
assert!(
crate::decode::<Time>(&crate::encode(&(23u8, 59u8, 59u8, 1_000_000_000u32))).is_err()
);
}

use alloc::vec::Vec;
use time::Time;
fn bench_data() -> Vec<Time> {
crate::random_data(1000)
.into_iter()
.map(|(h, m, s, n): (u8, u8, u8, u32)| {
Time::from_hms_nano(h % 24, m % 60, s % 60, n % 1_000_000_000).unwrap()
})
.collect()
}
crate::bench_encode_decode!(duration_vec: Vec<_>);
}
32 changes: 32 additions & 0 deletions src/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,38 @@ where
}
}

#[allow(unused)]
macro_rules! ranged_int {
($type: ident, $int: ty, $lower: expr, $upper: expr) => {
#[doc = concat!("A ", stringify!($int), " which takes value from ", stringify!($lower), " to ", stringify!($upper))]
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct $type(pub $int);
// Safety: They have the same layout because of #[repr(transparent)].
unsafe impl CheckedBitPattern for $type {
type Bits = $int;
#[inline(always)]
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
($lower..=$upper).contains(bits)
}
}
impl ConvertFrom<&$type> for $int {
fn convert_from(value: &$type) -> Self {
value.0
}
}
impl Encode for $type {
type Encoder = ConvertIntoEncoder<$int>;
}
impl<'a> Decode<'a> for $type {
type Decoder = crate::int::CheckedIntDecoder<'a, $type, $int>;
}
};
}

#[allow(unused)]
pub(crate) use ranged_int;

#[cfg(test)]
mod tests {
use crate::{decode, encode};
Expand Down
Loading