Skip to content

Commit 08b6cb4

Browse files
committed
std: add str.to_c_str()
1 parent 6011f83 commit 08b6cb4

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/libstd/os.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1948,7 +1948,7 @@ mod tests {
19481948
};
19491949
assert!((ostream as uint != 0u));
19501950
let s = ~"hello";
1951-
let mut buf = s.as_bytes_with_null().to_owned();
1951+
let mut buf = s.to_owned().to_c_str();
19521952
let len = buf.len();
19531953
do buf.as_mut_buf |b, _len| {
19541954
assert_eq!(libc::fwrite(b as *c_void, 1u as size_t,

src/libstd/str.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2024,6 +2024,13 @@ pub trait OwnedStr {
20242024
fn capacity(&self) -> uint;
20252025
fn to_bytes_with_null(self) -> ~[u8];
20262026
2027+
/// Allocates a null terminate byte array.
2028+
///
2029+
/// # Failure
2030+
///
2031+
/// Fails if there are any null characters inside the byte array.
2032+
fn to_c_str(self) -> ~[u8];
2033+
20272034
/// Work with the mutable byte buffer and length of a slice.
20282035
///
20292036
/// The given length is one byte longer than the 'official' indexable
@@ -2215,6 +2222,13 @@ impl OwnedStr for ~str {
22152222
unsafe { cast::transmute(self) }
22162223
}
22172224
2225+
#[inline]
2226+
fn to_c_str(self) -> ~[u8] {
2227+
let bytes = self.to_bytes_with_null();
2228+
assert!(bytes.slice(0, bytes.len() - 1).iter().all(|byte| *byte != 0));
2229+
bytes
2230+
}
2231+
22182232
#[inline]
22192233
fn as_mut_buf<T>(&mut self, f: &fn(*mut u8, uint) -> T) -> T {
22202234
let v: &mut ~[u8] = unsafe { cast::transmute(self) };
@@ -3059,6 +3073,18 @@ mod tests {
30593073
}
30603074
30613075
#[test]
3076+
fn test_to_c_str() {
3077+
let s = ~"ศไทย中华Việt Nam";
3078+
let v = ~[
3079+
224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228,
3080+
184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97,
3081+
109, 0
3082+
];
3083+
assert_eq!((~"").to_c_str(), ~[0]);
3084+
assert_eq!((~"abc").to_c_str(), ~['a' as u8, 'b' as u8, 'c' as u8, 0]);
3085+
assert_eq!(s.to_c_str(), v);
3086+
}
3087+
30623088
fn test_subslice_offset() {
30633089
let a = "kernelsprite";
30643090
let b = a.slice(7, a.len());

0 commit comments

Comments
 (0)