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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! genie-lang reads language files into a map of UTF-8 strings.
//! All three major language file types used by Age of Empires versions are
//! supported: DLLs, INI files, and HD Edition's key-value format.
//!
//! DLLs are used by the original games.
//! INI files are used for Voobly mods, and can be used with a standard
//! AoC installation through the aoc-language-ini mod.
//!
//! ## DLLs
//! ```rust
//! # fn main() -> anyhow::Result<()> {
//! use genie_lang::{LangFileType::Dll, StringKey};
//! use std::{convert::TryFrom, fs::File};
//! let f = File::open("./test/dlls/language_x1_p1.dll")?;
//! let lang_file = Dll.read_from(f)?;
//! assert_eq!(
//!     lang_file.get(&StringKey::try_from(30177).unwrap()),
//!     Some(&String::from("Turbo Random Map - Buildings create units faster, villagers gather faster, build faster, and carry more.")));
//! assert_eq!(
//!     lang_file.get(&StringKey::try_from(20156).unwrap()),
//!     Some(&String::from("<b>Byzantines<b> \n\
//!           Defensive civilization \n\
//!           · Buildings +10% HPs Dark, +20% Feudal, \n +30% Castle, +40% Imperial Age \n\
//!           · Camels, skirmishers, Pikemen, Halberdiers cost -25% \n\
//!           · Fire ships +20% attack \n\
//!           · Advance to Imperial Age costs -33% \n\
//!           · Town Watch free \n\n\
//!           <b>Unique Unit:<b> Cataphract (cavalry) \n\n\
//!           <b>Unique Tech:<b> Logistica (Cataphracts cause trample damage) \n\n\
//!           <b>Team Bonus:<b> Monks +50% heal speed")));
//! # Ok(()) }
//! ```
//!
//! ## INI files
//! ```rust
//! # fn main() -> anyhow::Result<()> {
//! use genie_lang::{LangFileType::Ini, StringKey};
//! use std::{convert::TryFrom, io::Cursor};
//! let text = br#"
//! 46523=The Uighurs will join if you kill Ornlu the wolf and return to tell the tale.
//! ; a comment
//! 46524=Uighurs: Yes, that is the pelt of the great wolf. We will join you, Genghis Khan. And to seal the agreement, we will give you the gift of flaming arrows!
//! "#;
//! let f = Cursor::new(&text[..]);
//! let lang_file = Ini.read_from(f)?;
//! assert_eq!(
//!     lang_file.get(&StringKey::try_from(46523).unwrap()),
//!     Some(&String::from("The Uighurs will join if you kill Ornlu the wolf and return to tell the tale.")));
//! # Ok(()) }
//! ```
//!
//! ## HD key-value files
//! ```rust
//! # fn main() -> anyhow::Result<()> {
//! use genie_lang::{LangFileType::KeyValue, StringKey};
//! use std::{convert::TryFrom, io::Cursor};
//! let text = br#"
//! 46523 "The Uighurs will join if you kill Ornlu the wolf and return to tell the tale."
//! 46524 "Uighurs: Yes, that is the pelt of the great wolf. We will join you, Genghis Khan. And to seal the agreement, we will give you the gift of flaming arrows!"
//! 46604 "Kill the traitor, Kushluk.\n\nPrevent the tent of Genghis Khan (Wonder) from being destroyed."
//! LOBBYBROWSER_DATMOD_TITLE_FORMAT "DatMod: \"%s\""
//! "#;
//! let f = Cursor::new(&text[..]);
//! let lang_file = KeyValue.read_from(f)?;
//! assert_eq!(
//!     lang_file.get(&StringKey::try_from(46523).unwrap()),
//!     Some(&String::from("The Uighurs will join if you kill Ornlu the wolf and return to tell the tale.")));
//! assert_eq!(
//!     lang_file.get(&StringKey::from("LOBBYBROWSER_DATMOD_TITLE_FORMAT")),
//!     Some(&String::from(r#"DatMod: "%s""#)));
//! # Ok(()) }
//! ```
//!
//! ## Creating a file from scratch
//! ```rust
//! # fn main() -> anyhow::Result<()> {
//! use genie_lang::{LangFile, StringKey};
//! use std::{convert::TryFrom, str};
//! let mut lang_file = LangFile::new();
//! lang_file.insert(StringKey::try_from(46604).unwrap(), String::from("Kill the traitor, Kushluk.\n\n\
//!                       Prevent the tent of Genghis Khan (Wonder) from being destroyed."));
//! let mut out = vec![];
//! lang_file.write_to_ini(&mut out)?;
//! assert_eq!(
//!     str::from_utf8(&out)?,
//!     r"46604=Kill the traitor, Kushluk.\n\nPrevent the tent of Genghis Khan (Wonder) from being destroyed.
//! ");
//! lang_file.insert(StringKey::from("LOBBYBROWSER_DATMOD_TITLE_FORMAT"), String::from(r#"DatMod: "%s""#));
//! let mut out = vec![];
//! lang_file.write_to_keyval(&mut out)?;
//! let result_string = str::from_utf8(&out)?;
//! println!("{}", result_string);
//! assert!(
//!     result_string == r#"46604 "Kill the traitor, Kushluk.\n\nPrevent the tent of Genghis Khan (Wonder) from being destroyed."
//! LOBBYBROWSER_DATMOD_TITLE_FORMAT "DatMod: \"%s\""
//! "#
//!     ||
//!     result_string == r#"LOBBYBROWSER_DATMOD_TITLE_FORMAT "DatMod: \"%s\""
//! 46604 "Kill the traitor, Kushluk.\n\nPrevent the tent of Genghis Khan (Wonder) from being destroyed."
//! "#);
//! # Ok(()) }
//! ```

