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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! This module contains the types and functions to interact with the
//! `fluent` localization system.
//!
//! Most important is the [FluentLanguageLoader].
//!
//! ⚠️ *This module requires the following crate features to be activated: `fluent-system`.*

use crate::{I18nAssets, I18nEmbedError, LanguageLoader};

use arc_swap::ArcSwap;
pub use fluent_langneg::NegotiationStrategy;
pub use i18n_embed_impl::fluent_language_loader;

use fluent::{
    bundle::FluentBundle, FluentArgs, FluentAttribute, FluentMessage, FluentResource, FluentValue,
};
use fluent_syntax::ast::{self, Pattern};
use intl_memoizer::concurrent::IntlLangMemoizer;
use parking_lot::RwLock;
use std::{borrow::Cow, collections::HashMap, fmt::Debug, iter::FromIterator, sync::Arc};
use unic_langid::LanguageIdentifier;

struct LanguageBundle {
    language: LanguageIdentifier,
    bundle: FluentBundle<Arc<FluentResource>, IntlLangMemoizer>,
    resource: Arc<FluentResource>,
}

impl LanguageBundle {
    fn new(language: LanguageIdentifier, resource: FluentResource) -> Self {
        let mut bundle = FluentBundle::new_concurrent(vec![language.clone()]);
        let resource = Arc::new(resource);
        if let Err(errors) = bundle.add_resource(resource.clone()) {
            errors.iter().for_each(|error | {
                log::error!(target: "i18n_embed::fluent", "Error while adding resource to bundle: {0:?}.", error);
            })
        }
        Self {
            language,
            bundle,
            resource,
        }
    }
}

impl Debug for LanguageBundle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "LanguageBundle(language: {})", self.language)
    }
}

#[derive(Debug)]
struct LanguageConfig {
    language_bundles: Vec<LanguageBundle>,
    /// This maps a `LanguageIdentifier` to the index inside the
    /// `language_bundles` vector.
    language_map: HashMap<LanguageIdentifier, usize>,
}

#[derive(Debug)]
struct CurrentLanguages {
    /// Languages currently selected.
    languages: Vec<LanguageIdentifier>,
    /// Indexes into the [`LanguageConfig::language_bundles`] associated the
    /// currently selected [`CurrentLanguages::languages`].
    indices: Vec<usize>,
}

#[derive(Debug)]
struct FluentLanguageLoaderInner {
    language_config: Arc<RwLock<LanguageConfig>>,
    current_languages: CurrentLanguages,
}

/// [LanguageLoader] implemenation for the `fluent` localization
/// system. Also provides methods to access localizations which have
/// been loaded.
///
/// ⚠️ *This API requires the following crate features to be activated: `fluent-system`.*
#[derive(Debug)]
pub struct FluentLanguageLoader {
    inner: ArcSwap<FluentLanguageLoaderInner>,
    domain: String,
    fallback_language: unic_langid::LanguageIdentifier,
}

impl FluentLanguageLoader {
    /// Create a new `FluentLanguageLoader`, which loads messages for
    /// the specified `domain`, and relies on the specified
    /// `fallback_language` for any messages that do not exist for the
    /// current language.
    pub fn new<S: Into<String>>(
        domain: S,
        fallback_language: unic_langid::LanguageIdentifier,
    ) -> Self {
        let config = LanguageConfig {
            language_bundles: Vec::new(),
            language_map: HashMap::new(),
        };

        Self {
            inner: ArcSwap::new(Arc::new(FluentLanguageLoaderInner {
                language_config: Arc::new(RwLock::new(config)),
                current_languages: CurrentLanguages {
                    languages: vec![fallback_language.clone()],
                    indices: vec![],
                },
            })),
            domain: domain.into(),
            fallback_language,
        }
    }

    fn current_language_impl(
        &self,
        inner: &FluentLanguageLoaderInner,
    ) -> unic_langid::LanguageIdentifier {
        inner
            .current_languages
            .languages
            .first()
            .map_or_else(|| self.fallback_language.clone(), Clone::clone)
    }

