diff --git a/core/src/lib.rs b/core/src/lib.rs index 4c1e8738..9d42e69c 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -233,6 +233,28 @@ impl TypedValue { } } +trait MicrosecondPrecision { + /// Truncate the provided `DateTime` to microsecond precision. + fn microsecond_precision(self) -> Self; +} + +impl MicrosecondPrecision for DateTime { + fn microsecond_precision(self) -> DateTime { + let nanoseconds = self.nanosecond(); + if nanoseconds % 1000 == 0 { + return self; + } + let microseconds = nanoseconds / 1000; + let truncated = microseconds * 1000; + self.with_nanosecond(truncated).expect("valid timestamp") + } +} + +/// Return the current time as a UTC `DateTime` instance with microsecond precision. +pub fn now() -> DateTime { + Utc::now().microsecond_precision() +} + // We don't do From or From 'cos it's ambiguous. impl From for TypedValue { @@ -245,9 +267,7 @@ impl From for TypedValue { /// `TypedValue::Instant`. impl From> for TypedValue { fn from(value: DateTime) -> TypedValue { - let microseconds = value.nanosecond() / 1000; - let truncated = microseconds * 1000; - TypedValue::Instant(value.with_nanosecond(truncated).expect("valid timestamp")) + TypedValue::Instant(value.microsecond_precision()) } } diff --git a/db/src/lib.rs b/db/src/lib.rs index dc1f6b7f..f9416319 100644 --- a/db/src/lib.rs +++ b/db/src/lib.rs @@ -28,11 +28,6 @@ use std::iter::repeat; use itertools::Itertools; -use mentat_core::{ - DateTime, - Utc, -}; - pub use errors::{Error, ErrorKind, ResultExt, Result}; pub mod db; @@ -116,8 +111,3 @@ pub fn repeat_values(values_per_tuple: usize, tuples: usize) -> String { let values: String = repeat(inner).take(tuples).join(", "); values } - -/// Return the current time as a UTC `DateTime` instance. -pub fn now() -> DateTime { - Utc::now() -} diff --git a/db/src/tx.rs b/db/src/tx.rs index 03b2f0f3..45d11e6d 100644 --- a/db/src/tx.rs +++ b/db/src/tx.rs @@ -85,6 +85,7 @@ use mentat_core::{ Schema, Utc, attribute, + now, }; use mentat_core::intern_set::InternSet; @@ -654,7 +655,7 @@ impl<'conn, 'a> Tx<'conn, 'a> { } } - tx_instant = self.tx_instant.unwrap_or(::now()); + tx_instant = self.tx_instant.unwrap_or_else(now); // Transact [:db/add :db/txInstant NOW :db/tx] if it doesn't exist. if self.tx_instant == None {