From a45ff8ca73060939983379f5d973ac3da4c75330 Mon Sep 17 00:00:00 2001 From: Terts Diepraam Date: Fri, 17 Nov 2023 14:39:39 +0100 Subject: [PATCH] printf: more flexible parsing of unparsed arguments --- .../src/lib/features/format/argument.rs | 40 ++++++++++++++++--- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/src/uucore/src/lib/features/format/argument.rs b/src/uucore/src/lib/features/format/argument.rs index 007f519c2..644546c38 100644 --- a/src/uucore/src/lib/features/format/argument.rs +++ b/src/uucore/src/lib/features/format/argument.rs @@ -30,23 +30,51 @@ impl FormatArgument { pub fn get_u64(&self) -> Option { match self { Self::UnsignedInt(n) => Some(*n), - Self::Unparsed(s) => s.parse().ok(), + Self::Unparsed(s) => { + if let Some(s) = s.strip_prefix("0x") { + u64::from_str_radix(s, 16).ok() + } else if let Some(s) = s.strip_prefix("0") { + u64::from_str_radix(s, 8).ok() + } else if let Some(s) = s.strip_prefix('\'') { + Some(s.chars().next()? as u64) + } else { + s.parse().ok() + } + } _ => None, } } - + pub fn get_i64(&self) -> Option { match self { Self::SignedInt(n) => Some(*n), - Self::Unparsed(s) => s.parse().ok(), + Self::Unparsed(s) => { + if let Some(s) = s.strip_prefix("0x") { + i64::from_str_radix(s, 16).ok() + } else if let Some(s) = s.strip_prefix("0") { + i64::from_str_radix(s, 8).ok() + } else if let Some(s) = s.strip_prefix('\'') { + Some(s.chars().next()? as i64) + } else { + s.parse().ok() + } + } _ => None, } } - + pub fn get_f64(&self) -> Option { match self { Self::Float(n) => Some(*n), - Self::Unparsed(s) => s.parse().ok(), + Self::Unparsed(s) => { + if s.starts_with("0x") || s.starts_with("-0x") { + unimplemented!("Hexadecimal floats are unimplemented!") + } else if let Some(s) = s.strip_prefix('\'') { + Some(s.chars().next()? as u64 as f64) + } else { + s.parse().ok() + } + } _ => None, } } @@ -57,4 +85,4 @@ impl FormatArgument { _ => None, } } -} \ No newline at end of file +}