Skip to content

Commit

Permalink
refactor TimeError
Browse files Browse the repository at this point in the history
- define individual error `SystemTimeError`.
- do not re-export std's `SystemTimeError`.
- update feature-gates.
joseluis committed Jan 12, 2025
1 parent be8e9e2 commit efcd4da
Showing 6 changed files with 57 additions and 68 deletions.
4 changes: 2 additions & 2 deletions DOCS/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -28,7 +28,7 @@ The format is based on [Keep a Changelog], and this project adheres to
- new structs:
- `Interval`, `Pnm`.
- new namespaces: `Alloc`, `Arch`, `ByteSearch`, `Char`, `Env`, `Mem`, `Ptr`, `Str`.
- new standalone error types: `FailedErrorConversion`, `DataNotEnough`, `NotImplemented`, `NotSupported`, `ElementNotFound`, `InvalidAxisLength`, `KeyAlreadyExists`, `MismatchedCapacity`, `MismatchedDimensions`, `MismatchedIndices`, `NodeEmpty`, `NodeLinkNotSet`, `NodeLinkNotUnique`, `NotEnoughElements`, `NotEnoughSpace`, `IndexOutOfBounds`, `DataOverflow`, `PartiallyAdded`.
- new standalone error types: `FailedErrorConversion`, `DataNotEnough`, `NotImplemented`, `NotSupported`, `ElementNotFound`, `InvalidAxisLength`, `KeyAlreadyExists`, `MismatchedCapacity`, `MismatchedDimensions`, `MismatchedIndices`, `NodeEmpty`, `NodeLinkNotSet`, `NodeLinkNotUnique`, `NotEnoughElements`, `NotEnoughSpace`, `IndexOutOfBounds`, `DataOverflow`, `PartiallyAdded`, `InvalidChar`, `InvalidUtf8`, `SystemTimeError`.
- new composite error types: `NotAvailable`, `DataNotEnough`, `MismatchedBounds`, `PartialSpace`.
- `False`, `True`, `UnitBi`, `UnitSi`.
- `HasherPengy`.
@@ -84,7 +84,7 @@ The format is based on [Keep a Changelog], and this project adheres to
- `NonZero`, `Saturating`, `Wrapping`, `OsStr`, `OsString`.
- `HashMapEntry` and `BTreeMapEntry`.
- `HashMap` and `BTreeMap` from `std` if `hashbrown` is disabled.
- `FromStr`, `IterChars`, `Utf8Error`.
- `FromStr`, `IterChars`.
- crate items from multiple related modules, like errors and strings.
- new modules: `num::alg`, `sys::sound`, `media::{audio, color, draw, font, image, layout}`, `phys`, `ui`.
- new `sys::os::linux` module and example `linux`.
3 changes: 0 additions & 3 deletions src/phys/mod.rs
Original file line number Diff line number Diff line change
@@ -9,8 +9,6 @@
// safety
#![cfg_attr(feature = "safe_phys", forbid(unsafe_code))]

// #[cfg(feature = "time")]
// #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "time")))]
pub mod time;

