datetimelike.rs
Overview
The [datetimelike.rs](/projects/287/67764) file defines internal utilities and abstractions for handling datetime-like objects in a Rust project. Its primary purpose is to provide a trait, `DateTimeLike`, which represents datetime objects capable of producing their components (year, month, day, hour, minute, second, microsecond, nanosecond) and formatting themselves into RFC3339-compliant string representations without heap allocation.
This file also includes helper macros for formatting numbers as zero-padded strings, an internal offset struct to represent timezone offsets, and an error enum for handling unsupported operations.
The focus on zero-allocation and efficient formatting makes this file a foundational piece for serializing datetime values, especially for use cases where performance and memory usage are critical (e.g., processing large volumes of timestamps).
Detailed Explanations
Enum: DateTimeError
Represents errors related to datetime operations within this module.
Variants:
LibraryUnsupported: Indicates that a required library or feature is unsupported in the current environment.
Macros
write_double_digit!
Writes a two-digit zero-padded number into a buffer.
Parameters:
$buf: A buffer implementingbytes::BufMutto which the output is written.$value: The integer value to write (expected to be less than 100).
Usage:
write_double_digit!(buf, 7); // Writes "07"
write_double_digit!(buf, 23); // Writes "23"
Behavior:
If the value is less than 10, it prefixes with '0' before writing the digits.
write_triple_digit!
Writes a three-digit zero-padded number into a buffer.
Parameters:
$buf: A buffer implementingbytes::BufMut.$value: The integer value to write (expected to be less than 1000).
Usage:
write_triple_digit!(buf, 7); // Writes "007"
write_triple_digit!(buf, 45); // Writes "045"
write_triple_digit!(buf, 123); // Writes "123"
Behavior:
Prefixes with enough zeros to ensure the output is always three digits.
Struct: Offset
Represents a timezone offset as a combination of day and second components.
Fields:
day: i32— The day offset relative to UTC (e.g., -1 or 0).second: i32— The offset in seconds within the day (range: 0 to 86400).
Default: Both fields initialized to zero.
Usage:
Used internally to represent timezone offsets when formatting datetime strings.
Trait: DateTimeLike
Defines the interface for datetime-like objects that can produce their component parts and write themselves as RFC3339 strings efficiently.
Trait Methods
Method | Description | Returns |
|---|---|---|
`year(&self)` | Returns the year component of the datetime. | `i32` |
`month(&self)` | Returns the month component (1-12). | `u8` |
`day(&self)` | Returns the day component (1-31). | `u8` |
`hour(&self)` | Returns the hour component (0-23). | `u8` |
`minute(&self)` | Returns the minute component (0-59). | `u8` |
`second(&self)` | Returns the second component (0-59). | `u8` |
`microsecond(&self)` | Returns the microseconds part of the time (0-999,999). | `u32` |
`nanosecond(&self)` | Returns the nanoseconds part of the time (0-999,999,999). | `u32` |
`has_tz(&self)` | Indicates if the datetime object is timezone-aware. | `bool` |
`slow_offset(&self)` | Provides a fallback method to get timezone offset without using zoneinfo data. Returns error if unsupported. | `Result` |
`offset(&self)` | Returns the timezone offset as an `Offset` struct. | `Result` |
`write_buf(&self, buf: &mut B, opts: Opt) -> Result<(), DateTimeError>` | Writes the datetime to a buffer in RFC3339 format based on formatting options. | `Result<(), DateTimeError>` |
write_buf Method Explanation
This method serializes the datetime-like object into an RFC3339-compliant string representation, writing directly into a mutable buffer implementing `bytes::BufMut`. It is optimized for minimal allocations and maximum speed.
Parameters:
buf: &mut B— The buffer to write into.opts: Opt— Formatting options to customize output; controls microsecond omission, UTC formatting, etc.
Returns:
Ok(())on successful writing.Err(DateTimeError)if an unsupported library or operation is encountered.
Formatting Details:
The output format is controlled closely to comply with RFC3339, including:YYYY-MM-DDTHH:MM:SS[.ffffff][Z|±HH:MM]Year is zero-padded to 4 digits.
Time components are zero-padded two-digit numbers.
Microseconds are written if non-zero and not disabled by options.
Nanosecond precision is currently not supported.
Timezone offset is written as 'Z' if zero offset and UTC_Z option enabled, otherwise as ±HH:MM.
Handles negative day offsets which can appear in some Python datetime timedelta representations (e.g., -05:00 offset).
Usage Example:
// Assume MyDateTime implements DateTimeLike
let dt: MyDateTime = ...;
let mut buf = bytes::BytesMut::new();
let options = Opt::default();
dt.write_buf(&mut buf, options).expect("Failed to write datetime");
let datetime_str = std::str::from_utf8(&buf).unwrap();
println!("Formatted datetime: {}", datetime_str);
Important Implementation Details and Algorithms
Zero Allocation Conversion:
Uses the third-party crateitoato convert integers to ASCII without intermediate heap allocations.Zero Padding via Macros:
Macroswrite_double_digit!andwrite_triple_digit!are used to efficiently zero-pad numeric values when writing to the buffer.Timezone Offset Handling:
TheOffsetstruct represents timezone offset split into days and seconds. The offset formatting accounts for edge cases such as offsets spanning days (e.g., -1 day + seconds).Optimizations:
Year formatting uses a static zero-padding trick by slicing a byte array.
Conditional compilation or option flags (
OMIT_MICROSECONDS,UTC_Z,NAIVE_UTC) control output format to balance precision and size.The method
write_bufis marked#[inline(never)]to reduce code bloat and improve inlining decisions elsewhere.
Interaction with Other Components
OptStruct (fromcrate::opt):
Controls formatting options such as whether to omit microseconds or use 'Z' for UTC offset. This file depends on these options to customize output.bytes::BufMutTrait:
The buffer abstraction used for writing output. Allows for zero-copy, efficient appending of bytes to buffers.itoacrate:
Used for integer-to-ASCII conversions without allocations.DateTime Implementations:
TheDateTimeLiketrait can be implemented by various datetime types in the codebase, including Python datetime wrappers or Rust datetime types converted from numpy or other sources.Error Handling:
TheDateTimeErrorenum supports error propagation when underlying features or libraries are unavailable.
Visual Diagram
The following Mermaid class diagram illustrates the structure of the main entities and their relationships in this file.
classDiagram
class DateTimeLike {
<<trait>>
+year() i32
+month() u8
+day() u8
+hour() u8
+minute() u8
+second() u8
+microsecond() u32
+nanosecond() u32
+has_tz() bool
+slow_offset() Result<Offset, DateTimeError>
+offset() Result<Offset, DateTimeError>
+write_buf<B>(&mut B, Opt) Result<(), DateTimeError>
}
class Offset {
+day: i32
+second: i32
+Default()
}
class DateTimeError {
<<enum>>
+LibraryUnsupported
}
DateTimeLike ..> Offset : returns offset
DateTimeLike ..> DateTimeError : may return error
Summary
[datetimelike.rs](/projects/287/67764) is a core utility module providing a zero-allocation, efficient interface to serialize datetime-like objects into RFC3339 strings. Its design abstracts over different datetime representations and ensures consistent, performant formatting with support for timezone offsets. The file is intended to be used internally by other modules that handle datetime serialization or manipulation and relies on formatting options and buffer traits to integrate seamlessly with the broader system.