#![deny(future_incompatible)]
#![deny(nonstandard_style)]
#![deny(rust_2018_idioms)]
#![deny(unsafe_code)]
#![warn(missing_docs)]
#![warn(unused)]

use byteorder::{ReadBytesExt, LE};
use encoding_rs::{UTF_16LE, WINDOWS_1252};
use encoding_rs_io::DecodeReaderBytesBuilder;
pub use genie_support::{StringKey, TryFromStringKeyError};
use pelite::{
    pe32::{Pe, PeFile},
    resources::Name,
};
use std::collections::hash_map::{Drain, Entry, IntoIter, Iter, IterMut, Keys, Values, ValuesMut};
use std::collections::HashMap;
use std::fmt;
use std::io::{self, BufRead, BufReader, Error as IoError, Read, Write};
use std::iter::FromIterator;
use std::num::ParseIntError;
use std::ops::Index;
use std::str::FromStr;

/// Errors that may occur when loading a language file.
///
/// For DLL files, PeError and IoError can occur.
/// For INI and HD Edition files, ParseIntError and IoError can occur.
/// Both the INI and HD Edition parsers silently ignore invalid lines.
#[derive(Debug, thiserror::Error)]
pub enum LoadError {
    /// An error occurred while reading strings from the DLL.
    /// It probably does not contain any or is malformed.
    #[error(transparent)]
    PeError(#[from] pelite::Error),
    /// An error occurred while reading data from the file.
    #[error(transparent)]
    IoError(#[from] IoError),
    /// An error occurred while parsing a numeric string ID into an integer
    /// value.
    #[error(transparent)]
    ParseIntError(#[from] ParseIntError),
}

/// An error when parsing a string to a language file.
///
/// The field contains the string that could not be parsed.
#[derive(Debug, thiserror::Error)]
#[error("{}", self.0)]
pub struct ParseLangFileTypeError(String);

/// Aoe2 supports three types of language files
#[derive(Debug)]
pub enum LangFileType {
    /// An AoK/AoC-style DLL file with language resource strings.
    Dll,
    /// A Voobly-style .ini language file.
    Ini,
    /// An HD Edition key-value language file.
    KeyValue,
}

impl LangFileType {
    /// Reads a language file from an input reader.
    /// Returns a `LoadError` if an error occurs while reading.
    pub fn read_from(&self, r: impl Read) -> Result<LangFile, LoadError> {
        use LangFileType::{Dll, Ini, KeyValue};
        let mut lang_file = LangFile::new();
        let from_method = match self {
            Dll => LangFile::read_dll,
            Ini => LangFile::read_ini,
            KeyValue => LangFile::read_keyval,
        };
        from_method(&mut lang_file, r)?;
        Ok(lang_file)
    }
}

impl FromStr for LangFileType {
    type Err = ParseLangFileTypeError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use LangFileType::{Dll, Ini, KeyValue};
        match &s.to_lowercase()[..] {
            "dll" => Ok(Dll),
            "ini" => Ok(Ini),
            "key-value" => Ok(KeyValue),
            _ => Err(ParseLangFileTypeError(String::from(s))),
        }
    }
}

/// A mapping of `StringKey` key to `String` values.
///
/// May be read from or written to one of the three file formats for Aoe2
/// language files.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LangFile(HashMap<StringKey, String>);

impl LangFile {
    /// Reads a language file from a .DLL.
    /// This function eagerly loads all the strings into memory.
    ///
    /// Returns `Err(e)` where `e` is a `LoadError` if an error occurs while
    /// loading the file.
    fn read_dll(&mut self, mut input: impl Read) -> Result<(), LoadError> {
        let mut bytes = vec![];
        input.read_to_end(&mut bytes)?;
        let pe = PeFile::from_bytes(&bytes)?;
        self.load_pe_file(pe)
    }

    /// TODO specify
    fn load_pe_file(&mut self, pe: PeFile<'_>) -> Result<(), LoadError> {
        for root_dir_entry in pe.resources()?.root()?.entries() {
            if let Ok(Name::Id(6)) = root_dir_entry.name() {
                if let Some(directory) = root_dir_entry.entry()?.dir() {
                    self.load_pe_directory(directory)?;
                }
            }
        }
        Ok(())
    }

    /// TODO specify
    fn load_pe_directory(
        &mut self,
        directory: pelite::resources::Directory<'_>,
    ) -> Result<(), LoadError> {
        for entry in directory.entries() {
            let base_index = if let Name::Id(n) = entry.name()? {
                (n - 1) * 16
            } else {
                continue;
            };
            if let Some(subdir) = entry.entry()?.dir() {
                for data_entry in subdir.entries() {
                    if let Some(data) = data_entry.entry()?.data() {
                        self.load_pe_data(base_index, data.bytes()?)?;
                    }
                }
            }
        }
        Ok(())
    }

    /// TODO specify
    fn load_pe_data(&mut self, mut index: u32, data: &[u8]) -> Result<(), LoadError> {
        use std::io::{Cursor, Seek, SeekFrom};
        let mut cursor = Cursor::new(data);
        while (cursor.position() as usize) < data.len() {
            let len = (cursor.read_u16::<LE>()? as usize) * 2;
            if len == 0 {
                index += 1;
                continue;
            }
            let start = cursor.position() as usize;
            let (string, _enc, failed) = UTF_16LE.decode(&data[start..start + len]);
            if !failed {
                self.0.insert(StringKey::from(index), string.to_string());
            }
            cursor.seek(SeekFrom::Current(len as i64))?;
            index += 1;
        }
        Ok(())
    }

    /// Reads a language file from a .INI file, like the ones used by Voobly and
    /// the aoc-language-ini mod.
    ///
    /// This function eagerly loads all the strings into memory.
    /// At this time, the encoding of the language.ini file is assumed to be
    /// Windows codepage 1252.
    ///
    /// Returns `Err(e)` where `e` is a `LoadError` if an error occurs while
    /// loading the file.
    fn read_ini(&mut self, input: impl Read) -> Result<(), LoadError> {
        let input = DecodeReaderBytesBuilder::new()
            .encoding(Some(WINDOWS_1252))
            .build(input);
        let input = BufReader::new(input);
        for line in input.lines() {
            self.load_ini_line(&line?)?;
        }
        Ok(())
    }

    /// Parses a single line from an ini language file.
    ///
    /// The key value pair stored in the line is inserted to `self`, if parsed
    /// successfully.
    /// A `LoadError` is returned if an error occurs while parsing.
    ///
    /// Returns a `LoadError` if an error occurs while reading the line.
    fn load_ini_line(&mut self, line: &str) -> Result<(), LoadError> {
        if line.starts_with(';') {
            return Ok(());
        }

        let mut split = line.splitn(2, '=');
        let id = match split.next() {
            Some(id) => id,
            None => return Ok(()),
        };
        let value = match split.next() {
            Some(value) => value,
            None => return Ok(()),
        };

        let id: u32 = id.parse()?;
        let value = unescape(value.chars(), false);
        self.0.insert(StringKey::from(id), value);
        Ok(())
    }

    /// Reads a language file from an HD Edition-style key-value file.
    ///
    /// This function loads eagerly all the strings into memory.
    fn read_keyval(&mut self, input: impl Read) -> Result<(), LoadError> {
        let input = BufReader::new(input);
        for line in input.lines() {
            self.load_keyval_line(&line?)?;
        }
        Ok(())
    }

    /// Parses an HD Edition string line.
    ///
    /// The key value pair stored in the line is inserted to `self`, if parsed
    /// successfully.
    /// A `LoadError` is returned if an error occurs while parsing.
    ///
    /// This is incomplete, unquoting and un-escaping is not yet done.
    fn load_keyval_line(&mut self, line: &str) -> Result<(), LoadError> {
        let line = line.trim();
        if line.starts_with("//") || line.is_empty() {
            return Ok(());
        }

        let mut iter = line.chars();
        let id: String = iter
            .by_ref()
            .take_while(|&c| !char::is_whitespace(c))
            .collect();
        let string_key = StringKey::from(id);

        // TODO unquoting and un-escaping
        let mut iter = iter.skip_while(|&c| char::is_whitespace(c));
        let value = if let Some('"') = iter.next() {
            unescape(iter, true)
        } else {
            return Ok(());
        };
        self.0.insert(string_key, value);
        Ok(())
    }

    /// Writes this language file to an output writer using the ini format.
    pub fn write_to_ini<W: Write>(&self, output: &mut W) -> io::Result<()> {
        // TODO warning if there are string ids
        for (id, string) in self.iter().filter(|(id, _)| id.is_numeric()) {
            output.write_all(format!("{}={}\n", id, escape(string, false)).as_bytes())?;
        }
        Ok(())
    }

    /// Writes this language file to an output writer using the key-value
    /// format.
    pub fn write_to_keyval<W: Write>(&self, output: &mut W) -> io::Result<()> {
        for (id, string) in self.iter() {
            output.write_all(format!("{} \"{}\"\n", id, escape(string, true)).as_bytes())?;
        }
        Ok(())
    }

    /// Creates an empty language file.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::LangFile;
    ///
    /// let lang_file = LangFile::new();
    /// ```
    pub fn new() -> Self {
        LangFile(HashMap::new())
    }

    /// Returns `true` if this language file contains no key-value pairs,
    /// `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// assert!(lang_file.is_empty());
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from(""));
    /// assert!(!lang_file.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of key-value pairs in this language file.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// assert_eq!(0, lang_file.len());
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from(""));
    /// assert_eq!(1, lang_file.len());
    /// ```
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Removes all key-value pairs from this Language file.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from(""));
    /// lang_file.clear();
    /// assert!(lang_file.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.0.clear()
    }

    /// Clears this Language file, returning all key-value pairs as an iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("a"));
    /// lang_file.insert(StringKey::try_from(1).unwrap(), String::from("b"));
    ///
    /// for (k, v) in lang_file.drain().take(1) {
    ///     assert!(k == StringKey::try_from(0).unwrap() || k == StringKey::try_from(1).unwrap());
    ///     assert!(v == "a" || v == "b");
    /// }
    /// assert!(lang_file.is_empty());
    /// ```
    pub fn drain(&mut self) -> Drain<'_, StringKey, String> {
        self.0.drain()
    }

    /// Returns `true` if the map contains a value for key `k`, `false` if not.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from(""));
    /// assert!(lang_file.contains_key(&StringKey::try_from(0).unwrap()));
    /// assert!(!lang_file.contains_key(&StringKey::try_from(1).unwrap()));
    /// ```
    pub fn contains_key(&self, k: &StringKey) -> bool {
        self.0.contains_key(k)
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from(""));
    /// assert_eq!(Some(&String::from("")), lang_file.get(&StringKey::try_from(0).unwrap()));
    /// assert_eq!(None, lang_file.get(&StringKey::try_from(1).unwrap()));
    /// ```
    pub fn get(&self, k: &StringKey) -> Option<&String> {
        self.0.get(k)
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("a"));
    /// if let Some(s) = lang_file.get_mut(&StringKey::try_from(0).unwrap()) { s.push('A'); }
    /// assert_eq!("aA", lang_file.get(&StringKey::try_from(0).unwrap()).unwrap());
    /// ```
    pub fn get_mut(&mut self, k: &StringKey) -> Option<&mut String> {
        self.0.get_mut(k)
    }

    /// Returns the given key's corresponding entry in the language file.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("a"));
    /// let s0 = lang_file.entry(StringKey::try_from(0).unwrap())
    ///                   .or_insert(String::from("Hello"));
    /// s0.push('A');
    /// let s1 = lang_file.entry(StringKey::try_from(1).unwrap())
    ///                   .or_insert(String::from("Hello"));
    /// s1.push('A');
    /// assert_eq!("aA", lang_file.get(&StringKey::try_from(0).unwrap()).unwrap());
    /// assert_eq!("HelloA", lang_file.get(&StringKey::try_from(1).unwrap()).unwrap());
    /// ```
    pub fn entry(&mut self, key: StringKey) -> Entry<'_, StringKey, String> {
        self.0.entry(key)
    }

    /// Inserts a key-value pair into this language file.
    ///
    /// Returns `None`. if the language file did not have the key present.
    ///
    /// If the key was present, the value is updated, and the old value is
    /// returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("a"));
    /// assert!(!lang_file.is_empty());
    ///
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("b"));
    /// assert_eq!(Some(String::from("b")),
    ///            lang_file.insert(StringKey::try_from(0).unwrap(), String::from("c")));
    /// ```
    pub fn insert(&mut self, k: StringKey, v: String) -> Option<String> {
        self.0.insert(k, v)
    }

    /// Removes a key-value pair from the map, returning the value at the key
    /// if the key was previously in the map.
    /// Returns `None` if the key was not in the map.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from(""));
    /// assert_eq!(Some(String::from("")),
    ///            lang_file.remove(&StringKey::try_from(0).unwrap()));
    /// assert_eq!(None, lang_file.remove(&StringKey::try_from(0).unwrap()));
    /// ```
    pub fn remove(&mut self, k: &StringKey) -> Option<String> {
        self.0.remove(k)
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, removes all pairs `(k, v)` such that `f(&k, &mut v)`
    /// returns `false`.
    ///
    /// # Examples
    ///
    /// ```
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("zero"));
    /// lang_file.insert(StringKey::from("a"), String::from("a"));
    /// lang_file.insert(StringKey::try_from(1).unwrap(), String::from("one"));
    /// lang_file.insert(StringKey::from("2"), String::from("two"));
    /// lang_file.retain(|k, _| match k {
    ///     StringKey::Num(_) => true,
    ///     StringKey::Name(_) => false,
    /// });
    /// assert_eq!(3, lang_file.len());
    /// ```
    pub fn retain<F: FnMut(&StringKey, &mut String) -> bool>(&mut self, f: F) {
        self.0.retain(f)
    }

    /// An iterator visiting all key-value pairs in an arbitrary order.
    /// The iterator element type is `(&'a StringKey, &'a String)`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("zero"));
    /// lang_file.insert(StringKey::from("a"), String::from("a"));
    /// lang_file.insert(StringKey::try_from(1).unwrap(), String::from("one"));
    /// lang_file.insert(StringKey::from("2"), String::from("two"));
    ///
    /// for (k, v) in lang_file.iter() { println!("key: {}, val: {}", k, v); }
    /// ```
    pub fn iter(&self) -> Iter<'_, StringKey, String> {
        self.0.iter()
    }

    /// Returns an iterator that visits all key-values pairs in an arbitrary
    /// order, with mutable references to the values.
    /// The iterator element type is `(&'a StringKey, &'a mut String)`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("zero"));
    /// lang_file.insert(StringKey::from("a"), String::from("a"));
    /// lang_file.insert(StringKey::try_from(1).unwrap(), String::from("one"));
    /// lang_file.insert(StringKey::from("2"), String::from("two"));
    ///
    /// for (_, v) in lang_file.iter_mut() { v.push('A'); }
    /// for (k, v) in &lang_file { println!("key: {}, val: {}", k, v); }
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<'_, StringKey, String> {
        self.0.iter_mut()
    }

    /// Returns an iterator that visits all keys in arbitrary order.
    /// The iterator element type is `&'a StringKey`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("zero"));
    /// lang_file.insert(StringKey::from("a"), String::from("a"));
    /// lang_file.insert(StringKey::try_from(1).unwrap(), String::from("one"));
    /// lang_file.insert(StringKey::from("2"), String::from("two"));
    ///
    /// for k in lang_file.keys() { println!("key: {}", k); }
    /// ```
    pub fn keys(&self) -> Keys<'_, StringKey, String> {
        self.0.keys()
    }

    /// Returns an iterator that visits all values in arbitrary order.
    /// The iterator element type is `&'a String`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("zero"));
    /// lang_file.insert(StringKey::from("a"), String::from("a"));
    /// lang_file.insert(StringKey::try_from(1).unwrap(), String::from("one"));
    /// lang_file.insert(StringKey::from("2"), String::from("two"));
    ///
    /// for v in lang_file.values() { println!("value: {}", v); }
    /// ```
    pub fn values(&self) -> Values<'_, StringKey, String> {
        self.0.values()
    }

    /// Returns an iterator visiting all values mutable in arbitrary order.
    /// The iterator element type is `&'a mut String`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use genie_lang::{LangFile, StringKey};
    /// use std::convert::TryFrom;
    ///
    /// let mut lang_file = LangFile::new();
    /// lang_file.insert(StringKey::try_from(0).unwrap(), String::from("zero"));
    /// lang_file.insert(StringKey::from("a"), String::from("a"));
    /// lang_file.insert(StringKey::try_from(1).unwrap(), String::from("one"));
    /// lang_file.insert(StringKey::from("2"), String::from("two"));
    ///
    /// for v in lang_file.values_mut() { v.push('A'); }
    /// for v in lang_file.values() { println!("{}", v); }
    /// ```
    pub fn values_mut(&mut self) -> ValuesMut<'_, StringKey, String> {
        self.0.values_mut()
    }
}

