Skip to content

Commit e5dea87

Browse files
committed
core: Add str::from_c_str, from_c_str_len, as_c_str
1 parent 3a2df84 commit e5dea87

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

src/libcore/str.rs

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,21 @@ export
1111
// Creating a string
1212
from_bytes,
1313
from_byte,
14-
push_char,
1514
from_char,
1615
from_chars,
1716
from_buf,
1817
from_buf_len,
18+
from_c_str,
19+
from_c_str_len,
20+
push_char,
1921
concat,
2022
connect,
2123

24+
// Reinterpretation
25+
as_bytes,
26+
as_buf,
27+
as_c_str,
28+
2229
// Adding things to and removing things from a string
2330
push_char,
2431
pop_char,
@@ -88,8 +95,6 @@ export
8895
char_range_at,
8996
is_char_boundary,
9097
char_at,
91-
as_bytes,
92-
as_buf,
9398
reserve,
9499

95100
unsafe;
@@ -192,6 +197,11 @@ fn from_buf(buf: *u8) -> str unsafe {
192197
ret from_buf_len(buf, i);
193198
}
194199

200+
#[doc = "Create a Rust string from a null-terminated C string"]
201+
fn from_c_str(c_str: *libc::c_char) -> str unsafe {
202+
from_buf(::unsafe::reinterpret_cast(c_str))
203+
}
204+
195205
#[doc = "Create a Rust string from a *u8 buffer of the given length"]
196206
fn from_buf_len(buf: *u8, len: uint) -> str unsafe {
197207
let mut v: [u8] = [];
@@ -206,6 +216,11 @@ fn from_buf_len(buf: *u8, len: uint) -> str unsafe {
206216
ret s;
207217
}
208218

219+
#[doc = "Create a Rust string from a `*c_char` buffer of the given length"]
220+
fn from_c_str_len(c_str: *libc::c_char, len: uint) -> str unsafe {
221+
from_buf_len(::unsafe::reinterpret_cast(c_str), len)
222+
}
223+
209224
#[doc = "Concatenate a vector of strings"]
210225
fn concat(v: [str]) -> str {
211226
let mut s: str = "";
@@ -1240,15 +1255,25 @@ Work with the byte buffer of a string.
12401255
12411256
Allows for unsafe manipulation of strings, which is useful for native
12421257
interop.
1258+
"]
1259+
fn as_buf<T>(s: str, f: fn(*u8) -> T) -> T unsafe {
1260+
as_bytes(s) { |v| vec::as_buf(v, f) }
1261+
}
1262+
1263+
#[doc = "
1264+
Work with the byte buffer of a string as a null-terminated C string.
1265+
1266+
Allows for unsafe manipulation of strings, which is useful for native
1267+
interop, without copying the original string.
12431268
12441269
# Example
12451270
12461271
```
12471272
let s = str::as_buf(\"PATH\", { |path_buf| libc::getenv(path_buf) });
12481273
```
12491274
"]
1250-
fn as_buf<T>(s: str, f: fn(*u8) -> T) -> T unsafe {
1251-
as_bytes(s) { |v| vec::as_buf(v, f) }
1275+
fn as_c_str<T>(s: str, f: fn(*libc::c_char) -> T) -> T unsafe {
1276+
as_buf(s) {|buf| f(buf as *libc::c_char) }
12521277
}
12531278

12541279
#[doc = "Allocate more memory for a string, up to `nn` + 1 bytes"]

0 commit comments

Comments
 (0)