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
#![crate_type = "lib"]
#![crate_name = "currency"]

extern crate regex;

use std::cmp::PartialEq;
use std::cmp::PartialOrd;
use std::cmp::Ordering;

use std::ops::Add;
use std::ops::Sub;
use std::ops::Mul;
use std::ops::Div;

use std::fmt::Display;
use std::fmt::LowerExp;
use std::fmt::Formatter;
use std::fmt::Result;

use std::marker::Copy;

/// Represents currency through an optional symbol and amount of coin.
/// 
/// Each 100 coins results in a banknote. (100 is formatted as 1.00)
/// The currency will be formatted as such:
///     Currency(Some('$'), 432) ==> "$4.32"
#[derive(Debug)]
pub struct Currency(pub Option<char>, pub i64);
 
impl Currency {
    /// Creates a blank Currency as Currency(None, 0)
    /// 
    /// # Examples 
    /// ```
	/// use currency::Currency;
	/// 
    /// let mut c = Currency::new();
    /// ```
    #[inline]
    #[allow(dead_code)]
    pub fn new() -> Currency {
        Currency(None, 0)
    }
 
    /// Uses a Regular Expression to parse a string literal (&str) and turns it into a currency.
    /// 
	/// If the currency is intended to be a negative amount, ensure the '-' is the first character in the string.
    /// The Regex recognizes European notation (€1,00)
    /// 
    /// # Examples
    /// ```
	/// use currency::Currency;
	/// 
    /// assert!(Currency::from_string("$4.32") == Currency(Some('$'), 432));
	/// assert!(Currency::from_string("-$4.32") == Currency(Some('$'), -432));
    /// assert!(Currency::from_string("424.44") == Currency(None, 42444));
	/// assert!(Currency::from_string("£12,00") == Currency(Some('£'), 1200));
	/// assert!(Currency::from_string("¥12") == Currency(Some('¥'), 1200));
    /// ```
    /// 
    /// # Failures
    /// Fails if the string is not formatted correctly.
    /// 
    /// # Panics
    /// Panics if a number fails to be parsed; this only occurs if the string
    /// argument has no numbers in it.
    #[allow(dead_code)]
    pub fn from_string(s: &str) -> Currency {
		use regex::Regex;
	
		// Shadow s with a trimmed version
		let s = s.trim();
		let re = Regex::new(r"(?:\b|(-)?)(\p{Sc})?((?:(?:\d{1,3}[\.,])+\d{3})|\d+)(?:[\.,](\d{2}))?\b").unwrap();
		
		if !re.is_match(s) {
			panic!("Failed to convert \"{}\" to currency", s);
		}
		
		// Used to negate the final result if the regex matches a negative
		let mut multiplier = 1;
		let mut sign: Option<char> = None;
		let mut coin_str: String = "".to_string();
		
		// If anyone's looking at this and knows how to do this without a loop, fork this.
		for cap in re.captures_iter(s) {
			// Without this, there is undefined behavior (try putting a character in the middle of s)
			if cap.at(0).unwrap_or("") != s {
				panic!("Failed to convert \"{}\" to currency", s);
			}
			
			if cap.at(1).is_some() {
				multiplier = -1;
			}
			
			if cap.at(2).is_some() {
				if multiplier < 0 {
					sign = Some(s.chars().skip(1).next().unwrap());
				} else {
					sign = Some(s.chars().next().unwrap());
				}
			}
			coin_str = cap.at(3).unwrap().replace(".", "").replace(",", "") + cap.at(4).unwrap_or("00");
			
			break;
		}
		
		let coin: i64 = multiplier * coin_str.parse::<i64>().ok().unwrap();
		
		Currency(sign, coin)
	}
}

/// Allows Currencies to be displayed as Strings
/// The format includes no comma delimiting with a two digit precision decimal
/// 
/// # Examples
/// ```
/// use currency::Currency;
/// 
/// assert!(Currency(Some('$'), 1210).to_string() == "$12.10");
/// assert!(Currency(None, 1210).to_string() == "12.10");
/// 
/// println!("{}", Currency(Some('$'), 100099));
/// ```
/// The last line prints the following:
/// ```text
/// "$1000.99"
/// ```
impl Display for Currency {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
		let decimal = format!("{:.2}", (self.1 as f32 / 100.0));
        match self.0 {
            Some(c) => write!(f, "{}{}", c, decimal),
            None    => write!(f, "{}", decimal),
        }
    }
}