    /// The languages associated with each actual currently loaded language bundle.
    pub fn current_languages(&self) -> Vec<unic_langid::LanguageIdentifier> {
        self.inner.load().current_languages.languages.clone()
    }

    /// Get a localized message referenced by the `message_id`.
    pub fn get(&self, message_id: &str) -> String {
        self.get_args_fluent(message_id, None)
    }

    /// A non-generic version of [FluentLanguageLoader::get_args()].
    pub fn get_args_concrete<'args>(
        &self,
        message_id: &str,
        args: HashMap<&'args str, FluentValue<'args>>,
    ) -> String {
        self.get_args_fluent(message_id, hash_map_to_fluent_args(args).as_ref())
    }

    /// A non-generic version of [FluentLanguageLoader::get_args()]
    /// accepting [FluentArgs] instead of a [HashMap].
    pub fn get_args_fluent<'args>(
        &self,
        message_id: &str,
        args: Option<&'args FluentArgs<'args>>,
    ) -> String {
        let inner = self.inner.load();
        let language_config = inner.language_config.read();
        inner
            .current_languages
            .indices
            .iter()
            .map(|&idx| &language_config.language_bundles[idx])
            .find_map(|language_bundle| language_bundle
                .bundle
                .get_message(message_id)
                .and_then(|m: FluentMessage<'_>| m.value())
                .map(|pattern: &Pattern<&str>| {
                    let mut errors = Vec::new();
                    let value = language_bundle.bundle.format_pattern(pattern, args, &mut errors);
                    if !errors.is_empty() {
                        log::error!(
                            target:"i18n_embed::fluent",
                            "Failed to format a message for language \"{}\" and id \"{}\".\nErrors\n{:?}.",
                            inner.current_languages.languages.first().unwrap_or(&self.fallback_language), message_id, errors
                        )
                    }
                    value.into()
                })
            )
            .unwrap_or_else(|| {
                log::error!(
                    target:"i18n_embed::fluent",
                    "Unable to find localization for language \"{}\" and id \"{}\".",
                    inner.current_languages.languages.first().unwrap_or(&self.fallback_language),
                    message_id
                );
                format!("No localization for id: \"{}\"", message_id)
            })
    }

    /// Get a localized message referenced by the `message_id`, and
    /// formatted with the specified `args`.
    pub fn get_args<'a, S, V>(&self, id: &str, args: HashMap<S, V>) -> String
    where
        S: Into<Cow<'a, str>> + Clone,
        V: Into<FluentValue<'a>> + Clone,
    {
        self.get_args_fluent(id, hash_map_to_fluent_args(args).as_ref())
    }

    /// Get a localized attribute referenced by the `message_id` and `attribute_id`.
    pub fn get_attr(&self, message_id: &str, attribute_id: &str) -> String {
        self.get_attr_args_fluent(message_id, attribute_id, None)
    }

    /// A non-generic version of [FluentLanguageLoader::get_attr_args()].
    pub fn get_attr_args_concrete<'args>(
        &self,
        message_id: &str,
        attribute_id: &str,
        args: HashMap<&'args str, FluentValue<'args>>,
    ) -> String {
        self.get_attr_args_fluent(
            message_id,
            attribute_id,
            hash_map_to_fluent_args(args).as_ref(),
        )
    }

    /// A non-generic version of [FluentLanguageLoader::get_attr_args()]
    /// accepting [FluentArgs] instead of a [HashMap].
    pub fn get_attr_args_fluent<'args>(
        &self,
        message_id: &str,
        attribute_id: &str,
        args: Option<&'args FluentArgs<'args>>,
    ) -> String {
        let inner = self.inner.load();
        let language_config = inner.language_config.read();
        let current_language = self.current_language_impl(&inner);

        language_config.language_bundles.iter().find_map(|language_bundle| {
            language_bundle
                .bundle
                .get_message(message_id)
                .and_then(|m: FluentMessage<'_>| {
                    m.get_attribute(attribute_id)
                    .map(|a: FluentAttribute<'_>| {
                        a.value()
                    })
                })
                .map(|pattern: &Pattern<&str>| {
                    let mut errors = Vec::new();
                    let value = language_bundle.bundle.format_pattern(pattern, args, &mut errors);
                    if !errors.is_empty() {
                        log::error!(
                            target:"i18n_embed::fluent",
                            "Failed to format a message for language \"{}\" and id \"{}\".\nErrors\n{:?}.",
                            current_language, message_id, errors
                        )
                    }
                    value.into()
                })
        })
        .unwrap_or_else(|| {
            log::error!(
                target:"i18n_embed::fluent",
                "Unable to find localization for language \"{}\", message id \"{}\" and attribute id \"{}\".",
                current_language,
                message_id,
                attribute_id
            );
            format!("No localization for message id: \"{message_id}\" and attribute id: \"{attribute_id}\"")
        })
    }

    /// Get a localized attribute referenced by the `message_id` and `attribute_id`, and
    /// formatted with the specified `args`.
    pub fn get_attr_args<'a, S, V>(
        &self,
        message_id: &str,
        attribute_id: &str,
        args: HashMap<S, V>,
    ) -> String
    where
        S: Into<Cow<'a, str>> + Clone,
        V: Into<FluentValue<'a>> + Clone,
    {
        self.get_attr_args_fluent(
            message_id,
            attribute_id,
            hash_map_to_fluent_args(args).as_ref(),
        )
    }

    /// Get a localized message referenced by the `message_id`.
    #[deprecated(
        since = "0.13.6",
        note = "Please use `select_languages(...).get(...)` instead"
    )]
    pub fn get_lang(&self, lang: &[&LanguageIdentifier], message_id: &str) -> String {
        self.select_languages(lang).get(message_id)
    }

    /// A non-generic version of [FluentLanguageLoader::get_lang_args()].
    #[deprecated(
        since = "0.13.6",
        note = "Please use `select_languages(...).get_args_concrete(...)` instead"
    )]
    pub fn get_lang_args_concrete<'source>(
        &self,
        lang: &[&LanguageIdentifier],
        message_id: &str,
        args: HashMap<&'source str, FluentValue<'source>>,
    ) -> String {
        self.select_languages(lang)
            .get_args_concrete(message_id, args)
    }

    /// A non-generic version of [FluentLanguageLoader::get_lang_args()]
    /// accepting [FluentArgs] instead of a [HashMap].
    #[deprecated(
        since = "0.13.6",
        note = "Please use `select_languages(...).get_args_fluent(...)` instead"
    )]
    pub fn get_lang_args_fluent<'args>(
        &self,
        lang: &[&LanguageIdentifier],
        message_id: &str,
        args: Option<&'args FluentArgs<'args>>,
    ) -> String {
        self.select_languages(lang)
            .get_args_fluent(message_id, args)
    }

    /// Get a localized message for the given language identifiers, referenced
    /// by the `message_id` and formatted with the specified `args`.
    #[deprecated(
        since = "0.13.6",
        note = "Please use `select_languages(...).get_args(...)` instead"
    )]
    pub fn get_lang_args<'a, S, V>(
        &self,
        lang: &[&LanguageIdentifier],
        id: &str,
        args: HashMap<S, V>,
    ) -> String
    where
        S: Into<Cow<'a, str>> + Clone,
        V: Into<FluentValue<'a>> + Clone,
    {
        self.select_languages(lang).get_args(id, args)
    }

    /// Get a localized attribute referenced by the `Message_id` and `attribute_id`.
    #[deprecated(
        since = "0.13.6",
        note = "Please use `select_languages(...).get_attr(...)` instead"
    )]
    pub fn get_lang_attr(
        &self,
        lang: &[&LanguageIdentifier],
        message_id: &str,
        attribute_id: &str,
    ) -> String {
        self.select_languages(lang)
            .get_attr(message_id, attribute_id)
    }

    /// A non-generic version of [FluentLanguageLoader::get_lang_attr_args()].
    #[deprecated(
        since = "0.13.6",
        note = "Please use `select_languages(...).get_attr_args_concrete(...)` instead"
    )]
    pub fn get_lang_attr_args_concrete<'source>(
        &self,
        lang: &[&LanguageIdentifier],
        message_id: &str,
        attribute_id: &str,
        args: HashMap<&'source str, FluentValue<'source>>,
    ) -> String {
        self.select_languages(lang)
            .get_attr_args_concrete(message_id, attribute_id, args)
    }

    /// A non-generic version of [FluentLanguageLoader::get_lang_attr_args()]
    /// accepting [FluentArgs] instead of a [HashMap].
    #[deprecated(
        since = "0.13.6",
        note = "Please use `select_languages(...).get_attr_args_fluent(...)` instead"
    )]
    pub fn get_lang_attr_args_fluent<'args>(
        &self,
        lang: &[&LanguageIdentifier],
        message_id: &str,
        attribute_id: &str,
        args: Option<&'args FluentArgs<'args>>,
    ) -> String {
        self.select_languages(lang)
            .get_attr_args_fluent(message_id, attribute_id, args)
    }

    /// Get a localized attribute referenced by the `message_id` and `attribute_id`
    /// and formatted with the `args`.
    #[deprecated(
        since = "0.13.6",
        note = "Please use `lang(...).get_attr_args(...)` instead"
    )]
    pub fn get_lang_attr_args<'a, S, V>(
        &self,
        lang: &[&LanguageIdentifier],
        message_id: &str,
        attribute_id: &str,
        args: HashMap<S, V>,
    ) -> String
    where
        S: Into<Cow<'a, str>> + Clone,
        V: Into<FluentValue<'a>> + Clone,
    {
        self.select_languages(lang)
            .get_attr_args(message_id, attribute_id, args)
    }

    /// available in any of the languages currently loaded (including
    /// the fallback language).
    pub fn has(&self, message_id: &str) -> bool {
        let mut has_message = false;

        self.inner
            .load()
            .language_config
            .read()
            .language_bundles
            .iter()
            .for_each(|language_bundle| {
                has_message |= language_bundle.bundle.has_message(message_id)
            });

        has_message
    }

    /// Determines if an attribute associated with the specified `message_id`
    /// is available in any of the currently loaded languages, including the fallback language.
    ///
    /// Returns true if at least one available instance was found,
    /// false otherwise.
    ///
    /// Note that this also returns false if the `message_id` could not be found;
    /// use [FluentLanguageLoader::has()] to determine if the `message_id` is available.
    pub fn has_attr(&self, message_id: &str, attribute_id: &str) -> bool {
        self.inner
            .load()
            .language_config
            .read()
            .language_bundles
            .iter()
            .find_map(|bundle| {
                bundle
                    .bundle
                    .get_message(message_id)
                    .map(|message| message.get_attribute(attribute_id).is_some())
            })
            .unwrap_or(false)
    }

    /// Run the `closure` with the message that matches the specified
    /// `message_id` (if it is available in any of the languages
    /// currently loaded, including the fallback language). Returns
    /// `Some` of whatever whatever the closure returns, or `None` if
    /// no messages were found matching the `message_id`.
    pub fn with_fluent_message<OUT, C>(&self, message_id: &str, closure: C) -> Option<OUT>
    where
        C: Fn(fluent::FluentMessage<'_>) -> OUT,
    {
        self.inner
            .load()
            .language_config
            .read()
            .language_bundles
            .iter()
            .find_map(|language_bundle| language_bundle.bundle.get_message(message_id))
            .map(closure)
    }

    /// Runs the provided `closure` with an iterator over the messages
    /// available for the specified `language`. There may be duplicate
    /// messages when they are duplicated in resources applicable to
    /// the language. Returns the result of the closure.
    pub fn with_message_iter<OUT, C>(&self, language: &LanguageIdentifier, closure: C) -> OUT
    where
        C: Fn(&mut dyn Iterator<Item = &ast::Message<&str>>) -> OUT,
    {
        let inner = self.inner.load();
        let config_lock = inner.language_config.read();

        let mut iter = config_lock
            .language_bundles
            .iter()
            .filter(|language_bundle| &language_bundle.language == language)
            .flat_map(|language_bundle| {
                language_bundle
                    .resource
                    .entries()
                    .filter_map(|entry| match entry {
                        ast::Entry::Message(message) => Some(message),
                        _ => None,
                    })
            });

        (closure)(&mut iter)
    }

    /// Set whether the underlying Fluent logic should insert Unicode
    /// Directionality Isolation Marks around placeables.
    ///
    /// See [`fluent::bundle::FluentBundleBase::set_use_isolating`] for more
    /// information.
    ///
    /// **Note:** This function will have no effect if
    /// [`LanguageLoader::load_languages`] has not been called first.
    ///
    /// Default: `true`.
    pub fn set_use_isolating(&self, value: bool) {
        self.with_bundles_mut(|bundle| bundle.set_use_isolating(value));
    }

    /// Apply some configuration to each budle in this loader.
    ///
    /// **Note:** This function will have no effect if
    /// [`LanguageLoader::load_languages`] has not been called first.
    pub fn with_bundles_mut<F>(&self, f: F)
    where
        F: Fn(&mut FluentBundle<Arc<FluentResource>, IntlLangMemoizer>),
    {
        for bundle in self
            .inner
            .load()
            .language_config
            .write()
            .language_bundles
            .as_mut_slice()
        {
            f(&mut bundle.bundle);
        }
    }
    /// Create a new loader with a subset of currently loaded languages.
    /// This is a rather cheap operation and does not require any
    /// extensive copy operations. Cheap does not mean free so you
    /// should not call this message repeatedly in order to translate
    /// multiple strings for the same language.
    #[deprecated(since = "0.13.7", note = "Please use `select_languages(...)` instead")]
    pub fn lang<LI: AsRef<LanguageIdentifier>>(&self, languages: &[LI]) -> FluentLanguageLoader {
        self.select_languages(languages)
    }

    /// Create a new loader with a subset of currently loaded languages.
    /// This is a rather cheap operation and does not require any
    /// extensive copy operations. Cheap does not mean free so you
    /// should not call this message repeatedly in order to translate
    /// multiple strings for the same language.
    pub fn select_languages<LI: AsRef<LanguageIdentifier>>(
        &self,
        languages: &[LI],
    ) -> FluentLanguageLoader {
        let inner = self.inner.load();
        let config_lock = inner.language_config.read();
        let fallback_language: Option<&unic_langid::LanguageIdentifier> = if languages
            .iter()
            .any(|language| language.as_ref() == &self.fallback_language)
        {
            None
        } else {
            Some(&self.fallback_language)
        };

        let indices = languages
            .iter()
            .map(|lang| lang.as_ref())
            .chain(fallback_language)
            .filter_map(|lang| config_lock.language_map.get(lang.as_ref()))
            .cloned()
            .collect();
        FluentLanguageLoader {
            inner: ArcSwap::new(Arc::new(FluentLanguageLoaderInner {
                current_languages: CurrentLanguages {
                    languages: languages.iter().map(|lang| lang.as_ref().clone()).collect(),
                    indices,
                },
                language_config: self.inner.load().language_config.clone(),
            })),
            domain: self.domain.clone(),
            fallback_language: self.fallback_language.clone(),
        }
    }

    /// Select the requested `languages` from the currently loaded languages using the supplied
    /// [`NegotiationStrategy`].
    pub fn select_languages_negotiate<LI: AsRef<LanguageIdentifier>>(
        &self,
        languages: &[LI],
        strategy: NegotiationStrategy,
    ) -> FluentLanguageLoader {
        let available_languages = &self.inner.load().current_languages.languages;
        let negotiated_languages = fluent_langneg::negotiate_languages(
            languages,
            available_languages,
            Some(self.fallback_language()),
            strategy,
        );

        self.select_languages(&negotiated_languages)
    }
}

