From 5f2374b33960f42fd1cb575ee4801ef50f342cf8 Mon Sep 17 00:00:00 2001 From: Terts Diepraam Date: Fri, 17 Nov 2023 14:57:09 +0100 Subject: [PATCH] printf: fix negative hex argument parsing --- src/uucore/src/lib/features/format/argument.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/uucore/src/lib/features/format/argument.rs b/src/uucore/src/lib/features/format/argument.rs index 644546c38..120b59aa4 100644 --- a/src/uucore/src/lib/features/format/argument.rs +++ b/src/uucore/src/lib/features/format/argument.rs @@ -49,9 +49,13 @@ impl FormatArgument { match self { Self::SignedInt(n) => Some(*n), 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") { + // For hex, we parse `u64` because we do not allow another + // minus sign. We might need to do more precise parsing here. + if let Some(s) = s.strip_prefix("-0x") { + Some(- (u64::from_str_radix(s, 16).ok()? as i64)) + } else if let Some(s) = s.strip_prefix("0x") { + Some(u64::from_str_radix(s, 16).ok()? as i64) + } else if s.starts_with("-0") || s.starts_with('0') { i64::from_str_radix(s, 8).ok() } else if let Some(s) = s.strip_prefix('\'') { Some(s.chars().next()? as i64)