Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

add String#getbyte

Conflicts:

	src/string.c
	test/t/string.rb
  • Loading branch information...
commit f780ab84ae190147f5dcfcb4998814973cce6ac6 1 parent cb3813c
@akiray03 akiray03 authored
Showing with 35 additions and 0 deletions.
  1. +23 −0 src/string.c
  2. +12 −0 test/t/string.rb
View
23 src/string.c
@@ -3043,6 +3043,28 @@ mrb_str_bytes(mrb_state *mrb, mrb_value str)
return a;
}
+static mrb_value
+mrb_str_getbyte(mrb_state *mrb, mrb_value str)
+{
+ mrb_int idx;
+ struct RString *s;
+ mrb_value str2;
+ unsigned char *p;
+
+ mrb_get_args(mrb, "i", &idx);
+ str2 = mrb_str_substr(mrb, str, idx, 1);
+ if (mrb_nil_p(str2) || RSTRING_LEN(str2) == 0) {
+ return mrb_nil_value();
+ }
+
+ s = mrb_str_ptr(str2);
+ p = (unsigned char *)(s->ptr);
+
+ return mrb_fixnum_value(p[0]);
+}
+
+
+
/* ---------------------------*/
void
mrb_init_string(mrb_state *mrb)
@@ -3110,6 +3132,7 @@ mrb_init_string(mrb_state *mrb)
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());
+ mrb_define_method(mrb, s, "getbyte", mrb_str_getbyte, ARGS_REQ(1));
mrb_gv_set(mrb, mrb_intern(mrb, "$;"), mrb_nil_value());
}
View
12 test/t/string.rb
@@ -602,3 +602,15 @@
"%-5s: %08x" % [ "ID", 123 ] == "ID : 0000007b" and
"foo = %{foo}" % { :foo => 'bar' } == "foo = bar"
end
+
+assert('String#getbyte') do
+ str1 = "hello"
+ bytes1 = [104, 101, 108, 108, 111]
+ assert_equal bytes1[0], str1.getbyte(0)
+ assert_equal bytes1[-1], str1.getbyte(-1)
+ assert_equal bytes1[6], str1.getbyte(6)
+
+ str2 = "\xFF"
+ bytes2 = [0xFF]
+ assert_equal bytes2[0], str2.getbyte(0)
+end
Please sign in to comment.
Something went wrong with that request. Please try again.