parse.rs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. #[cfg(test)]
  70. mod tests {
  71. use super::{decode_base10, encode_base10};
  72. #[test]
  73. fn test_decode_base10() {
  74. assert_eq!(124, decode_base10("12.33", 1, false).unwrap());
  75. assert_eq!(1233000, decode_base10("12.33", 5, false).unwrap());
  76. assert_eq!(1200000, decode_base10("12.", 5, false).unwrap());
  77. assert_eq!(1200000, decode_base10("12", 5, false).unwrap());
  78. assert!(decode_base10("12.33", 1, true).is_err());
  79. }
  80. #[test]
  81. fn test_encode_base10() {
  82. assert_eq!("23.4321111", &encode_base10(234321111, 7));
  83. assert_eq!("23432111.1", &encode_base10(234321111, 1));
  84. assert_eq!("234321.1", &encode_base10(2343211, 1));
  85. assert_eq!("2343211", &encode_base10(2343211, 0));
  86. assert_eq!("0.00002343", &encode_base10(2343, 8));
  87. }
  88. }