11use super :: unsupported;
2+ use crate :: convert:: TryFrom ;
23use crate :: error:: Error as StdError ;
34use crate :: ffi:: { CStr , CString , OsStr , OsString } ;
45use crate :: fmt;
@@ -9,6 +10,7 @@ use crate::os::{
910} ;
1011use crate :: path:: { self , PathBuf } ;
1112use crate :: sync:: RwLock ;
13+ use crate :: sys:: common:: small_c_string:: run_with_cstr;
1214use crate :: vec;
1315
1416use super :: { error, itron, memchr} ;
@@ -139,35 +141,33 @@ pub fn env() -> Env {
139141pub fn getenv ( k : & OsStr ) -> Option < OsString > {
140142 // environment variables with a nul byte can't be set, so their value is
141143 // 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| {
144145 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 ( ) ) )
151154 }
152155}
153156
154157pub 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+ } )
162164}
163165
164166pub 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| {
168168 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+ } )
171171}
172172
173173/// In kmclib, `setenv` and `unsetenv` don't always set `errno`, so this
0 commit comments