strftime/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#![forbid(unsafe_code)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![allow(clippy::cast_possible_truncation)]
#![allow(unknown_lints)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(rust_2018_idioms)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unsafe_op_in_unsafe_fn)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]

//! This crate provides a Ruby 3.1.2 compatible `strftime` function, which
//! formats time according to the directives in the given format string.
//!
//! The directives begin with a percent `%` character. Any text not listed as a
//! directive will be passed through to the output string.
//!
//! Each directive consists of a percent `%` character, zero or more flags,
//! optional minimum field width, optional modifier and a conversion specifier
//! as follows:
//!
//! ```text
//! %<flags><width><modifier><conversion>
//! ```
//!
//! # Usage
//!
//! The various `strftime` functions in this crate take a generic _time_
//! parameter that implements the [`Time`] trait.
//!
//! # Format Specifiers
//!
//! ## Flags
//!
//! | Flag | Description                                                                            |
//! |------|----------------------------------------------------------------------------------------|
//! |  `-` | Use left padding, ignoring width and removing all other padding options in most cases. |
//! |  `_` | Use spaces for padding.                                                                |
//! |  `0` | Use zeros for padding.                                                                 |
//! |  `^` | Convert the resulting string to uppercase.                                             |
//! |  `#` | Change case of the resulting string.                                                   |
//!
//!
//! ## Width
//!
//! The minimum field width specifies the minimum width.
//!
//! ## Modifiers
//!
//! The modifiers are `E` and `O`. They are ignored.
//!
//! ## Specifiers
//!
//! | Specifier  | Example       | Description                                                                                                           |
//! |------------|---------------|-----------------------------------------------------------------------------------------------------------------------|
//! |    `%Y`    | `-2001`       | Year with century if provided, zero-padded to at least 4 digits plus the possible negative sign.                      |
//! |    `%C`    | `-21`         | `Year / 100` using Euclidean division, zero-padded to at least 2 digits.                                              |
//! |    `%y`    | `99`          | `Year % 100` in `00..=99`, using Euclidean remainder, zero-padded to 2 digits.                                        |
//! |    `%m`    | `01`          | Month of the year in `01..=12`, zero-padded to 2 digits.                                                              |
//! |    `%B`    | `July`        | Locale independent full month name.                                                                                   |
//! | `%b`, `%h` | `Jul`         | Locale independent abbreviated month name, using the first 3 letters.                                                 |
//! |    `%d`    | `01`          | Day of the month in `01..=31`, zero-padded to 2 digits.                                                               |
//! |    `%e`    | ` 1`          | Day of the month in ` 1..=31`, blank-padded to 2 digits.                                                              |
//! |    `%j`    | `001`         | Day of the year in `001..=366`, zero-padded to 3 digits.                                                              |
//! |    `%H`    | `00`          | Hour of the day (24-hour clock) in `00..=23`, zero-padded to 2 digits.                                                |
//! |    `%k`    | ` 0`          | Hour of the day (24-hour clock) in ` 0..=23`, blank-padded to 2 digits.                                               |
//! |    `%I`    | `01`          | Hour of the day (12-hour clock) in `01..=12`, zero-padded to 2 digits.                                                |
//! |    `%l`    | ` 1`          | Hour of the day (12-hour clock) in ` 1..=12`, blank-padded to 2 digits.                                               |
//! |    `%P`    | `am`          | Lowercase meridian indicator (`"am"` or `"pm"`).                                                                      |
//! |    `%p`    | `AM`          | Uppercase meridian indicator (`"AM"` or `"PM"`).                                                                      |
//! |    `%M`    | `00`          | Minute of the hour in `00..=59`, zero-padded to 2 digits.                                                             |
//! |    `%S`    | `00`          | Second of the minute in `00..=60`, zero-padded to 2 digits.                                                           |
//! |    `%L`    | `123`         | Truncated fractional seconds digits, with 3 digits by default. Number of digits is specified by the width field.      |
//! |    `%N`    | `123456789`   | Truncated fractional seconds digits, with 9 digits by default. Number of digits is specified by the width field.      |
//! |    `%z`    | `+0200`       | Zero-padded signed time zone UTC hour and minute offsets (`+hhmm`).                                                   |
//! |    `%:z`   | `+02:00`      | Zero-padded signed time zone UTC hour and minute offsets with colons (`+hh:mm`).                                      |
//! |    `%::z`  | `+02:00:00`   | Zero-padded signed time zone UTC hour, minute and second offsets with colons (`+hh:mm:ss`).                           |
//! |    `%:::z` | `+02`         | Zero-padded signed time zone UTC hour offset, with optional minute and second offsets with colons (`+hh[:mm[:ss]]`).  |
//! |    `%Z`    | `CEST`        | Platform-dependent abbreviated time zone name.                                                                        |
//! |    `%A`    | `Sunday`      | Locale independent full weekday name.                                                                                 |
//! |    `%a`    | `Sun`         | Locale independent abbreviated weekday name, using the first 3 letters.                                               |
//! |    `%u`    | `1`           | Day of the week from Monday in `1..=7`, zero-padded to 1 digit.                                                       |
//! |    `%w`    | `0`           | Day of the week from Sunday in `0..=6`, zero-padded to 1 digit.                                                       |
//! |    `%G`    | `-2001`       | Same as `%Y`, but using the ISO 8601 week-based year. [^1]                                                            |
//! |    `%g`    | `99`          | Same as `%y`, but using the ISO 8601 week-based year. [^1]                                                            |
//! |    `%V`    | `01`          | ISO 8601 week number in `01..=53`, zero-padded to 2 digits. [^1]                                                      |
//! |    `%U`    | `00`          | Week number from Sunday in `00..=53`, zero-padded to 2 digits. The week `1` starts with the first Sunday of the year. |
//! |    `%W`    | `00`          | Week number from Monday in `00..=53`, zero-padded to 2 digits. The week `1` starts with the first Monday of the year. |
//! |    `%s`    | `86400`       | Number of seconds since `1970-01-01 00:00:00 UTC`, zero-padded to at least 1 digit.                                   |
//! |    `%n`    | `\n`          | Newline character `'\n'`.                                                                                             |
//! |    `%t`    | `\t`          | Tab character `'\t'`.                                                                                                 |
//! |    `%%`    | `%`           | Literal `'%'` character.                                                                                              |
//! |    `%c`    | `Sun Jul  8 00:23:45 2001` | Date and time, equivalent to `"%a %b %e %H:%M:%S %Y"`.                                                   |
//! | `%D`, `%x` | `07/08/01`    | Date, equivalent to `"%m/%d/%y"`.                                                                                     |
//! |    `%F`    | `2001-07-08`  | ISO 8601 date, equivalent to `"%Y-%m-%d"`.                                                                            |
//! |    `%v`    | ` 8-JUL-2001` | VMS date, equivalent to `"%e-%^b-%4Y"`.                                                                               |
//! |    `%r`    | `12:23:45 AM` | 12-hour time, equivalent to `"%I:%M:%S %p"`.                                                                          |
//! |    `%R`    | `00:23`       | 24-hour time without seconds, equivalent to `"%H:%M"`.                                                                |
//! | `%T`, `%X` | `00:23:45`    | 24-hour time, equivalent to `"%H:%M:%S"`.                                                                             |
//!
//! [^1]: `%G`, `%g`, `%V`: Week 1 of ISO 8601 is the first week with at least 4
//! days in that year. The days before the first week are in the last week of
//! the previous year.

#![doc(html_root_url = "https://docs.rs/strftime-ruby/1.0.1")]
#![no_std]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "alloc")]
use alloc::collections::TryReserveError;

mod format;

#[cfg(test)]
mod tests;

/// Error type returned by the `strftime` functions.
#[derive(Debug)]
// To ensure the API is the same for all feature combinations, do not derive
// `Copy`. The `OutOfMemory` variant (when it is enabled by `alloc`) contains a
// member that is not `Copy`.
#[non_exhaustive]
#[allow(missing_copy_implementations)]
#[allow(variant_size_differences)]
pub enum Error {
    /// Provided time implementation returns invalid values.
    InvalidTime,
    /// Provided format string is ended by an unterminated format specifier.
    InvalidFormatString,
    /// Formatted string is too large and could cause an out-of-memory error.
    FormattedStringTooLarge,
    /// Provided buffer for the [`buffered::strftime`] function is too small for
    /// the formatted string.
    ///
    /// This corresponds to the [`std::io::ErrorKind::WriteZero`] variant.
    ///
    /// [`std::io::ErrorKind::WriteZero`]: <https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.WriteZero>
    WriteZero,
    /// Formatting error, corresponding to [`core::fmt::Error`].
    FmtError(core::fmt::Error),
    /// An allocation failure has occurred in either [`bytes::strftime`] or
    /// [`string::strftime`].
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    OutOfMemory(TryReserveError),
    /// An I/O error has occurred in [`io::strftime`].
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    IoError(std::io::Error),
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::InvalidTime => f.write_str("invalid time"),
            Error::InvalidFormatString => f.write_str("invalid format string"),
            Error::FormattedStringTooLarge => f.write_str("formatted string too large"),
            Error::WriteZero => f.write_str("failed to write the whole buffer"),
            Error::FmtError(_) => f.write_str("formatter error"),
            #[cfg(feature = "alloc")]
            Error::OutOfMemory(_) => f.write_str("allocation failure"),
            #[cfg(feature = "std")]
            Error::IoError(_) => f.write_str("I/O error"),
        }
    }
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::FmtError(inner) => Some(inner),
            Self::OutOfMemory(inner) => Some(inner),
            Self::IoError(inner) => Some(inner),
            _ => None,
        }
    }
}