impl IntoIterator for LangFile {
    type Item = (StringKey, String);
    type IntoIter = IntoIter<StringKey, String>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a LangFile {
    type Item = (&'a StringKey, &'a String);
    type IntoIter = Iter<'a, StringKey, String>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl<'a> IntoIterator for &'a mut LangFile {
    type Item = (&'a StringKey, &'a mut String);
    type IntoIter = IterMut<'a, StringKey, String>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter_mut()
    }
}

impl fmt::Display for LangFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let strs: Vec<String> = self
            .0
            .iter()
            .map(|(k, v)| format!("{}: {}", k, v))
            .collect();
        write!(f, "{}", strs.join("\n"))
    }
}

impl Extend<(StringKey, String)> for LangFile {
    fn extend<T: IntoIterator<Item = (StringKey, String)>>(&mut self, iter: T) {
        self.0.extend(iter);
    }
}

impl FromIterator<(StringKey, String)> for LangFile {
    fn from_iter<T: IntoIterator<Item = (StringKey, String)>>(iter: T) -> LangFile {
        let mut lang_file = LangFile::default();
        lang_file.extend(iter);
        lang_file
    }
}

impl Index<&StringKey> for LangFile {
    type Output = String;
    fn index(&self, key: &StringKey) -> &String {
        self.0.index(key)
    }
}

