summaryrefslogtreecommitdiffhomepage
path: root/src
diff options
context:
space:
mode:
authorYukihiro Matsumoto <[email protected]>2012-11-01 06:12:11 +0900
committerYukihiro Matsumoto <[email protected]>2012-11-01 06:12:11 +0900
commitfe36bdb7f12050254f02a5f2c3a75623dfd289c0 (patch)
tree935c32eaacb273ad68ab926f5df4c8fe48e07a63 /src
parent9b85ffa5a760e53536762bf6cdf402c90ae9ceb7 (diff)
downloadmruby-fe36bdb7f12050254f02a5f2c3a75623dfd289c0.tar.gz
mruby-fe36bdb7f12050254f02a5f2c3a75623dfd289c0.zip
add String#bytes to return bytes in a string
Diffstat (limited to 'src')
-rw-r--r--src/string.c24
1 files changed, 24 insertions, 0 deletions
diff --git a/src/string.c b/src/string.c
index f3ceb6d96..8eb08562d 100644
--- a/src/string.c
+++ b/src/string.c
@@ -2989,6 +2989,29 @@ mrb_str_inspect(mrb_state *mrb, mrb_value str)
return result;
}
+/*
+ * call-seq:
+ * str.bytes -> array of fixnums
+ *
+ * Returns an array of bytes in _str_.
+ *
+ * str = "hello"
+ * str.bytes #=> [104, 101, 108, 108, 111]
+ */
+static mrb_value
+mrb_str_bytes(mrb_state *mrb, mrb_value str)
+{
+ struct RString *s = mrb_str_ptr(str);
+ mrb_value a = mrb_ary_new_capa(mrb, s->len);
+ char *p = s->ptr, *pend = p + s->len;
+
+ while (p < pend) {
+ mrb_ary_push(mrb, a, mrb_fixnum_value(p[0]));
+ p++;
+ }
+ return a;
+}
+
/* ---------------------------*/
void
mrb_init_string(mrb_state *mrb)
@@ -3053,4 +3076,5 @@ mrb_init_string(mrb_state *mrb)
mrb_define_method(mrb, s, "upcase", mrb_str_upcase, ARGS_REQ(1)); /* 15.2.10.5.42 */
mrb_define_method(mrb, s, "upcase!", mrb_str_upcase_bang, ARGS_REQ(1)); /* 15.2.10.5.43 */
mrb_define_method(mrb, s, "inspect", mrb_str_inspect, ARGS_NONE()); /* 15.2.10.5.46(x) */
+ mrb_define_method(mrb, s, "bytes", mrb_str_bytes, ARGS_NONE());
}