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
// Copyright 2016 John D. Hume
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! Support for formatting and parsing of monetary values.
//!
//! A style of formatting is described by a `FormatSpec`, which provides a function to wrap a
//! `Money` or `SmallMoney` in a `Display`-implementing struct for use in `format!`, `println!`,
//! etc.
//!
//! ```
//! use steel_cent::Money;
//! use steel_cent::currency::USD;
//! use steel_cent::formatting::{us_style, FormatSpec};
//! use steel_cent::formatting::FormatPart::*;
//!
//! let money = Money::of_minor(USD, -123);
//! let custom_spec = FormatSpec::new(',', '.', vec![OptionalMinus, CurrencySymbol, Amount])
//!                       .with_short_symbol(USD, String::from("$"));
//! assert_eq!("total: ($1.23)",
//!            format!("total: {}", us_style().display_for(&money)));
//! assert_eq!("total: -$1.23",
//!            format!("total: {}", custom_spec.display_for(&money)));
//! ```
//!
//! If you just need a formatted money `String` without additional context, use the `format` fn
//! directly.
//!
//! A `FormatSpec` can also be used to create a `Parser` for strings of the specified format.

use currency::{self, Currency};
use std::collections::HashMap;
use std::fmt;
use std::error::Error;

const NBSP: char = '\u{a0}';

/// Elements that can appear in a `FormatSpec` template.
///
/// New variants may be added, so please don't create exhaustive matches.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum FormatPart {
    Amount,
    CurrencySymbol,
    OptionalMinus,
    OptionalMinusOpenParenthesis,
    OptionalMinusCloseParenthesis,
    NonBreakingSpace,
    #[doc(hidden)]
    __Nonexhaustive,
}

/// A specification of a currency format.
#[derive(PartialEq, Eq, Clone)]
pub struct FormatSpec {
    thousands_separator: char,
    decimal_separator: char,
    short_currency_symbols: HashMap<Currency, String>,
    template: Vec<FormatPart>,
}

impl FormatSpec {
    /// Creates a new `FormatSpec` with no short symbol mappings.
    pub fn new(thousands_sep: char, decimal_sep: char, template: Vec<FormatPart>) -> FormatSpec {
        FormatSpec {
            thousands_separator: thousands_sep,
            decimal_separator: decimal_sep,
            short_currency_symbols: HashMap::new(),
            template: template,
        }
    }

    /// Creates a clone with the given short symbol mapping added.
    pub fn with_short_symbol(&self, currency: Currency, symbol: String) -> FormatSpec {
        let mut result = self.clone();
        result.short_currency_symbols.insert(currency, symbol);
        result
    }