impl LanguageLoader for FluentLanguageLoader {
    /// The fallback language for the module this loader is responsible
    /// for.
    fn fallback_language(&self) -> &unic_langid::LanguageIdentifier {
        &self.fallback_language
    }
    /// The domain for the translation that this loader is associated with.
    fn domain(&self) -> &str {
        &self.domain
    }

    /// The language file name to use for this loader.
    fn language_file_name(&self) -> String {
        format!("{}.ftl", self.domain())
    }

    /// Get the language which is currently selected for this loader.
    fn current_language(&self) -> unic_langid::LanguageIdentifier {
        self.current_language_impl(&self.inner.load())
    }

    /// Load the languages `language_ids` using the resources packaged
    /// in the `i18n_assets` in order of fallback preference. This
    /// also sets the [LanguageLoader::current_language()] to the
    /// first in the `language_ids` slice. You can use
    /// [select()](super::select()) to determine which fallbacks are
    /// actually available for an arbitrary slice of preferences.
    fn load_languages(
        &self,
        i18n_assets: &dyn I18nAssets,
        language_ids: &[&unic_langid::LanguageIdentifier],
    ) -> Result<(), I18nEmbedError> {
        if language_ids.is_empty() {
            return Err(I18nEmbedError::RequestedLanguagesEmpty);
        }

        // The languages to load
        let mut load_language_ids: Vec<unic_langid::LanguageIdentifier> =
            language_ids.iter().map(|id| (**id).clone()).collect();

        if !load_language_ids.contains(&self.fallback_language) {
            load_language_ids.push(self.fallback_language.clone());
        }

        let mut language_bundles = Vec::with_capacity(language_ids.len());

        for language in &load_language_ids {
            let (path, file) = self.language_file(language, i18n_assets);

            if let Some(file) = file {
                log::debug!(target:"i18n_embed::fluent", "Loaded language file: \"{0}\" for language: \"{1}\"", path, language);

                let file_string = String::from_utf8(file.to_vec())
                    .map_err(|err| I18nEmbedError::ErrorParsingFileUtf8(path.clone(), err))?
                    // TODO: Workaround for https://github.com/kellpossible/cargo-i18n/issues/57
                    // remove when https://github.com/projectfluent/fluent-rs/issues/213 is resolved.
                    .replace("\u{000D}\n", "\n");

                let resource = match FluentResource::try_new(file_string) {
                    Ok(resource) => resource,
                    Err((resource, errors)) => {
                        errors.iter().for_each(|err| {
                            log::error!(target: "i18n_embed::fluent", "Error while parsing fluent language file \"{0}\": \"{1:?}\".", path, err);
                        });
                        resource
                    }
                };

                let language_bundle = LanguageBundle::new(language.clone(), resource);

                language_bundles.push(language_bundle);
            } else {
                log::debug!(target:"i18n_embed::fluent", "Unable to find language file: \"{0}\" for language: \"{1}\"", path, language);
                if language == &self.fallback_language {
                    return Err(I18nEmbedError::LanguageNotAvailable(path, language.clone()));
                }
            }
        }

        self.inner.swap(Arc::new(FluentLanguageLoaderInner {
            current_languages: CurrentLanguages {
                languages: language_ids.iter().map(|&lang| lang.to_owned()).collect(),
                indices: (0..load_language_ids.len()).collect(),
            },
            language_config: Arc::new(RwLock::new(LanguageConfig {
                language_map: language_bundles
                    .iter()
                    .enumerate()
                    .map(|(i, language_bundle)| (language_bundle.language.clone(), i))
                    .collect(),
                language_bundles,
            })),
        }));

        Ok(())
    }
}

fn hash_map_to_fluent_args<'args, K, V>(map: HashMap<K, V>) -> Option<FluentArgs<'args>>
where
    K: Into<Cow<'args, str>>,
    V: Into<FluentValue<'args>>,
{
    if map.is_empty() {
        None
    } else {
        Some(FluentArgs::from_iter(map))
    }
}