impl From<core::fmt::Error> for Error {
    fn from(err: core::fmt::Error) -> Self {
        Self::FmtError(err)
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl From<TryReserveError> for Error {
    fn from(err: TryReserveError) -> Self {
        Self::OutOfMemory(err)
    }
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Self::IoError(err)
    }
}

/// Common methods needed for formatting _time_.
///
/// This should be implemented for structs representing a _time_.
///
/// All the `strftime` functions take as input an implementation of this trait.
pub trait Time {
    /// Returns the year for _time_ (including the century).
    fn year(&self) -> i32;
    /// Returns the month of the year in `1..=12` for _time_.
    fn month(&self) -> u8;
    /// Returns the day of the month in `1..=31` for _time_.
    fn day(&self) -> u8;
    /// Returns the hour of the day in `0..=23` for _time_.
    fn hour(&self) -> u8;
    /// Returns the minute of the hour in `0..=59` for _time_.
    fn minute(&self) -> u8;
    /// Returns the second of the minute in `0..=60` for _time_.
    fn second(&self) -> u8;
    /// Returns the number of nanoseconds in `0..=999_999_999` for _time_.
    fn nanoseconds(&self) -> u32;
    /// Returns an integer representing the day of the week in `0..=6`, with
    /// `Sunday == 0`.
    fn day_of_week(&self) -> u8;
    /// Returns an integer representing the day of the year in `1..=366`.
    fn day_of_year(&self) -> u16;
    /// Returns the number of seconds as a signed integer since the Epoch.
    fn to_int(&self) -> i64;
    /// Returns true if the time zone is UTC.
    fn is_utc(&self) -> bool;
    /// Returns the offset in seconds between the timezone of _time_ and UTC.
    fn utc_offset(&self) -> i32;
    /// Returns the name of the time zone as a string.
    fn time_zone(&self) -> &str;
}

// Check that the Time trait is object-safe
const _: Option<&dyn Time> = None;

/// Format string used by Ruby [`Time#asctime`] method.
///
/// [`Time#asctime`]: <https://ruby-doc.org/core-3.1.2/Time.html#method-i-asctime>
pub const ASCTIME_FORMAT_STRING: &str = "%c";

/// Provides a `strftime` implementation using a format string with arbitrary
/// bytes, writing to a provided byte slice.
pub mod buffered {
    use super::{Error, Time};
    use crate::format::TimeFormatter;

