Skip to content

[API Question] Why FluentBundle::format_pattern takes Option<'bundle FluentArgs> #260

Closed
@juliancoffee

Description

@juliancoffee

format_pattern has the following signature:

pub fn format_pattern<'bundle>(
       &'bundle self,
       pattern: &'bundle ast::Pattern<&str>,
       args: Option<&'bundle FluentArgs>,
       errors: &mut Vec<FluentError>,
) -> Cow<'bundle, str>

And if I read lifetimes right, it means that args must have the same lifetime as a result. And it's impossible to create args at runtime because their lifetime will be obviously less than the bundle.
I have this code for i18n in my app.

pub struct Locale {
    langs: HashMap<LanguageIdentifier, FluentBundle<FluentResource>>,
    current_lang: LanguageIdentifier,
}

impl Locale {
    fn bundle(&self) -> &FluentBundle<FluentResource> {
        self.langs
            .get(&self.current_lang)
            .expect("failed to get bundle for current locale")
    }

    pub fn try_msg_ctx(
        &self,
        key: &str,
        args: &[(&str, &str)],
    ) -> Option<String> {
        let bundle = self.bundle();
        let msg = bundle.get_message(key)?;

        let context = wrap(args);

        let mut errs = Vec::new();
        let msg =
            bundle.format_pattern(msg.value()?, Some(&context), &mut errs);
        for err in errs {
            eprintln!("err: {err}")
        }
        
        // notice into_owned here
        Some(msg.into_owned())
    }
}

And because the result of try_msg_ctx borrows lifetime from args, I can't use Cow here and am forced to use String. This means I need to duplicate the code to get message with arguments and without arguments because in the latter case I don't need to create a new string, I can just get it from the bundle, but in the former case, I obviously need to create an owned string. And it seems that I should be ok with just using Cow<'bundle, string>, but because format_pattern links args and result, it doesn't compile (because args will always have a lesser lifetime).
So, my understanding is wrong or things actually can be improved so that args can have their own lifetime?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions