Skip to content

Commit 2df64f0

Browse files
committed
os: implement device_encoding
1 parent 30fe670 commit 2df64f0

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

Lib/test/test_os.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2941,8 +2941,6 @@ def test_identity(self):
29412941

29422942
class DeviceEncodingTests(unittest.TestCase):
29432943

2944-
# TODO: RUSTPYTHON (AttributeError: module 'os' has no attribute 'device_encoding')
2945-
@unittest.expectedFailure
29462944
def test_bad_fd(self):
29472945
# Return None when an fd doesn't actually exist.
29482946
self.assertIsNone(os.device_encoding(123456))

vm/src/stdlib/os.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1697,6 +1697,40 @@ pub(super) mod _os {
16971697
}
16981698
}
16991699

1700+
// TODO: libc currently doesn't support nl_langinfo in wasi
1701+
#[cfg(not(target_os = "wasi"))]
1702+
#[pyfunction]
1703+
fn device_encoding(fd: i32, _vm: &VirtualMachine) -> PyResult<Option<String>> {
1704+
if !isatty(fd) {
1705+
return Ok(None);
1706+
}
1707+
1708+
cfg_if::cfg_if! {
1709+
if #[cfg(target_os = "android")] {
1710+
Ok(Some("UTF-8".to_owned()))
1711+
} else if #[cfg(windows)] {
1712+
let cp = match fd {
1713+
0 => unsafe { winapi::um::consoleapi::GetConsoleCP() },
1714+
1 | 2 => unsafe { winapi::um::consoleapi::GetConsoleOutputCP() },
1715+
_ => 0,
1716+
};
1717+
1718+
Ok(Some(format!("cp{}", cp)))
1719+
} else {
1720+
let encoding = unsafe {
1721+
let encoding = libc::nl_langinfo(libc::CODESET);
1722+
if encoding.is_null() || encoding.read() == '\0' as libc::c_char {
1723+
"UTF-8".to_owned()
1724+
} else {
1725+
ffi::CStr::from_ptr(encoding).to_string_lossy().into_owned()
1726+
}
1727+
};
1728+
1729+
Ok(Some(encoding))
1730+
}
1731+
}
1732+
}
1733+
17001734
#[pyattr]
17011735
#[pyclass(module = "os", name = "terminal_size")]
17021736
#[derive(PyStructSequence)]

0 commit comments

Comments
 (0)