From: Tanaka Akira Date: 2008-01-28T00:59:49+09:00 Subject: [ruby-dev:33428] Re: Binary String In article , Yukihiro Matsumoto writes: > みなさんはどう思います? 私は非対称性が気になるので、 > > * b=s.bytes; b[1] = b[1]+1 > * s.byte(1)=s.byte(1)+1 > * s.set_byte(1,s.byte(1)+1) > > のようなのがいいかなあと思ってますが。 String#byte と String#set_byte ならこんなですかね。 でも、String#byte って String#bytes と名前が似すぎてませんか ね。get_byte にして bytes とは離したほうがいいような感じが ちょっと。 Index: string.c =================================================================== --- string.c (revision 15281) +++ string.c (working copy) @@ -3074,6 +3074,49 @@ rb_str_chr(VALUE str) /* * call-seq: + * str.byte(index) => 0 .. 255 + * + * returns the indexth byte as an integer. + */ +static VALUE +rb_str_byte(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.set_byte(index, int) => int + * + * modifies the indexth byte as int. + */ +static VALUE +rb_str_set_byte(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 * * Returns a new string with the characters from str in reverse order. @@ -6054,6 +6097,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, "byte", rb_str_byte, 1); + rb_define_method(rb_cString, "set_byte", rb_str_set_byte, 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); -- [田中 哲][たなか あきら][Tanaka Akira]