Skip to main content

rustpython_common/
windows.rs

1use rustpython_wtf8::Wtf8;
2use std::{
3    ffi::{OsStr, OsString},
4    os::windows::ffi::{OsStrExt, OsStringExt},
5};
6
7/// _MAX_ENV from Windows CRT stdlib.h - maximum environment variable size
8pub const _MAX_ENV: usize = 32767;
9
10pub trait ToWideString {
11    fn to_wide(&self) -> Vec<u16>;
12    fn to_wide_with_nul(&self) -> Vec<u16>;
13}
14
15impl<T> ToWideString for T
16where
17    T: AsRef<OsStr>,
18{
19    fn to_wide(&self) -> Vec<u16> {
20        self.as_ref().encode_wide().collect()
21    }
22    fn to_wide_with_nul(&self) -> Vec<u16> {
23        self.as_ref().encode_wide().chain(Some(0)).collect()
24    }
25}
26
27impl ToWideString for OsStr {
28    fn to_wide(&self) -> Vec<u16> {
29        self.encode_wide().collect()
30    }
31    fn to_wide_with_nul(&self) -> Vec<u16> {
32        self.encode_wide().chain(Some(0)).collect()
33    }
34}
35
36impl ToWideString for Wtf8 {
37    fn to_wide(&self) -> Vec<u16> {
38        self.encode_wide().collect()
39    }
40    fn to_wide_with_nul(&self) -> Vec<u16> {
41        self.encode_wide().chain(Some(0)).collect()
42    }
43}
44
45pub trait FromWideString
46where
47    Self: Sized,
48{
49    fn from_wides_until_nul(wide: &[u16]) -> Self;
50}
51impl FromWideString for OsString {
52    fn from_wides_until_nul(wide: &[u16]) -> OsString {
53        let len = wide.iter().take_while(|&&c| c != 0).count();
54        OsString::from_wide(&wide[..len])
55    }
56}