    /// Format a _time_ implementation with the specified format byte string,
    /// writing in the provided buffer and returning the written subslice.
    ///
    /// See the [crate-level documentation](crate) for a complete description of
    /// possible format specifiers.
    ///
    /// # Allocations
    ///
    /// This `strftime` implementation makes no heap allocations and is usable
    /// in a `no_std` context.
    ///
    /// # Examples
    ///
    /// ```
    /// use strftime::buffered::strftime;
    /// use strftime::Time;
    ///
    /// // Not shown: create a time implementation with the year 1970
    /// // let time = ...;
    /// # include!("mock.rs.in");
    /// # fn main() -> Result<(), strftime::Error> {
    /// # let time = MockTime { year: 1970, ..Default::default() };
    /// assert_eq!(time.year(), 1970);
    ///
    /// let mut buf = [0u8; 8];
    /// assert_eq!(strftime(&time, b"%Y", &mut buf)?, b"1970");
    /// assert_eq!(buf, *b"1970\0\0\0\0");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce an [`Error`](crate::Error) when the formatting fails.
    pub fn strftime<'a>(
        time: &impl Time,
        format: &[u8],
        buf: &'a mut [u8],
    ) -> Result<&'a mut [u8], Error> {
        let len = buf.len();

        let mut cursor = &mut buf[..];
        TimeFormatter::new(time, format).fmt(&mut cursor)?;
        let remaining_len = cursor.len();

        Ok(&mut buf[..len - remaining_len])
    }
}

/// Provides a `strftime` implementation using a UTF-8 format string, writing to
/// a [`core::fmt::Write`] object.
pub mod fmt {
    use core::fmt::Write;

    use super::{Error, Time};
    use crate::format::{FmtWrite, TimeFormatter};

    /// Format a _time_ implementation with the specified UTF-8 format string,
    /// writing to the provided [`core::fmt::Write`] object.
    ///
    /// See the [crate-level documentation](crate) for a complete description of
    /// possible format specifiers.
    ///
    /// # Allocations
    ///
    /// This `strftime` implementation makes no heap allocations on its own, but
    /// the provided writer may allocate.
    ///
    /// # Examples
    ///
    /// ```
    /// use strftime::fmt::strftime;
    /// use strftime::Time;
    ///
    /// // Not shown: create a time implementation with the year 1970
    /// // let time = ...;
    /// # include!("mock.rs.in");
    /// # fn main() -> Result<(), strftime::Error> {
    /// # let time = MockTime { year: 1970, ..Default::default() };
    /// assert_eq!(time.year(), 1970);
    ///
    /// let mut buf = String::new();
    /// strftime(&time, "%Y", &mut buf)?;
    /// assert_eq!(buf, "1970");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce an [`Error`](crate::Error) when the formatting fails.
    pub fn strftime(time: &impl Time, format: &str, buf: &mut dyn Write) -> Result<(), Error> {
        TimeFormatter::new(time, format).fmt(&mut FmtWrite::new(buf))
    }
}

/// Provides a `strftime` implementation using a format string with arbitrary
/// bytes, writing to a newly allocated [`Vec`].
///
/// [`Vec`]: alloc::vec::Vec
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub mod bytes {
    use alloc::vec::Vec;

    use super::{Error, Time};
    use crate::format::TimeFormatter;

    /// Format a _time_ implementation with the specified format byte string.
    ///
    /// See the [crate-level documentation](crate) for a complete description of
    /// possible format specifiers.
    ///
    /// # Allocations
    ///
    /// This `strftime` implementation writes its output to a heap-allocated
    /// [`Vec`]. The implementation exclusively uses fallible allocation APIs
    /// like [`Vec::try_reserve`]. This function will return [`Error::OutOfMemory`]
    /// if there is an allocation failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use strftime::bytes::strftime;
    /// use strftime::Time;
    ///
    /// // Not shown: create a time implementation with the year 1970
    /// // let time = ...;
    /// # include!("mock.rs.in");
    /// # fn main() -> Result<(), strftime::Error> {
    /// # let time = MockTime { year: 1970, ..Default::default() };
    /// assert_eq!(time.year(), 1970);
    ///
    /// assert_eq!(strftime(&time, b"%Y")?, b"1970");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce an [`Error`](crate::Error) when the formatting fails.
    pub fn strftime(time: &impl Time, format: &[u8]) -> Result<Vec<u8>, Error> {
        let mut buf = Vec::new();
        TimeFormatter::new(time, format).fmt(&mut buf)?;
        Ok(buf)
    }
}