    /// Creates a `Display` wrapper for the given money value using this spec.
    ///
    /// ```
    /// # use steel_cent::Money;
    /// # use steel_cent::currency::*;
    /// # use steel_cent::formatting::*;
    /// assert_eq!("$1.00", format!("{}", us_style().display_for(&Money::of_major(USD, 1))));
    /// assert_eq!("GBP1.00", format!("{}", us_style().display_for(&Money::of_major(GBP, 1))));
    /// ```
    pub fn display_for<'a, 'b, T: FormattableMoney>(&'a self,
                                                    money: &'b T)
                                                    -> MoneyDisplay<'b, 'a, T> {
        MoneyDisplay {
            money: money,
            spec: self,
        }
    }

    /// Creates a `Parser` that will parse strings conforming to this `FormatSpec`.
    ///
    /// ```
    /// # use steel_cent::Money;
    /// # use steel_cent::currency::*;
    /// # use steel_cent::formatting::*;
    /// assert_eq!(Ok(Money::of_major(USD, 1)), us_style().parser().parse("$1.00"));
    /// assert_eq!(Ok(Money::of_major(GBP, 1)), us_style().parser().parse("GBP1.00"));
    /// ```
    pub fn parser(&self) -> Parser {
        let mut parser = Parser::new(self.thousands_separator, self.decimal_separator, self.template.clone());
        for (currency, symbol) in &self.short_currency_symbols {
            parser = parser.with_short_symbol(currency.clone(), symbol.clone());
        }
        parser
    }
}

lazy_static!{
    static ref STYLE_GENERIC: FormatSpec = FormatSpec::new(
        ',', '.', vec![FormatPart::OptionalMinus,
                       FormatPart::Amount,
                       FormatPart::NonBreakingSpace,
                       FormatPart::CurrencySymbol]);

    static ref STYLE_FRANCE: FormatSpec = FormatSpec::new(
        NBSP, ',', vec![FormatPart::OptionalMinus,
                        FormatPart::Amount,
                        FormatPart::NonBreakingSpace,
                        FormatPart::CurrencySymbol])
        .with_short_symbol(currency::EUR, String::from("€"));

    static ref STYLE_UK: FormatSpec = FormatSpec::new(
        ',', '.', vec![FormatPart::OptionalMinus, FormatPart::CurrencySymbol, FormatPart::Amount])
        .with_short_symbol(currency::GBP, String::from("£"));

    static ref STYLE_US: FormatSpec = FormatSpec::new(
        ',', '.', vec![FormatPart::OptionalMinusOpenParenthesis,
                       FormatPart::CurrencySymbol,
                       FormatPart::Amount,
                       FormatPart::OptionalMinusCloseParenthesis])
        .with_short_symbol(currency::USD, String::from("$"));
}

/// A generic (US- and UK-friendly) readable style with no short symbol mappings.
///
/// ```
/// # use steel_cent::Money;
/// # use steel_cent::currency::*;
/// # use steel_cent::formatting::*;
/// assert_eq!("1,234.56\u{a0}GBP",
///            format(generic_style(), &Money::of_minor(GBP, 123456)));
/// assert_eq!("-1,234.56\u{a0}GBP",
///            format(generic_style(), &Money::of_minor(GBP, -123456)));
/// ```
pub fn generic_style() -> &'static FormatSpec {
    &*STYLE_GENERIC
}

/// A format for France, using the Euro symbol in place of "EUR."
///
/// ```
/// # use steel_cent::Money;
/// # use steel_cent::currency::*;
/// # use steel_cent::formatting::*;
/// assert_eq!("1\u{a0}234,56\u{a0}€",
///            format(france_style(), &Money::of_minor(EUR, 123456)));
/// assert_eq!("1\u{a0}234,56\u{a0}GBP",
///            format(france_style(), &Money::of_minor(GBP, 123456)));
/// assert_eq!("-1\u{a0}234,56\u{a0}€",
///            format(france_style(), &Money::of_minor(EUR, -123456)));
/// ```
pub fn france_style() -> &'static FormatSpec {
    &*STYLE_FRANCE
}

/// A format for the United Kingdom, using the pound sign in place of "GBP."
///
/// ```
/// # use steel_cent::Money;
/// # use steel_cent::currency::*;
/// # use steel_cent::formatting::*;
/// assert_eq!("£1,234.56",
///            format(uk_style(), &Money::of_minor(GBP, 123456)));
/// assert_eq!("EUR1,234.56",
///            format(uk_style(), &Money::of_minor(EUR, 123456)));
/// assert_eq!("-£1,234.56",
///            format(uk_style(), &Money::of_minor(GBP, -123456)));
/// ```
pub fn uk_style() -> &'static FormatSpec {
    &*STYLE_UK
}

/// A format for the United States, using the dollar sign in place of "USD" and parentheses for
/// negative amounts.
///
/// ```
/// # use steel_cent::Money;
/// # use steel_cent::currency::*;
/// # use steel_cent::formatting::*;
/// assert_eq!("$1,234.56",
///            format(us_style(), &Money::of_minor(USD, 123456)));
/// assert_eq!("EUR1,234.56",
///            format(us_style(), &Money::of_minor(EUR, 123456)));
/// assert_eq!("($1,234.56)",
///            format(us_style(), &Money::of_minor(USD, -123456)));
/// ```
pub fn us_style() -> &'static FormatSpec {
    &*STYLE_US
}

pub trait FormattableMoney {
    fn unformatted_minor_amount(&self) -> String;
    fn currency(&self) -> Currency;
}