// TODO specify
fn unescape(escaped: impl Iterator<Item = char>, quoted: bool) -> String {
    let mut unescaped = String::new();
    let mut prev = 'x'; // Innocuous character
    for c in escaped {
        // NOTE this does not support escapes like "\\n", which should
        // print out "\n" literally, instead we get "\" followed by a newline.
        // Could be solved by making `prev` an Option
        match (prev, c) {
            ('\\', '\\') => unescaped.push('\\'),
            ('\\', 'n') => unescaped.push('\n'),
            ('\\', 'r') => unescaped.push('\r'),
            ('\\', 't') => unescaped.push('\t'),
            ('\\', '"') if quoted => unescaped.push('"'),
            (_, '"') if quoted => break,
            (_, '\\') => {} // Might be escape, wait for one more
            ('\\', c) => {
                // Previous character was escape,
                // but this is not part of a sequence
                unescaped.push('\\');
                unescaped.push(c);
            }
            (_, c) => unescaped.push(c),
        }
        prev = c;
    }
    unescaped
}

// TODO specify
fn escape(source: &str, quoted: bool) -> String {
    let mut escaped = String::new();
    for c in source.chars() {
        match c {
            '\\' => escaped.push_str(r"\\"),
            '\n' => escaped.push_str(r"\n"),
            '\r' => escaped.push_str(r"\r"),
            '\t' => escaped.push_str(r"\t"),
            '"' if quoted => escaped.push_str(r#"\""#),
            c => escaped.push(c),
        }
    }
    escaped
}