/// Provides a `strftime` implementation using a UTF-8 format string, writing to
/// a newly allocated [`String`].
///
/// [`String`]: alloc::string::String
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub mod string {
    use alloc::string::String;
    use alloc::vec::Vec;

    use super::{Error, Time};
    use crate::format::TimeFormatter;

    /// Format a _time_ implementation with the specified UTF-8 format string.
    ///
    /// See the [crate-level documentation](crate) for a complete description of
    /// possible format specifiers.
    ///
    /// # Allocations
    ///
    /// This `strftime` implementation writes its output to a heap-allocated
    /// [`Vec`]. The implementation exclusively uses fallible allocation APIs
    /// like [`Vec::try_reserve`]. This function will return [`Error::OutOfMemory`]
    /// if there is an allocation failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use strftime::string::strftime;
    /// use strftime::Time;
    ///
    /// // Not shown: create a time implementation with the year 1970
    /// // let time = ...;
    /// # include!("mock.rs.in");
    /// # fn main() -> Result<(), strftime::Error> {
    /// # let time = MockTime { year: 1970, ..Default::default() };
    /// assert_eq!(time.year(), 1970);
    ///
    /// assert_eq!(strftime(&time, "%Y")?, "1970");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce an [`Error`](crate::Error) when the formatting fails.
    pub fn strftime(time: &impl Time, format: &str) -> Result<String, Error> {
        let mut buf = Vec::new();
        TimeFormatter::new(time, format).fmt(&mut buf)?;
        Ok(String::from_utf8(buf).expect("formatted string should be valid UTF-8"))
    }
}

/// Provides a `strftime` implementation using a format string with arbitrary
/// bytes, writing to a [`std::io::Write`] object.
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub mod io {
    use std::io::Write;

    use super::{Error, Time};
    use crate::format::{IoWrite, TimeFormatter};

    /// Format a _time_ implementation with the specified format byte string,
    /// writing to the provided [`std::io::Write`] object.
    ///
    /// See the [crate-level documentation](crate) for a complete description of
    /// possible format specifiers.
    ///
    /// # Allocations
    ///
    /// This `strftime` implementation makes no heap allocations on its own, but
    /// the provided writer may allocate.
    ///
    /// # Examples
    ///
    /// ```
    /// use strftime::io::strftime;
    /// use strftime::Time;
    ///
    /// // Not shown: create a time implementation with the year 1970
    /// // let time = ...;
    /// # include!("mock.rs.in");
    /// # fn main() -> Result<(), strftime::Error> {
    /// # let time = MockTime { year: 1970, ..Default::default() };
    /// assert_eq!(time.year(), 1970);
    ///
    /// let mut buf = Vec::new();
    /// strftime(&time, b"%Y", &mut buf)?;
    /// assert_eq!(buf, *b"1970");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce an [`Error`](crate::Error) when the formatting fails.
    pub fn strftime(time: &impl Time, format: &[u8], buf: &mut dyn Write) -> Result<(), Error> {
        TimeFormatter::new(time, format).fmt(&mut IoWrite::new(buf))
    }
}

// Ensure code blocks in `README.md` compile.
//
// This module declaration should be kept at the end of the file, in order to
// not interfere with code coverage.
#[cfg(all(doctest, feature = "std"))]
#[doc = include_str!("../README.md")]
mod readme {}