Skip to content

Commit a880a9d

Browse files
committed
Implement NixPath for str and OsStr
This is a stop gap improvement until the NixPath reform is figured out. refs #221
1 parent e8f014d commit a880a9d

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
@@ -48,7 +48,7 @@ pub mod unistd;
4848

4949
use libc::c_char;
5050
use std::{ptr, result};
51-
use std::ffi::CStr;
51+
use std::ffi::{CStr, OsStr};
5252
use std::path::{Path, PathBuf};
5353
use std::os::unix::ffi::OsStrExt;
5454
use std::io;
@@ -123,6 +123,28 @@ pub trait NixPath {
123123
where F: FnOnce(&CStr) -> T;
124124
}
125125

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

169191
impl NixPath for Path {
170192
fn len(&self) -> usize {
171-
self.as_os_str().as_bytes().len()
193+
NixPath::len(self.as_os_str())
172194
}
173195

174196
fn with_nix_path<T, F>(&self, f: F) -> Result<T> where F: FnOnce(&CStr) -> T {
175-
self.as_os_str().as_bytes().with_nix_path(f)
197+
self.as_os_str().with_nix_path(f)
176198
}
177199
}
178200

179201
impl NixPath for PathBuf {
180202
fn len(&self) -> usize {
181-
self.as_os_str().as_bytes().len()
203+
NixPath::len(self.as_os_str())
182204
}
183205

184206
fn with_nix_path<T, F>(&self, f: F) -> Result<T> where F: FnOnce(&CStr) -> T {
185-
self.as_os_str().as_bytes().with_nix_path(f)
207+
self.as_os_str().with_nix_path(f)
186208
}
187209
}
188210

0 commit comments

Comments
 (0)