Skip to content

Commit 9f7c9fb

Browse files
committed
Implement NixPath for str and OsStr
This is a stop gap improvement until the NixPath reform is figured out. refs nix-rust#221
1 parent beec2f4 commit 9f7c9fb

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

src/lib.rs

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ pub mod unistd;
5050

5151
use libc::c_char;
5252
use std::{ptr, result};
53-
use std::ffi::CStr;
53+
use std::ffi::{CStr, OsStr};
5454
use std::path::{Path, PathBuf};
5555
use std::os::unix::ffi::OsStrExt;
5656
use std::io;
@@ -125,6 +125,28 @@ pub trait NixPath {
125125
where F: FnOnce(&CStr) -> T;
126126
}
127127

128+
impl NixPath for str {
129+
fn len(&self) -> usize {
130+
NixPath::len(OsStr::new(self))
131+
}
132+
133+
fn with_nix_path<T, F>(&self, f: F) -> Result<T>
134+
where F: FnOnce(&CStr) -> T {
135+
OsStr::new(self).with_nix_path(f)
136+
}
137+
}
138+
139+
impl NixPath for OsStr {
140+
fn len(&self) -> usize {
141+
self.as_bytes().len()
142+
}
143+
144+
fn with_nix_path<T, F>(&self, f: F) -> Result<T>
145+
where F: FnOnce(&CStr) -> T {
146+
self.as_bytes().with_nix_path(f)
147+
}
148+
}
149+
128150
impl NixPath for CStr {
129151
fn len(&self) -> usize {
130152
self.to_bytes().len()
@@ -170,21 +192,21 @@ impl NixPath for [u8] {
170192

171193
impl NixPath for Path {
172194
fn len(&self) -> usize {
173-
self.as_os_str().as_bytes().len()
195+
NixPath::len(self.as_os_str())
174196
}
175197

176198
fn with_nix_path<T, F>(&self, f: F) -> Result<T> where F: FnOnce(&CStr) -> T {
177-
self.as_os_str().as_bytes().with_nix_path(f)
199+
self.as_os_str().with_nix_path(f)
178200
}
179201
}
180202

181203
impl NixPath for PathBuf {
182204
fn len(&self) -> usize {
183-
self.as_os_str().as_bytes().len()
205+
NixPath::len(self.as_os_str())
184206
}
185207

186208
fn with_nix_path<T, F>(&self, f: F) -> Result<T> where F: FnOnce(&CStr) -> T {
187-
self.as_os_str().as_bytes().with_nix_path(f)
209+
self.as_os_str().with_nix_path(f)
188210
}
189211
}
190212

0 commit comments

Comments
 (0)