use crate::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date {
year: i32,
month: u8,
day: u8,
}
impl Date {
pub fn new(year: i32, month: u8, day: u8) -> Result<Self> {
let leap =
year.rem_euclid(4) == 0 && (year.rem_euclid(100) != 0 || year.rem_euclid(400) == 0);
let days = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => 0,
};
if day == 0 || day > days {
return Err(Error::Data("invalid Gregorian calendar date".into()));
}
Ok(Self { year, month, day })
}
pub const fn year(self) -> i32 {
self.year
}
pub const fn month(self) -> u8 {
self.month
}
pub const fn day(self) -> u8 {
self.day
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Duration(i128);
impl Duration {
pub const fn from_nanos(nanos: i128) -> Self {
Self(nanos)
}
pub const fn from_secs(seconds: i64) -> Self {
Self(seconds as i128 * 1_000_000_000)
}
pub const fn nanoseconds(self) -> i128 {
self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TimeZone {
Iana(String),
FixedOffset(i32),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Timestamp {
seconds: i64,
nanos: u32,
zone: Option<TimeZone>,
offset_seconds: Option<i32>,
fold: Option<u8>,
}
impl Timestamp {
pub fn new(
seconds: i64,
nanos: u32,
zone: Option<TimeZone>,
offset_seconds: Option<i32>,
fold: Option<u8>,
) -> Result<Self> {
let valid_offset = |offset: i32| (-86_399..=86_399).contains(&offset);
if nanos >= 1_000_000_000
|| fold.is_some_and(|value| value > 1)
|| offset_seconds.is_some_and(|offset| !valid_offset(offset))
{
return Err(Error::Data(
"invalid timestamp nanoseconds, offset or fold".into(),
));
}
match &zone {
Some(TimeZone::Iana(name)) if name.is_empty() => {
return Err(Error::Data("timezone name must not be empty".into()));
}
Some(TimeZone::FixedOffset(offset))
if !valid_offset(*offset)
|| offset_seconds.is_some_and(|original| original != *offset) =>
{
return Err(Error::Data("inconsistent fixed timezone offset".into()));
}
_ => {}
}
Ok(Self {
seconds,
nanos,
zone,
offset_seconds,
fold,
})
}
pub const fn seconds(&self) -> i64 {
self.seconds
}
pub const fn nanos(&self) -> u32 {
self.nanos
}
pub const fn unix_ns(&self) -> i128 {
self.seconds as i128 * 1_000_000_000 + self.nanos as i128
}
pub const fn zone(&self) -> Option<&TimeZone> {
self.zone.as_ref()
}
pub const fn offset_seconds(&self) -> Option<i32> {
self.offset_seconds
}
pub const fn fold(&self) -> Option<u8> {
self.fold
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LocalTimestamp {
date: Date,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
}
impl LocalTimestamp {
pub fn new(date: Date, hour: u8, minute: u8, second: u8, nanos: u32) -> Result<Self> {
if hour >= 24 || minute >= 60 || second >= 60 || nanos >= 1_000_000_000 {
return Err(Error::Data("invalid local timestamp".into()));
}
Ok(Self {
date,
hour,
minute,
second,
nanos,
})
}
pub const fn date(self) -> Date {
self.date
}
pub const fn hour(self) -> u8 {
self.hour
}
pub const fn minute(self) -> u8 {
self.minute
}
pub const fn second(self) -> u8 {
self.second
}
pub const fn nanos(self) -> u32 {
self.nanos
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DurationUnit {
Nanosecond,
Microsecond,
Millisecond,
Second,
Minute,
Hour,
Day,
Week,
}
impl DurationUnit {
pub const fn nanoseconds(self) -> i128 {
match self {
Self::Nanosecond => 1,
Self::Microsecond => 1_000,
Self::Millisecond => 1_000_000,
Self::Second => 1_000_000_000,
Self::Minute => 60 * 1_000_000_000,
Self::Hour => 3_600 * 1_000_000_000,
Self::Day => 86_400 * 1_000_000_000,
Self::Week => 604_800 * 1_000_000_000,
}
}
}
impl Duration {
pub fn from_units(value: i128, unit: DurationUnit) -> Result<Self> {
value
.checked_mul(unit.nanoseconds())
.map(Self)
.ok_or_else(|| Error::Data("elapsed duration exceeds exact nanosecond range".into()))
}
}
macro_rules! temporal_column {
($name:ident, $element:ty, $read:ty, $read_value:expr, $doc:literal $(, $extra:ident: $extra_type:ty)*) => {
#[doc = $doc]
#[derive(Debug, Clone)]
pub struct $name {
name: std::sync::Arc<str>,
values: std::sync::Arc<[Option<$element>]>,
source: super::binding::VectorSource,
$($extra: $extra_type,)*
}
impl $name {
pub fn new(
name: impl Into<String>,
$($extra: $extra_type,)*
values: impl IntoIterator<Item = $element>,
) -> Result<Self> {
Self::nullable(name, $($extra,)* values.into_iter().map(Some))
}
pub fn nullable(
name: impl Into<String>,
$($extra: $extra_type,)*
values: impl IntoIterator<Item = Option<$element>>,
) -> Result<Self> {
let values = super::source::collect_source(values.into_iter().map(Ok))?;
Ok(Self {
name: std::sync::Arc::from(name.into()),
source: super::binding::VectorSource::direct(values.len()),
values: values.into(),
$($extra,)*
})
}
#[doc(hidden)]
pub fn get_source(&self) -> &super::DataSourceInfo { self.source.info() }
pub fn name(&self) -> &str { &self.name }
pub fn len(&self) -> usize { self.values.len() }
pub fn is_empty(&self) -> bool { self.values.is_empty() }
pub fn get(&self, index: usize) -> Option<Option<$read>> {
self.values.get(index).map($read_value)
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<$read>> + '_ {
self.values.iter().map($read_value)
}
pub fn is_valid(&self, index: usize) -> Option<bool> {
self.values.get(index).map(Option::is_some)
}
}
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.values == other.values $(&& self.$extra == other.$extra)*
}
}
impl Eq for $name {}
};
}
temporal_column!(
DateValues,
Date,
Date,
|value: &Option<Date>| *value,
"An immutable nullable column of exact Gregorian dates."
);
temporal_column!(
TimeValues,
Timestamp,
&Timestamp,
Option::as_ref,
"An immutable nullable column of exact instants and timezone metadata."
);
temporal_column!(DurationValues, Duration, Duration, |value: &Option<Duration>| *value, "An immutable nullable column of exact elapsed durations.", unit: DurationUnit);
impl DurationValues {
pub const fn unit(&self) -> DurationUnit {
self.unit
}
}
#[cfg(test)]
mod column_tests {
use super::*;
#[test]
fn temporal_columns_keep_exact_original_values() {
let date = Date::new(2000, 2, 29).unwrap();
let dates = DateValues::nullable("date", [Some(date), None]).unwrap();
assert_eq!(dates.get(0), Some(Some(date)));
assert_eq!(dates.is_valid(1), Some(false));
assert_eq!(dates.get(2), None);
let instant = Timestamp::new(
-1,
999_999_999,
Some(TimeZone::FixedOffset(0)),
Some(0),
None,
)
.unwrap();
let times = TimeValues::nullable("time", [Some(instant), None]).unwrap();
assert_eq!(times.get(0).flatten().unwrap().unix_ns(), -1);
let duration = Duration::from_units(-17, DurationUnit::Microsecond).unwrap();
let elapsed =
DurationValues::nullable("elapsed", DurationUnit::Microsecond, [Some(duration), None])
.unwrap();
assert_eq!(elapsed.get(0).flatten().unwrap().nanoseconds(), -17_000);
assert_eq!(elapsed.unit(), DurationUnit::Microsecond);
assert!(Duration::from_units(i128::MAX, DurationUnit::Week).is_err());
}
}