From 12b1578cabdf06cc76f6debaf8a953a922b47154 Mon Sep 17 00:00:00 2001 From: akr Date: Fri, 15 Feb 2008 06:35:20 +0000 Subject: * string.c (rb_str_getbyte): new method. (rb_str_setbyte): new method. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@15484 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- string.c | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'string.c') diff --git a/string.c b/string.c index ade00a3d27..1f6e2f8450 100644 --- a/string.c +++ b/string.c @@ -3125,6 +3125,49 @@ rb_str_chr(VALUE str) return rb_str_substr(str, 0, 1); } +/* + * call-seq: + * str.getbyte(index) => 0 .. 255 + * + * returns the indexth byte as an integer. + */ +static VALUE +rb_str_getbyte(VALUE str, VALUE index) +{ + long pos = NUM2LONG(index); + + if (pos < 0) + pos += RSTRING_LEN(str); + if (pos < 0 || RSTRING_LEN(str) <= pos) + return Qnil; + + return INT2FIX((unsigned char)RSTRING_PTR(str)[pos]); +} + +/* + * call-seq: + * str.setbyte(index, int) => int + * + * modifies the indexth byte as int. + */ +static VALUE +rb_str_setbyte(VALUE str, VALUE index, VALUE value) +{ + long pos = NUM2LONG(index); + int byte = NUM2INT(value); + + rb_str_modify(str); + + if (pos < -RSTRING_LEN(str) || RSTRING_LEN(str) <= pos) + rb_raise(rb_eIndexError, "index %ld out of string", pos); + if (pos < 0) + pos += RSTRING_LEN(str); + + RSTRING_PTR(str)[pos] = byte; + + return value; +} + /* * call-seq: * str.reverse => new_str @@ -6107,6 +6150,8 @@ Init_String(void) rb_define_method(rb_cString, "replace", rb_str_replace, 1); rb_define_method(rb_cString, "clear", rb_str_clear, 0); rb_define_method(rb_cString, "chr", rb_str_chr, 0); + rb_define_method(rb_cString, "getbyte", rb_str_getbyte, 1); + rb_define_method(rb_cString, "setbyte", rb_str_setbyte, 2); rb_define_method(rb_cString, "to_i", rb_str_to_i, -1); rb_define_method(rb_cString, "to_f", rb_str_to_f, 0); -- cgit v1.2.3