1
1
use super :: unsupported;
2
+ use crate :: convert:: TryFrom ;
2
3
use crate :: error:: Error as StdError ;
3
4
use crate :: ffi:: { CStr , CString , OsStr , OsString } ;
4
5
use crate :: fmt;
@@ -9,6 +10,7 @@ use crate::os::{
9
10
} ;
10
11
use crate :: path:: { self , PathBuf } ;
11
12
use crate :: sync:: RwLock ;
13
+ use crate :: sys:: common:: small_c_string:: run_with_cstr;
12
14
use crate :: vec;
13
15
14
16
use super :: { error, itron, memchr} ;
@@ -139,35 +141,33 @@ pub fn env() -> Env {
139
141
pub fn getenv ( k : & OsStr ) -> Option < OsString > {
140
142
// environment variables with a nul byte can't be set, so their value is
141
143
// always None as well
142
- let k = CString :: new ( k. as_bytes ( ) ) . ok ( ) ?;
143
- unsafe {
144
+ let s = run_with_cstr ( k. as_bytes ( ) , |k| {
144
145
let _guard = ENV_LOCK . read ( ) ;
145
- let s = libc:: getenv ( k. as_ptr ( ) ) as * const libc:: c_char ;
146
- if s. is_null ( ) {
147
- None
148
- } else {
149
- Some ( OsStringExt :: from_vec ( CStr :: from_ptr ( s) . to_bytes ( ) . to_vec ( ) ) )
150
- }
146
+ Ok ( unsafe { libc:: getenv ( k. as_ptr ( ) ) } as * const libc:: c_char )
147
+ } )
148
+ . ok ( ) ?;
149
+
150
+ if s. is_null ( ) {
151
+ None
152
+ } else {
153
+ Some ( OsStringExt :: from_vec ( unsafe { CStr :: from_ptr ( s) } . to_bytes ( ) . to_vec ( ) ) )
151
154
}
152
155
}
153
156
154
157
pub fn setenv ( k : & OsStr , v : & OsStr ) -> io:: Result < ( ) > {
155
- let k = CString :: new ( k. as_bytes ( ) ) ?;
156
- let v = CString :: new ( v. as_bytes ( ) ) ?;
157
-
158
- unsafe {
159
- let _guard = ENV_LOCK . write ( ) ;
160
- cvt_env ( libc:: setenv ( k. as_ptr ( ) , v. as_ptr ( ) , 1 ) ) . map ( drop)
161
- }
158
+ run_with_cstr ( k. as_bytes ( ) , |k| {
159
+ run_with_cstr ( v. as_bytes ( ) , |v| {
160
+ let _guard = ENV_LOCK . write ( ) ;
161
+ cvt_env ( unsafe { libc:: setenv ( k. as_ptr ( ) , v. as_ptr ( ) , 1 ) } ) . map ( drop)
162
+ } )
163
+ } )
162
164
}
163
165
164
166
pub fn unsetenv ( n : & OsStr ) -> io:: Result < ( ) > {
165
- let nbuf = CString :: new ( n. as_bytes ( ) ) ?;
166
-
167
- unsafe {
167
+ run_with_cstr ( n. as_bytes ( ) , |nbuf| {
168
168
let _guard = ENV_LOCK . write ( ) ;
169
- cvt_env ( libc:: unsetenv ( nbuf. as_ptr ( ) ) ) . map ( drop)
170
- }
169
+ cvt_env ( unsafe { libc:: unsetenv ( nbuf. as_ptr ( ) ) } ) . map ( drop)
170
+ } )
171
171
}
172
172
173
173
/// In kmclib, `setenv` and `unsetenv` don't always set `errno`, so this
0 commit comments