es_fluent/traits/
fluent_display.rs

1use std::fmt;
2
3/// A trait for types that can be displayed in a Fluent message.
4///
5/// This is a counterpart to `std::fmt::Display`, but specifically for generating
6/// strings that are meant to be used with Fluent. The derive macro for `es-fluent`
7/// can implement this trait for your types.
8pub trait FluentDisplay {
9    /// Formats the value using the given formatter.
10    fn fluent_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
11}
12
13/// Extension trait that provides `to_fluent_string`.
14pub trait ToFluentString {
15    /// Converts a value to a `String` for use in Fluent.
16    fn to_fluent_string(&self) -> String;
17}
18
19impl<T: FluentDisplay + ?Sized> ToFluentString for T {
20    fn to_fluent_string(&self) -> String {
21        struct FluentDisplayWrapper<'a, T: ?Sized> {
22            inner: &'a T,
23        }
24
25        impl<'a, T: FluentDisplay + ?Sized> fmt::Display for FluentDisplayWrapper<'a, T> {
26            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27                self.inner.fluent_fmt(f)
28            }
29        }
30
31        FluentDisplayWrapper { inner: self }.to_string()
32    }
33}