parse.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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. pub fn decode_base10(amount: &str, decimal_places: usize, strict: bool) -> Result<u64> {
  21. let mut s: Vec<char> = amount.to_string().chars().collect();
  22. // Get rid of the decimal point:
  23. let point: usize = if let Some(p) = amount.find('.') {
  24. s.remove(p);
  25. p
  26. } else {
  27. s.len()
  28. };
  29. // Only digits should remain
  30. for i in &s {
  31. if !i.is_ascii_digit() {
  32. return Err(Error::ParseFailed("Found non-digits"))
  33. }
  34. }
  35. // Add digits to the end if there are too few:
  36. let actual_places = s.len() - point;
  37. if actual_places < decimal_places {
  38. s.extend(vec!['0'; decimal_places - actual_places])
  39. }
  40. // Remove digits from the end if there are too many:
  41. let mut round = false;
  42. if actual_places > decimal_places {
  43. let end = point + decimal_places;
  44. for i in &s[end..s.len()] {
  45. if *i != '0' {
  46. round = true;
  47. break
  48. }
  49. }
  50. s.truncate(end);
  51. }
  52. if strict && round {
  53. return Err(Error::ParseFailed("Would end up rounding while strict"))
  54. }
  55. // Convert to an integer
  56. let number = u64::from_str(&String::from_iter(&s))?;
  57. // Round and return
  58. if round && number == u64::MAX {
  59. return Err(Error::ParseFailed("u64 overflow"))
  60. }
  61. Ok(number + round as u64)
  62. }
  63. pub fn encode_base10(amount: u64, decimal_places: usize) -> String {
  64. let mut s: Vec<char> =
  65. format!("{:0width$}", amount, width = 1 + decimal_places).chars().collect();
  66. s.insert(s.len() - decimal_places, '.');
  67. String::from_iter(&s).trim_end_matches('0').trim_end_matches('.').to_string()
  68. }
  69. pub fn truncate(amount: u64, decimals: u16, token_decimals: u16) -> Result<u64> {
  70. let mut amount: Vec<char> = amount.to_string().chars().collect();
  71. if token_decimals > decimals {
  72. if amount.len() <= (token_decimals - decimals) as usize {
  73. return Ok(0)
  74. }
  75. amount.truncate(amount.len() - (token_decimals - decimals) as usize);
  76. }
  77. if token_decimals < decimals {
  78. amount.resize(amount.len() + (decimals - token_decimals) as usize, '0');
  79. }
  80. let amount = u64::from_str(&String::from_iter(amount))?;
  81. Ok(amount)
  82. }
  83. #[cfg(test)]
  84. mod tests {
  85. use super::{decode_base10, encode_base10, truncate};
  86. #[test]
  87. fn test_decode_base10() {
  88. assert_eq!(124, decode_base10("12.33", 1, false).unwrap());
  89. assert_eq!(1233000, decode_base10("12.33", 5, false).unwrap());
  90. assert_eq!(1200000, decode_base10("12.", 5, false).unwrap());
  91. assert_eq!(1200000, decode_base10("12", 5, false).unwrap());
  92. assert!(decode_base10("12.33", 1, true).is_err());
  93. }
  94. #[test]
  95. fn test_encode_base10() {
  96. assert_eq!("23.4321111", &encode_base10(234321111, 7));
  97. assert_eq!("23432111.1", &encode_base10(234321111, 1));
  98. assert_eq!("234321.1", &encode_base10(2343211, 1));
  99. assert_eq!("2343211", &encode_base10(2343211, 0));
  100. assert_eq!("0.00002343", &encode_base10(2343, 8));
  101. }
  102. #[test]
  103. fn test_truncate() {
  104. // Token decimals is equal to 8
  105. assert_eq!(100, truncate(100, 8, 8).unwrap());
  106. assert_eq!(12, truncate(12, 8, 8).unwrap());
  107. // Token decimals is bigger than 8
  108. assert_eq!(100000000, truncate(1000000000, 8, 9).unwrap());
  109. assert_eq!(10, truncate(100, 8, 9).unwrap());
  110. assert_eq!(1, truncate(12, 8, 9).unwrap());
  111. assert_eq!(10, truncate(102, 8, 9).unwrap());
  112. assert_eq!(0, truncate(1, 8, 9).unwrap());
  113. assert_eq!(1, truncate(100000000, 8, 16).unwrap());
  114. assert_eq!(10, truncate(100000000, 8, 15).unwrap());
  115. assert_eq!(0, truncate(100000000, 8, 17).unwrap());
  116. assert_eq!(0, truncate(10, 8, 16).unwrap());
  117. // Token decimals is less than 8
  118. assert_eq!(1000, truncate(100, 8, 7).unwrap());
  119. assert_eq!(12000, truncate(120, 8, 6).unwrap());
  120. assert_eq!(1000000, truncate(100, 8, 4).unwrap());
  121. // token decimals is 0
  122. assert_eq!(00000000, truncate(0, 8, 0).unwrap());
  123. assert_eq!(100000000, truncate(1, 8, 0).unwrap());
  124. //
  125. // reverse truncate
  126. //
  127. // Token decimals is less than decimals
  128. assert_eq!(1000000000, truncate(100000000, 9, 8).unwrap());
  129. assert_eq!(100000000, truncate(10000000, 9, 8).unwrap());
  130. assert_eq!(100, truncate(10, 9, 8).unwrap());
  131. assert_eq!(10, truncate(1, 9, 8).unwrap());
  132. assert_eq!(100, truncate(10, 9, 8).unwrap());
  133. assert_eq!(0, truncate(0, 9, 8).unwrap());
  134. assert_eq!(100000000, truncate(1, 16, 8).unwrap());
  135. assert_eq!(100000000, truncate(10, 15, 8).unwrap());
  136. assert_eq!(0, truncate(0, 17, 8).unwrap());
  137. // Token decimals is bigger than decimals
  138. assert_eq!(100, truncate(1000, 7, 8).unwrap());
  139. assert_eq!(120, truncate(12000, 6, 8).unwrap());
  140. assert_eq!(100, truncate(1000000, 4, 8).unwrap());
  141. // token decimals is 0
  142. assert_eq!(0, truncate(00000000, 0, 8).unwrap());
  143. assert_eq!(1, truncate(100000000, 0, 8).unwrap());
  144. }
  145. }