Skip to content

Commit ea7197e

Browse files
committed
rustc: Add str_from_cstr() and str_from_buf() functions to the standard library, as well as a test case
1 parent 320ac6b commit ea7197e

File tree

4 files changed

+48
-0
lines changed

4 files changed

+48
-0
lines changed

src/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,7 @@ TEST_XFAILS_RUSTC := $(addprefix test/run-pass/, \
498498
lib-sha1.rs \
499499
lib-sort.rs \
500500
lib-str.rs \
501+
lib-str-buf.rs \
501502
lib-task.rs \
502503
lib-uint.rs \
503504
lib-vec-str-conversions.rs \

src/lib/_str.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ native "rust" mod rustrt {
88
fn str_byte_len(str s) -> uint;
99
fn str_alloc(uint n_bytes) -> str;
1010
fn str_from_vec(vec[u8] b) -> str;
11+
fn str_from_cstr(sbuf cstr) -> str;
12+
fn str_from_buf(sbuf buf, uint len) -> str;
1113
fn refcount[T](str s) -> uint;
1214
}
1315

@@ -115,6 +117,14 @@ fn unsafe_from_byte(u8 u) -> str {
115117
ret rustrt.str_from_vec(vec(u));
116118
}
117119

120+
unsafe fn str_from_cstr(sbuf cstr) -> str {
121+
ret rustrt.str_from_cstr(cstr);
122+
}
123+
124+
unsafe fn str_from_buf(sbuf buf, uint len) -> str {
125+
ret rustrt.str_from_buf(buf, len);
126+
}
127+
118128

119129
fn refcount(str s) -> uint {
120130
auto r = rustrt.refcount[u8](s);

src/rt/rust_builtin.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,29 @@ str_from_vec(rust_task *task, rust_vec *v)
207207
return st;
208208
}
209209

210+
extern "C" CDECL rust_str *
211+
str_from_cstr(rust_task *task, char *sbuf)
212+
{
213+
size_t len = strlen(sbuf) + 1;
214+
rust_str *st = vec_alloc_with_data(task, len, len, 1, sbuf);
215+
if (!st) {
216+
task->fail(2);
217+
return NULL;
218+
}
219+
return st;
220+
}
221+
222+
extern "C" CDECL rust_str *
223+
str_from_buf(rust_task *task, char *buf, unsigned int len) {
224+
rust_str *st = vec_alloc_with_data(task, len + 1, len, 1, buf);
225+
if (!st) {
226+
task->fail(2);
227+
return NULL;
228+
}
229+
st->data[st->fill++] = '\0';
230+
return st;
231+
}
232+
210233
extern "C" CDECL void *
211234
rand_new(rust_task *task)
212235
{

src/test/run-pass/lib-str-buf.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// -*- rust -*-
2+
3+
use std;
4+
import std._str;
5+
6+
fn main() {
7+
auto s = "hello";
8+
auto sb = _str.rustrt.str_buf(s);
9+
auto s_cstr = _str.rustrt.str_from_cstr(sb);
10+
check (_str.eq(s_cstr, s));
11+
auto s_buf = _str.rustrt.str_from_buf(sb, 5u);
12+
check (_str.eq(s_buf, s));
13+
}
14+

0 commit comments

Comments
 (0)