/// A `Display` wrapper for a monetary amount and a `FormatSpec`.
/// Obtained from `FormatSpec::display_for`.
pub struct MoneyDisplay<'a, 'b, T: 'a + FormattableMoney> {
    money: &'a T,
    spec: &'b FormatSpec,
}

impl<'a, 'b, T: FormattableMoney> fmt::Display for MoneyDisplay<'a, 'b, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", format(&self.spec, self.money))
    }
}

/// Given a `FormatSpec` and a monetary value, returns a formatted string.
pub fn format<T: FormattableMoney>(spec: &FormatSpec, money: &T) -> String {
    let currency = money.currency();
    let unformatted_amount = money.unformatted_minor_amount();
    let negative = unformatted_amount.starts_with('-');
    let mut result = String::new();
    for part in &spec.template {
        match *part {
            FormatPart::OptionalMinus => {
                if negative {
                    result.push('-');
                }
            }
            FormatPart::OptionalMinusOpenParenthesis => {
                if negative {
                    result.push('(');
                }
            }
            FormatPart::OptionalMinusCloseParenthesis => {
                if negative {
                    result.push(')');
                }
            }
            FormatPart::NonBreakingSpace => {
                result.push(NBSP);
            }
            FormatPart::Amount => {
                push_formatted_amount(&mut result,
                                      currency,
                                      if negative {
                                          &unformatted_amount[1..]
                                      } else {
                                          unformatted_amount.as_str()
                                      },
                                      spec);
            }
            FormatPart::CurrencySymbol => {
                result.push_str(spec.short_currency_symbols
                    .get(&currency)
                    .unwrap_or(&currency.code())
                    .as_str());
            }
            ref x => {
                panic!("Don't know how to format FormatPart: {:?}", x);
            }
        }
    }
    result
}

fn push_formatted_amount(result: &mut String,
                         currency: Currency,
                         amount: &str,
                         spec: &FormatSpec) {
    let decimal_places = currency.decimal_places() as usize;
    if amount.len() > decimal_places {
        let major_len = amount.len() - decimal_places;
        let mut index = major_len % 3;
        result.push_str(&amount[0..index]);
        while index < major_len {
            if index != 0 {
                result.push(spec.thousands_separator);
            }
            result.push_str(&amount[index..(index + 3)]);
            index += 3;
        }
        result.push(spec.decimal_separator);
        result.push_str(&amount[index..]);
    } else {
        result.push('0');
        result.push(spec.decimal_separator);
        for _ in 0..(decimal_places - amount.len()) {
            result.push('0');
        }
        result.push_str(amount);
    }
}

/// A `Parser` is created from a `FormatSpec` and parses strings conforming to that spec.
#[derive(PartialEq, Eq, Clone)]
pub struct Parser {
    thousands_separator: char,
    decimal_separator: char,
    short_currency_symbols: HashMap<String, Currency>,
    template: Vec<FormatPart>,
}

/// Returned when a string cannot be parsed.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ParseError {
    kind: ParseErrorKind,
    pub loc: usize,
}

