numparse.rs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // -*- coding: utf-8 -*-
  2. //
  3. // Simple CMS
  4. //
  5. // Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
  6. //
  7. // Licensed under the Apache License version 2.0
  8. // or the MIT license, at your option.
  9. // SPDX-License-Identifier: Apache-2.0 OR MIT
  10. use anyhow::{self as ah, format_err as err};
  11. pub fn parse_usize(s: &str) -> ah::Result<usize> {
  12. let s = s.trim();
  13. if let Some(s) = s.strip_prefix("0x") {
  14. Ok(usize::from_str_radix(s, 16)?)
  15. } else {
  16. Ok(s.parse::<usize>()?)
  17. }
  18. }
  19. pub fn parse_i64(s: &str) -> ah::Result<i64> {
  20. let s = s.trim();
  21. if let Some(s) = s.strip_prefix("0x") {
  22. Ok(i64::from_str_radix(s, 16)?)
  23. } else {
  24. Ok(s.parse::<i64>()?)
  25. }
  26. }
  27. pub fn parse_f64(s: &str) -> ah::Result<f64> {
  28. Ok(s.trim().parse::<f64>()?)
  29. }
  30. pub fn parse_bool(s: &str) -> ah::Result<bool> {
  31. let s = s.to_lowercase();
  32. let s = s.trim();
  33. match s {
  34. "true" | "1" | "yes" | "on" => Ok(true),
  35. "false" | "0" | "no" | "off" => Ok(false),
  36. _ => Err(err!("Invalid boolean string")),
  37. }
  38. }
  39. // vim: ts=4 sw=4 expandtab