Skip to content

Commit 3b53a5b

Browse files
committed
refactor: extract helper function for safer numeric locale detection
Refactored the detect_numeric_locale function to initialize settings early and extract common logic into single_byte_from_locale_ptr helper, improving code safety and readability without changing behavior.
1 parent be1ea65 commit 3b53a5b

File tree

1 file changed

+26
-23
lines changed

1 file changed

+26
-23
lines changed

src/uu/sort/src/sort.rs

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1287,39 +1287,42 @@ impl FieldSelector {
12871287

12881288
#[cfg(unix)]
12891289
fn detect_numeric_locale() -> NumericLocaleSettings {
1290+
let mut settings = NumericLocaleSettings::default();
12901291
unsafe {
12911292
libc::setlocale(libc::LC_NUMERIC, c"".as_ptr());
1292-
let mut settings = NumericLocaleSettings::default();
1293-
let conv = libc::localeconv();
1294-
if conv.is_null() {
1295-
return settings;
1296-
}
1297-
1298-
let decimal_ptr = (*conv).decimal_point;
1299-
if !decimal_ptr.is_null() {
1300-
let decimal_point = CStr::from_ptr(decimal_ptr).to_bytes();
1301-
if decimal_point.len() == 1 {
1302-
settings.decimal_pt = Some(decimal_point[0]);
1303-
}
1304-
}
1305-
1306-
let thousands_ptr = (*conv).thousands_sep;
1307-
if !thousands_ptr.is_null() {
1308-
let thousands_sep = CStr::from_ptr(thousands_ptr).to_bytes();
1309-
if thousands_sep.len() == 1 {
1310-
settings.thousands_sep = Some(thousands_sep[0]);
1311-
}
1312-
}
1313-
1314-
settings
13151293
}
1294+
let conv = unsafe { libc::localeconv() };
1295+
if conv.is_null() {
1296+
return settings;
1297+
}
1298+
let (decimal_ptr, thousands_ptr) = unsafe {
1299+
let conv = &*conv;
1300+
(conv.decimal_point, conv.thousands_sep)
1301+
};
1302+
1303+
settings.decimal_pt = single_byte_from_locale_ptr(decimal_ptr);
1304+
settings.thousands_sep = single_byte_from_locale_ptr(thousands_ptr);
1305+
settings
13161306
}
13171307

13181308
#[cfg(not(unix))]
13191309
fn detect_numeric_locale() -> NumericLocaleSettings {
13201310
NumericLocaleSettings::default()
13211311
}
13221312

1313+
#[cfg(unix)]
1314+
fn single_byte_from_locale_ptr(ptr: *const libc::c_char) -> Option<u8> {
1315+
if ptr.is_null() {
1316+
return None;
1317+
}
1318+
let bytes = unsafe { CStr::from_ptr(ptr).to_bytes() };
1319+
if bytes.len() == 1 {
1320+
Some(bytes[0])
1321+
} else {
1322+
None
1323+
}
1324+
}
1325+
13231326
/// Creates an `Arg` for a sort mode flag.
13241327
fn make_sort_mode_arg(mode: &'static str, short: char, help: String) -> Arg {
13251328
Arg::new(mode)

0 commit comments

Comments
 (0)