crate::items! { // structural access: _mods, _all, _always
@@ -20,7 +18,6 @@ crate::items! { // structural access: _mods, _all, _always
pub use _always::*;

mod _mods {
// #[cfg(feature = "time")]
pub use super::time::_all::*;
}
pub(super) mod _all {
87 changes: 40 additions & 47 deletions src/phys/time/error.rs
Original file line number Diff line number Diff line change
@@ -3,60 +3,53 @@
//!
//

use super::Duration;

#[doc = crate::TAG_RESULT!()]
/// A time-related result.
pub type TimeResult<T> = crate::Result<T, TimeError>;

/// A time-related error.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TimeError {
/// The `Duration` from a [`SystemTimeError`][std::time::SystemTimeError].
///
/// Used to learn how far in the opposite direction a [`SystemTime`][super::SystemTime] lies.
// IMPROVE: generalize.
SystemTimeError(Duration),
use crate::impl_error;
#[cfg(feature = "std")]
use crate::Duration;

/// The given value is out of bounds.
OutOfBounds(Option<usize>),
#[cfg(feature = "std")]
use std::time::SystemTimeError as StdSystemTimeError;

impl_error! { individual:
#[cfg(feature = "std")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "std")))]
pub struct SystemTimeError(Duration);
DOC_SYSTEM_TIME_ERROR =
"An error returned from the `duration_since` and `elapsed` methods on `SystemTime`.\n\n
This is basically a replication of `std::time::`[`SystemTimeError`][StdSystemTimeError].",
self+f => write!(f, "SystemTimeError difference: {:?}", self.0)
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "std")))]
mod std_impls {
use super::TimeError;
use std::time::SystemTimeError;

impl From<SystemTimeError> for TimeError {
fn from(time: SystemTimeError) -> Self {
TimeError::SystemTimeError(time.duration())
}
impl From<StdSystemTimeError> for SystemTimeError {
fn from(from: StdSystemTimeError) -> Self {
SystemTimeError(from.duration())
}
}

mod core_impls {
use crate::{impl_trait, TimeError};

impl crate::Error for TimeError {}
impl crate::ExtError for TimeError {
type Kind = ();
fn error_eq(&self, other: &Self) -> bool {
self == other
#[cfg(all(feature = "error", feature = "time"))]
pub use full_composite::*;
#[cfg(all(feature = "error", feature = "time"))]
#[cfg_attr(feature = "nightly_doc", doc(cfg(all(feature = "error", feature = "time"))))]
mod full_composite {
use super::*;
use crate::{DataOverflow, DOC_DATA_OVERFLOW};

#[doc = crate::TAG_RESULT!()]
/// A text-related result.
pub type TimeResult<T> = crate::Result<T, TimeError>;

impl_error! { composite: fmt(f)
/// A text-related composite error.
#[non_exhaustive]
pub enum TimeError {
DOC_DATA_OVERFLOW:
DataOverflow(o|0: Option<usize>) => DataOverflow(*o),

#[cfg(feature = "std")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "std")))]
DOC_SYSTEM_TIME_ERROR:
SystemTime(d|0: Duration) => SystemTimeError(*d),
}
fn error_kind(&self) -> Self::Kind {}
}
impl_trait! { fmt::Display for TimeError |self, f| {
use TimeError as E;
match self {
E::SystemTimeError(d) => {
write!(f, "SystemTimeError({d:?})")
}
E::OutOfBounds(v) => match v {
Some(v) => write!(f, "The given value {v} is out of bounds."),
None => write!(f, "The given value is out of bounds."),
},
}
}}
}
8 changes: 4 additions & 4 deletions src/phys/time/mod.rs
Original file line number Diff line number Diff line change
@@ -7,12 +7,12 @@
// safety
#![cfg_attr(feature = "safe_time", forbid(unsafe_code))]

mod error;
mod reexports;

#[cfg(feature = "time")]
crate::items! {
mod calendar;
mod error;
mod fmt;
mod no;
mod split;
@@ -25,12 +25,12 @@ crate::items! { // structural access: _mods, _all, _always
#[allow(unused)] #[doc(hidden)] #[doc(no_inline)]
pub use _always::*;

mod _mods {
pub use super::reexports::*;
mod _mods { #![allow(unused)]
pub use super::{error::*, reexports::*};

#[cfg(feature = "time")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "time")))]
pub use super::{calendar::*, error::*, fmt::*, no::*, split::*, unix::*};
pub use super::{calendar::*, fmt::*, no::*, split::*, unix::*};
}
pub(super) mod _all {
#[doc(inline)]
10 changes: 5 additions & 5 deletions src/phys/time/reexports.rs
Original file line number Diff line number Diff line change
@@ -27,11 +27,11 @@ reexport! { rust: std::time,
doc: "A measurement of the system clock.",
SystemTime
}
reexport! { rust: std::time,
tag: crate::TAG_ERROR!(),
doc: "Error returned from the `duration_since` and `elapsed` methods on [`SystemTime`].",
SystemTimeError
}
// reexport! { rust: std::time,
// tag: crate::TAG_ERROR!(),
// doc: "Error returned from the `duration_since` and `elapsed` methods on [`SystemTime`].",
// SystemTimeError
// }
reexport! { rust: std::time,
doc: "A [`SystemTime`] anchored to “1970-01-01 00:00:00 UTC”.",
UNIX_EPOCH
13 changes: 6 additions & 7 deletions src/phys/time/unix.rs
Original file line number Diff line number Diff line change
@@ -313,7 +313,7 @@ impl TryFrom<UnixTimeI64> for UnixTimeU32 {
#[cfg(feature = "std")]
mod std_impls {
#[cfg(feature = "cast")]
use crate::{Cast, TimeError, UnixTimeU32};
use crate::{Cast, DataOverflow, UnixTimeU32};
use crate::{SystemTime, SystemTimeError, UnixTimeI64};

impl TryFrom<SystemTime> for UnixTimeI64 {
@@ -327,16 +327,15 @@ mod std_impls {
}
}

#[cfg(feature = "cast")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "cast")))]
#[cfg(all(feature = "cast", feature = "error"))]
#[cfg_attr(feature = "nightly_doc", doc(cfg(all(feature = "cast", feature = "error"))))]
impl TryFrom<SystemTime> for UnixTimeU32 {
type Error = TimeError;
type Error = crate::TimeError;

fn try_from(time: SystemTime) -> Result<Self, Self::Error> {
let since = time.duration_since(SystemTime::UNIX_EPOCH)?;
let seconds = u32::try_from(since.as_secs()).map_err(|_| {
TimeError::OutOfBounds(Cast(since.as_secs()).checked_cast_to_usize().ok())
})?;
let seconds = u32::try_from(since.as_secs())
.map_err(|_| DataOverflow(Cast(since.as_secs()).checked_cast_to_usize().ok()))?;
Ok(UnixTimeU32 { seconds })
}
}

0 comments on commit efcd4da

Please sign in to comment.