parse.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{iter::FromIterator, str::FromStr};
  19. use crate::{Error, Result};
  20. fn is_digit(c: char) -> bool {
  21. ('0'..='9').contains(&c)
  22. }
  23. fn char_eq(a: char, b: char) -> bool {
  24. a == b
  25. }
  26. pub fn decode_base10(amount: &str, decimal_places: usize, strict: bool) -> Result<u64> {
  27. let mut s: Vec<char> = amount.to_string().chars().collect();
  28. // Get rid of the decimal point:
  29. let point: usize = if let Some(p) = amount.find('.') {
  30. s.remove(p);
  31. p
  32. } else {
  33. s.len()
  34. };
  35. // Only digits should remain
  36. for i in &s {
  37. if !is_digit(*i) {
  38. return Err(Error::ParseFailed("Found non-digits"))
  39. }
  40. }
  41. // Add digits to the end if there are too few:
  42. let actual_places = s.len() - point;
  43. if actual_places < decimal_places {
  44. s.extend(vec!['0'; decimal_places - actual_places])
  45. }
  46. // Remove digits from the end if there are too many:
  47. let mut round = false;
  48. if actual_places > decimal_places {
  49. let end = point + decimal_places;
  50. for i in &s[end..s.len()] {
  51. if !char_eq(*i, '0') {
  52. round = true;
  53. break
  54. }
  55. }
  56. s.truncate(end);
  57. }
  58. if strict && round {
  59. return Err(Error::ParseFailed("Would end up rounding while strict"))
  60. }
  61. // Convert to an integer
  62. let number = u64::from_str(&String::from_iter(&s))?;
  63. // Round and return
  64. if round && number == u64::MAX {
  65. return Err(Error::ParseFailed("u64 overflow"))
  66. }
  67. Ok(number + round as u64)
  68. }
  69. pub fn encode_base10(amount: u64, decimal_places: usize) -> String {
  70. let mut s: Vec<char> =
  71. format!("{:0width$}", amount, width = 1 + decimal_places).chars().collect();
  72. s.insert(s.len() - decimal_places, '.');
  73. String::from_iter(&s).trim_end_matches('0').trim_end_matches('.').to_string()
  74. }
  75. pub fn truncate(amount: u64, decimals: u16, token_decimals: u16) -> Result<u64> {
  76. let mut amount: Vec<char> = amount.to_string().chars().collect();
  77. if token_decimals > decimals {
  78. if amount.len() <= (token_decimals - decimals) as usize {
  79. return Ok(0)
  80. }
  81. amount.truncate(amount.len() - (token_decimals - decimals) as usize);
  82. }
  83. if token_decimals < decimals {
  84. amount.resize(amount.len() + (decimals - token_decimals) as usize, '0');
  85. }
  86. let amount = u64::from_str(&String::from_iter(amount))?;
  87. Ok(amount)
  88. }
  89. #[cfg(test)]
  90. mod tests {
  91. use super::{decode_base10, encode_base10, truncate};
  92. #[test]
  93. fn test_decode_base10() {
  94. assert_eq!(124, decode_base10("12.33", 1, false).unwrap());
  95. assert_eq!(1233000, decode_base10("12.33", 5, false).unwrap());
  96. assert_eq!(1200000, decode_base10("12.", 5, false).unwrap());
  97. assert_eq!(1200000, decode_base10("12", 5, false).unwrap());
  98. assert!(decode_base10("12.33", 1, true).is_err());
  99. }
  100. #[test]
  101. fn test_encode_base10() {
  102. assert_eq!("23.4321111", &encode_base10(234321111, 7));
  103. assert_eq!("23432111.1", &encode_base10(234321111, 1));
  104. assert_eq!("234321.1", &encode_base10(2343211, 1));
  105. assert_eq!("2343211", &encode_base10(2343211, 0));
  106. assert_eq!("0.00002343", &encode_base10(2343, 8));
  107. }
  108. #[test]
  109. fn test_truncate() {
  110. // Token decimals is equal to 8
  111. assert_eq!(100, truncate(100, 8, 8).unwrap());
  112. assert_eq!(12, truncate(12, 8, 8).unwrap());
  113. // Token decimals is bigger than 8
  114. assert_eq!(100000000, truncate(1000000000, 8, 9).unwrap());
  115. assert_eq!(10, truncate(100, 8, 9).unwrap());
  116. assert_eq!(1, truncate(12, 8, 9).unwrap());
  117. assert_eq!(10, truncate(102, 8, 9).unwrap());
  118. assert_eq!(0, truncate(1, 8, 9).unwrap());
  119. assert_eq!(1, truncate(100000000, 8, 16).unwrap());
  120. assert_eq!(10, truncate(100000000, 8, 15).unwrap());
  121. assert_eq!(0, truncate(100000000, 8, 17).unwrap());
  122. assert_eq!(0, truncate(10, 8, 16).unwrap());
  123. // Token decimals is less than 8
  124. assert_eq!(1000, truncate(100, 8, 7).unwrap());
  125. assert_eq!(12000, truncate(120, 8, 6).unwrap());
  126. assert_eq!(1000000, truncate(100, 8, 4).unwrap());
  127. // token decimals is 0
  128. assert_eq!(00000000, truncate(0, 8, 0).unwrap());
  129. assert_eq!(100000000, truncate(1, 8, 0).unwrap());
  130. //
  131. // reverse truncate
  132. //
  133. // Token decimals is less than decimals
  134. assert_eq!(1000000000, truncate(100000000, 9, 8).unwrap());
  135. assert_eq!(100000000, truncate(10000000, 9, 8).unwrap());
  136. assert_eq!(100, truncate(10, 9, 8).unwrap());
  137. assert_eq!(10, truncate(1, 9, 8).unwrap());
  138. assert_eq!(100, truncate(10, 9, 8).unwrap());
  139. assert_eq!(0, truncate(0, 9, 8).unwrap());
  140. assert_eq!(100000000, truncate(1, 16, 8).unwrap());
  141. assert_eq!(100000000, truncate(10, 15, 8).unwrap());
  142. assert_eq!(0, truncate(0, 17, 8).unwrap());
  143. // Token decimals is bigger than decimals
  144. assert_eq!(100, truncate(1000, 7, 8).unwrap());
  145. assert_eq!(120, truncate(12000, 6, 8).unwrap());
  146. assert_eq!(100, truncate(1000000, 4, 8).unwrap());
  147. // token decimals is 0
  148. assert_eq!(0, truncate(00000000, 0, 8).unwrap());
  149. assert_eq!(1, truncate(100000000, 0, 8).unwrap());
  150. }
  151. }