/// Identical to the implementation of Display, but replaces the "." with a ","
/// Access this formating by using "{:e}"
/// 
/// # Examples
/// ```
/// use currency::Currency;
/// 
/// println!("{:e}", Currency(Some('£'), 100099));
/// ```
/// The last line prints the following:
/// ```text
/// "£1000,99"
/// ```
impl LowerExp for Currency {
	#[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
		write!(f, "{}", format!("{}", self).replace(".", ","))
    }
}

/// Overloads the '==' operator for Currency objects.
/// 
/// # Panics
/// Panics if the two comparators are different types of currency, as denoted by
/// the Currency's symbol.
impl PartialEq<Currency> for Currency {
    #[inline]
    fn eq(&self, rhs: &Currency) -> bool {
        self.0 == rhs.0 && self.1 == rhs.1
    }
 
    #[inline]
    fn ne(&self, rhs: &Currency) -> bool {
        self.0 != rhs.0 || self.1 != rhs.1
    }
}
 
/// Overloads the order operators for Currency objects.
/// 
/// These operators include '<', '<=', '>', and '>='.
/// 
/// # Panics
/// Panics if the two comparators are different types of currency, as denoted by
/// the Currency's symbol.
impl PartialOrd<Currency> for Currency {
    #[inline]
    fn partial_cmp(&self, rhs: &Currency) -> Option<Ordering> {
        if self.0 == rhs.0 {
            if self < rhs { return Some(Ordering::Less) }
            if self == rhs { return Some(Ordering::Equal) }
            if self > rhs { return Some(Ordering::Greater) }
        }
        None
    }
    
    #[inline]
    fn lt(&self, rhs: &Currency) -> bool {
        if self.0 == rhs.0 { 
            self.1 < rhs.1 
        }
        else { 
            panic!("Cannot compare two different types of currency."); 
        }
    }
    #[inline]
    fn le(&self, rhs: &Currency) -> bool {
        self < rhs || self == rhs
    }
    #[inline]
    fn gt(&self, rhs: &Currency) -> bool {
        if self.0 == rhs.0 { 
            self.1 > rhs.1 
        }
        else { 
            panic!("Cannot compare two different types of currency."); 
        }
    }
    #[inline]
    fn ge(&self, rhs: &Currency) -> bool {
        self > rhs || self == rhs
    }
}
 
/// Overloads the '+' operator for Currency objects.
/// 
/// # Panics
/// Panics if the two addends are different types of currency, as denoted by the
/// Currency's symbol.
impl Add for Currency {
    type Output = Currency;
 
    #[inline]
    fn add(self, rhs: Currency) -> Currency {
        if self.0 == rhs.0 {
            Currency(self.0, self.1 + rhs.1)
        } else {
            panic!("Cannot add two different types of currency!");
        }
    }
}
 
/// Overloads the '-' operator for Currency objects.
/// 
/// # Panics
/// Panics if the minuend and subtrahend are two different types of currency, 
/// as denoted by the Currency's symbol.
impl Sub for Currency {
    type Output = Currency;
    
    #[inline]
    fn sub(self, rhs: Currency) -> Currency {
        if self.0 == rhs.0 {
            Currency(self.0, self.1 - rhs.1)
        } else {
            panic!("Cannot subtract two different types of currency!");
        }
    }
}
 
/// Overloads the '*' operator for Currency objects.
///
/// Allows a Currency to be multiplied by an i64.
impl Mul<i64> for Currency {
    type Output = Currency;
    
    #[inline]
    fn mul(self, rhs: i64) -> Currency {
        Currency(self.0, self.1 * rhs)
    }
}
 
/// Overloads the '*' operator for i64.
/// 
/// Allows an i64 to be multiplied by a Currency.
/// Completes the commutative property for i64 multiplied by Currency.
impl Mul<Currency> for i64 {
    type Output = Currency;
    
    #[inline]
    fn mul(self, rhs: Currency) -> Currency {
        Currency(rhs.0, rhs.1 * self)
    }
}
 
/// Overloads the '/' operator for Currency objects.
/// 
/// Allows a Currency to be divided by an i64.
impl Div<i64> for Currency {
    type Output = Currency;
    
    #[inline]
    fn div(self, rhs: i64) -> Currency {
        Currency(self.0, self.1 / rhs)
    }
}
 
/// Allows Currencies to be copied, rather than using move semantics.
impl Copy for Currency { }
impl Clone for Currency {
    #[inline]
    fn clone(&self) -> Currency { *self }
}