use std::fmt;
use crate::error::{Error, Result};
const MAX_LENGTH: usize = 12;
const RANGE: std::ops::RangeInclusive<i64> = -(1i64 << 31)..=(1i64 << 31) - 1;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IntegerString {
text: String,
value: i32,
}
impl IntegerString {
pub fn parse(text: &str) -> Result<Self> {
let text = text.trim();
if text.len() > MAX_LENGTH {
return Err(Error::InvalidValue(format!(
"an integer string has at most {MAX_LENGTH} characters: {text}"
)));
}
if !looks_like_integer(text) {
return Err(Error::InvalidValue(format!(
"not an integer string: {text}"
)));
}
let value: i64 = text
.parse()
.map_err(|_| Error::InvalidValue(format!("not an integer string: {text}")))?;
if !RANGE.contains(&value) {
return Err(Error::InvalidValue(format!(
"an integer string must be between {} and {}: {text}",
RANGE.start(),
RANGE.end()
)));
}
Ok(Self {
text: text.to_owned(),
value: value as i32,
})
}
pub fn from_i32(value: i32) -> Self {
Self {
text: value.to_string(),
value,
}
}
pub fn text(&self) -> &str {
&self.text
}
pub fn value(&self) -> i32 {
self.value
}
}
impl fmt::Display for IntegerString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
impl From<IntegerString> for String {
fn from(value: IntegerString) -> Self {
value.text
}
}
fn looks_like_integer(text: &str) -> bool {
let bytes = text.as_bytes();
let mut index = 0usize;
if matches!(bytes.first(), Some(b'+' | b'-')) {
index += 1;
}
if index == bytes.len() {
return false;
}
bytes[index..].iter().all(u8::is_ascii_digit)
}