time icon indicating copy to clipboard operation
time copied to clipboard

Make `format` methods localizable

Open tguichaoua opened this issue 9 months ago • 6 comments

It should be possible to make format methods localizable by passing a struct Localization with the month and weekday names. This struct is passed down to fmt_month and fmt_weekday methods that used it instead of the hardcoded MONTH_NAMES and WEEKDAY_NAMES.

pub struct Localization {
    pub month_names: [&[u8]; 12],
    pub weekday_names: [&[u8]; 7],
}

impl Localization {
    pub const EN: Self = Self { /* ... */ }
    pub const FR: Self = Self { /* ... */ }
    pub const DE: Self = Self { /* ... */ }
    pub const ES: Self = Self { /* ... */ }
     /* ... */
}

pub trait Sealed {
    fn format_into(
        &self,
        output: &mut impl Write,
        localization: &Localization,    // <-- new argument
        date: Option<Date>,
        time: Option<Time>,
        offset: Option<UtcOffset>
    ) -> Result<usize, Format>;

    fn format(
        &self,
        localization: &Localization,    // <-- new argument
        date: Option<Date>,
        time: Option<Time>,
        offset: Option<UtcOffset>
    ) -> Result<String, Format> { ... }
}

impl { Date, Time, ... } {
    pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
        // Preserve the current behaviour
        self.format_localized(format, &Localization::EN)
    }

    pub fn format_localized(self, format: &(impl Formattable + ?Sized), localization: &Localization) -> Result<String, error::Format> {
        format.format(localization, Some(self), None, None)
    }
}

tguichaoua avatar May 07 '24 12:05 tguichaoua