@@ -2024,6 +2024,13 @@ pub trait OwnedStr {
2024
2024
fn capacity(&self) -> uint;
2025
2025
fn to_bytes_with_null(self) -> ~[u8];
2026
2026
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
+
2027
2034
/// Work with the mutable byte buffer and length of a slice.
2028
2035
///
2029
2036
/// The given length is one byte longer than the 'official' indexable
@@ -2215,6 +2222,13 @@ impl OwnedStr for ~str {
2215
2222
unsafe { cast::transmute(self) }
2216
2223
}
2217
2224
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
+
2218
2232
#[inline]
2219
2233
fn as_mut_buf<T>(&mut self, f: &fn(*mut u8, uint) -> T) -> T {
2220
2234
let v: &mut ~[u8] = unsafe { cast::transmute(self) };
@@ -3059,6 +3073,18 @@ mod tests {
3059
3073
}
3060
3074
3061
3075
#[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
+
3062
3088
fn test_subslice_offset() {
3063
3089
let a = " kernelsprite";
3064
3090
let b = a.slice(7, a.len());
0 commit comments