impl ParseError {
    fn new(kind: ParseErrorKind, loc: usize) -> Self {
        ParseError { kind: kind, loc: loc }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

impl Error for ParseError {
    fn description(&self) -> &str {
        use self::ParseErrorKind::*;
        match self.kind {
            MisusedThousandsSeparator => "Thousands separator in wrong place",
            UnmatchedNegationParen => "Unmatched negation parenthesis",
            NonWhitespace => "Expected whitespace",
            UnknownCurrencySymbol => "Unknown currency symbol",
            UnparseableNumber => "Unparseable number",
            ExtraCharacters => "String contains extra characters",
            WrongNumberDecimalPlaces => "Wrong number of decimal places for currency",
            EmptyInputString => "Empty input string",
            FormatSpecMissingCurrencySymbol => "FormatSpec template is missing FormatPart::CurrencySymbol. To parse strings with no currency symbol, try adding the empty string to your FormatSpec as a short symbol",
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum ParseErrorKind {
    MisusedThousandsSeparator,
    UnmatchedNegationParen,
    NonWhitespace,
    UnknownCurrencySymbol,
    UnparseableNumber,
    ExtraCharacters,
    WrongNumberDecimalPlaces,
    EmptyInputString,
    FormatSpecMissingCurrencySymbol,
}

impl Parser {
    fn new(thousands_sep: char, decimal_sep: char, template: Vec<FormatPart>) -> Self {
        Parser {
            thousands_separator: thousands_sep,
            decimal_separator: decimal_sep,
            short_currency_symbols: HashMap::new(),
            template: template,
        }
    }

    /// Creates a clone with the given short symbol mapping added.
    pub fn with_short_symbol(&self, currency: Currency, symbol: String) -> Self {
        let mut result = self.clone();
        result.short_currency_symbols.insert(symbol, currency);
        result
    }

    /// Parses a currency string.
    ///
    /// ```
    /// # use steel_cent::Money;
    /// # use steel_cent::currency::*;
    /// # use steel_cent::formatting::*;
    /// use std::error::Error;
    ///
    /// assert_eq!(Ok(Money::of_major(USD, 1)), us_style().parser().parse("$1.00"));
    /// assert_eq!(Ok(Money::of_major(USD, 1)), us_style().parser().parse("USD1.00"));
    /// assert_eq!(Ok(Money::of_major(GBP, 1)), us_style().parser().parse("GBP1.00"));
    ///
    /// let parse_error = us_style().parser().parse::<Money>("£1.00").unwrap_err();
    /// assert_eq!("Unknown currency symbol", parse_error.description());
    /// assert_eq!(0, parse_error.loc);
    /// ```
    pub fn parse<T: ParseableMoney>(&self, s: &str) -> Result<T, ParseError> {
        use self::ParseErrorKind::*;
        let mut negated = false;
        let mut currency: Option<Currency> = None;
        let mut decimal_places = 0_usize;
        let mut minor_amount = String::new();
        let mut buffer_pos = 0_usize;
        let chars: Vec<char> = s.chars().collect();
        if !self.template.contains(&FormatPart::CurrencySymbol) {
            return Err(ParseError::new(FormatSpecMissingCurrencySymbol, 0));
        }
        if chars.is_empty() {
            return Err(ParseError::new(EmptyInputString, 0));
        }
        for item in &self.template {
            if buffer_pos >= chars.len() {
                break;
            }
            let mut c = chars[buffer_pos];
            match item {
                &FormatPart::OptionalMinus => {
                    if c == '-' {
                        negated = true;
                        buffer_pos += 1;
                    }
                },
                &FormatPart::OptionalMinusOpenParenthesis => {
                    if c == '(' {
                        negated = true;
                        buffer_pos += 1;
                    }
                },
                &FormatPart::CurrencySymbol => {
                    let start_pos = buffer_pos;
                    let mut sym = String::new();
                    while !c.is_whitespace() && !c.is_digit(10)
                        && c != '(' && c != ')' && c != '-'
                        && c != self.thousands_separator && c != self.decimal_separator {
                        sym.push(c);
                        buffer_pos += 1;
                        if buffer_pos < chars.len() {
                            c = chars[buffer_pos];
                        } else {
                            break;
                        }
                    }
                    currency = self.short_currency_symbols.get(&sym)
                        .map(|r| r.clone())
                        .or_else(|| currency::with_code(&sym));
                    if currency.is_none() {
                        return Err(ParseError::new(UnknownCurrencySymbol, start_pos));
                    }
                },
                &FormatPart::Amount => {
                    let mut found_decimal = false;
                    let mut decimal_pos = 0_usize;
                    loop {
                        if buffer_pos >= chars.len() {
                            break;
                        }
                        c = chars[buffer_pos];
                        if c.is_digit(10) {
                            minor_amount.push(c);
                            buffer_pos += 1;
                        } else if !found_decimal
                            && (c == self.thousands_separator
                                || (c.is_whitespace() && self.thousands_separator.is_whitespace())) {
                            for i in 1..4 {
                                if (buffer_pos + i) >= chars.len() {
                                    return Err(ParseError::new(MisusedThousandsSeparator, buffer_pos));
                                }
                                c = chars[buffer_pos + i];
                                if !c.is_digit(10) {
                                    return Err(ParseError::new(MisusedThousandsSeparator, buffer_pos));
                                }
                                minor_amount.push(c);
                            }
                            buffer_pos += 4;
                        } else if !found_decimal && c == self.decimal_separator {
                            found_decimal = true;
                            decimal_pos = buffer_pos;
                            buffer_pos += 1;
                        } else {
                            break;
                        }
                    }
                    decimal_places = buffer_pos - decimal_pos - 1;
                },
                &FormatPart::OptionalMinusCloseParenthesis => {
                    if c == ')' {
                        if negated {
                            buffer_pos += 1;
                        } else {
                            return Err(ParseError::new(UnmatchedNegationParen, buffer_pos));
                        }
                    }
                },
                &FormatPart::NonBreakingSpace => {
                    if c.is_whitespace() {
                        buffer_pos += 1;
                    } else {
                        return Err(ParseError::new(NonWhitespace, buffer_pos));
                    }
                },
                ref x => {
                    panic!("Don't know how to parse {:?} yet", x);
                },
            }
        }
        if currency.unwrap().decimal_places() as usize != decimal_places {
            return Err(ParseError::new(WrongNumberDecimalPlaces, 0));
        }
        if buffer_pos < chars.len() {
            return Err(ParseError::new(ExtraCharacters, buffer_pos));
        }
        if negated {
            minor_amount.insert(0, '-');
        }
        ParseableMoney::from_unformatted_minor_amount(currency.unwrap(), minor_amount.as_str())
            .map_err(|_| ParseError::new(UnparseableNumber, 0))
    }
}

pub trait ParseableMoney {
    fn from_unformatted_minor_amount(currency: Currency, unformatted_minor_amount: &str)
                                     -> Result<Self, ::std::num::ParseIntError>
        where Self: ::std::marker::Sized;
}

#[cfg(test)]
mod tests {
    use money::Money;
    use currency;
    use super::*;
    use super::ParseErrorKind;

    #[test]
    fn positive_us_money_in_us_format() {
        assert_eq!("$0.01",
                   format(us_style(), &Money::of_minor(currency::USD, 1)).as_str());
        assert_eq!("$0.10",
                   format(us_style(), &Money::of_minor(currency::USD, 10)).as_str());
        assert_eq!("$1.00",
                   format(us_style(), &Money::of_minor(currency::USD, 100)).as_str());
        assert_eq!("$100.00",
                   format(us_style(), &Money::of_minor(currency::USD, 100_00)).as_str());
        assert_eq!("$12,345,678.90",
                   format(us_style(), &Money::of_minor(currency::USD, 12_345_678_90)).as_str());
    }

    #[test]
    fn negative_us_money_in_us_format() {
        assert_eq!("($0.01)",
                   format(us_style(), &Money::of_minor(currency::USD, -1)).as_str());
        assert_eq!("($1,234.56)",
                   format(us_style(), &Money::of_minor(currency::USD, -123456)).as_str());
    }

    #[test]
    fn uk_money_in_us_format() {
        assert_eq!("GBP1,234.56",
                   format(us_style(), &Money::of_minor(currency::GBP, 123456)).as_str());
        assert_eq!("(GBP1,234.56)",
                   format(us_style(), &Money::of_minor(currency::GBP, -123456)).as_str());
    }

    #[test]
    fn uk_money_in_uk_format() {
        assert_eq!("£1,234.56",
                   format(uk_style(), &Money::of_minor(currency::GBP, 123456)).as_str());
        assert_eq!("-£1,234.56",
                   format(uk_style(), &Money::of_minor(currency::GBP, -123456)).as_str());
    }

    #[test]
    fn us_money_in_uk_format() {
        assert_eq!("USD12,345,678.90",
                   format(uk_style(), &Money::of_minor(currency::USD, 1234567890)).as_str());
        assert_eq!("-USD12,345,678.90",
                   format(uk_style(), &Money::of_minor(currency::USD, -1234567890)).as_str());
    }

    #[test]
    fn fr_money_in_fr_format() {
        assert_eq!("12\u{a0}345\u{a0}678,90\u{a0}€",
                   format(france_style(), &Money::of_minor(currency::EUR, 1234567890)).as_str());
        assert_eq!("-12\u{a0}345\u{a0}678,90\u{a0}€",
                   format(france_style(), &Money::of_minor(currency::EUR, -1234567890)).as_str());
    }

    #[test]
    fn us_money_in_fr_format() {
        assert_eq!("12\u{a0}345\u{a0}678,90\u{a0}USD",
                   format(france_style(), &Money::of_minor(currency::USD, 1234567890)).as_str());
        assert_eq!("-12\u{a0}345\u{a0}678,90\u{a0}USD",
                   format(france_style(), &Money::of_minor(currency::USD, -1234567890)).as_str());
    }

    #[test]
    fn parse_us_style_usd() {
        let parser = us_style().parser();
        assert_eq!(Ok(Money::of_minor(currency::USD, 1)), parser.parse("$0.01"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 10)), parser.parse("$0.10"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 1_00)), parser.parse("$1.00"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 12_345_678_90)), parser.parse("$12,345,678.90"));
        assert_eq!(Ok(Money::of_minor(currency::USD, -1_00)), parser.parse("($1.00)"));
    }

    #[test]
    fn parse_us_style_gbp() {
        let parser = us_style().parser();
        assert_eq!(Ok(Money::of_minor(currency::GBP, 1)), parser.parse("GBP0.01"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, 10)), parser.parse("GBP0.10"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, 1_00)), parser.parse("GBP1.00"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, 12_345_678_90)), parser.parse("GBP12,345,678.90"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, -1_00)), parser.parse("(GBP1.00)"));
    }

    #[test]
    fn parse_uk_style_usd() {
        let parser = uk_style().parser();
        assert_eq!(Ok(Money::of_minor(currency::USD, 1)), parser.parse("USD0.01"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 10)), parser.parse("USD0.10"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 1_00)), parser.parse("USD1.00"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 12_345_678_90)), parser.parse("USD12,345,678.90"));
        assert_eq!(Ok(Money::of_minor(currency::USD, -1_00)), parser.parse("-USD1.00"));
    }

    #[test]
    fn parse_uk_style_gbp() {
        let parser = uk_style().parser();
        assert_eq!(Ok(Money::of_minor(currency::GBP, 1)), parser.parse("£0.01"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, 10)), parser.parse("£0.10"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, 1_00)), parser.parse("£1.00"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, 12_345_678_90)), parser.parse("£12,345,678.90"));
        assert_eq!(Ok(Money::of_minor(currency::GBP, -1_00)), parser.parse("-£1.00"));
    }

    #[test]
    fn parse_france_style_usd() {
        let parser = france_style().parser();
        assert_eq!(Ok(Money::of_minor(currency::USD, 1)), parser.parse("0,01\u{a0}USD"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 10)), parser.parse("0,10\u{a0}USD"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 1_00)), parser.parse("1,00\u{a0}USD"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 12_345_678_90)), parser.parse("12\u{a0}345\u{a0}678,90\u{a0}USD"));
        assert_eq!(Ok(Money::of_minor(currency::USD, -1_00)), parser.parse("-1,00\u{a0}USD"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 1_00)), parser.parse("1,00 USD"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 12_345_678_90)), parser.parse("12 345 678,90 USD"));
    }

    #[test]
    fn parse_france_style_eur() {
        let parser = france_style().parser();
        assert_eq!(Ok(Money::of_minor(currency::EUR, 1)), parser.parse("0,01\u{a0}€"));
        assert_eq!(Ok(Money::of_minor(currency::EUR, 10)), parser.parse("0,10\u{a0}€"));
        assert_eq!(Ok(Money::of_minor(currency::EUR, 1_00)), parser.parse("1,00\u{a0}€"));
        assert_eq!(Ok(Money::of_minor(currency::EUR, 12_345_678_90)), parser.parse("12\u{a0}345\u{a0}678,90\u{a0}€"));
        assert_eq!(Ok(Money::of_minor(currency::EUR, -1_00)), parser.parse("-1,00\u{a0}€"));
        assert_eq!(Ok(Money::of_minor(currency::EUR, 1_00)), parser.parse("1,00 €"));
        assert_eq!(Ok(Money::of_minor(currency::EUR, 12_345_678_90)), parser.parse("12 345 678,90 €"));
    }

    #[test]
    fn parse_with_no_currency_symbol_using_custom_spec() {
        let parser = FormatSpec::new(',', '.', vec![FormatPart::OptionalMinus, FormatPart::CurrencySymbol, FormatPart::Amount])
            .with_short_symbol(currency::USD, "".to_string())
            .parser();
        assert_eq!(Ok(Money::of_minor(currency::USD, 1)), parser.parse("0.01"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 1_234_56)), parser.parse("1,234.56"));
        assert_eq!(Ok(Money::of_minor(currency::USD, -15_08)), parser.parse("-15.08"));
    }

    #[test]
    fn parse_with_spec_having_currency_symbol_before_optional_minus() {
        let parser = FormatSpec::new(',', '.', vec![FormatPart::CurrencySymbol, FormatPart::OptionalMinus, FormatPart::Amount])
            .with_short_symbol(currency::USD, "$".to_string())
            .parser();
        assert_eq!(Ok(Money::of_minor(currency::USD, 1)), parser.parse("$0.01"));
        assert_eq!(Ok(Money::of_minor(currency::USD, 1_234_56)), parser.parse("$1,234.56"));
        assert_eq!(Ok(Money::of_minor(currency::USD, -15_08)), parser.parse("$-15.08"));
    }

    #[test]
    fn parsing_failures() {
        let us_parser = us_style().parser();
        let fr_parser = france_style().parser();
        assert_eq!(Err(ParseError::new(ParseErrorKind::UnknownCurrencySymbol, 0)), us_parser.parse::<Money>("garbage"));
        assert_eq!(Err(ParseError::new(ParseErrorKind::WrongNumberDecimalPlaces, 0)), us_parser.parse::<Money>("$1.234,56")); // TODO should fail differently
        assert_eq!(Err(ParseError::new(ParseErrorKind::ExtraCharacters, 5)), us_parser.parse::<Money>("$1.00 "));
        assert_eq!(Err(ParseError::new(ParseErrorKind::WrongNumberDecimalPlaces, 0)), us_parser.parse::<Money>("$1.0000"));
        assert_eq!(Err(ParseError::new(ParseErrorKind::WrongNumberDecimalPlaces, 0)), us_parser.parse::<Money>("$1.0"));
        assert_eq!(Err(ParseError::new(ParseErrorKind::MisusedThousandsSeparator, 2)), us_parser.parse::<Money>("$1,23.45"));
        assert_eq!(Err(ParseError::new(ParseErrorKind::UnmatchedNegationParen, 5)), us_parser.parse::<Money>("$1.00)"));
        assert_eq!(Err(ParseError::new(ParseErrorKind::NonWhitespace, 4)), fr_parser.parse::<Money>("1,00€"));
        assert_eq!(Err(ParseError::new(ParseErrorKind::EmptyInputString, 0)), us_parser.parse::<Money>(""));
        let bad_parser = FormatSpec::new(',', '.', vec![FormatPart::OptionalMinus, FormatPart::Amount]).parser();
        assert_eq!(Err(ParseError::new(ParseErrorKind::FormatSpecMissingCurrencySymbol, 0)), bad_parser.parse::<Money>("1.00"));
    }

    #[test]
    fn should_be_parsing_failures() { // TODO
        let parser = us_style().parser();
        assert_eq!(Ok(Money::of_minor(currency::USD, -1_00)), parser.parse("($1.00")); // unmatched paren
        assert_eq!(Ok(Money::of_minor(currency::USD, 100_000_00)), parser.parse("$1,00000.00")); // misplaced thousands separator
    }
}