Bryan Duxbury | c016628 | 2009-02-02 00:48:17 +0000 | [diff] [blame^] | 1 | #include <ruby.h> |
| 2 | #include <constants.h> |
| 3 | |
| 4 | ID buf_ivar_id; |
| 5 | ID index_ivar_id; |
| 6 | |
| 7 | ID slice_method_id; |
| 8 | |
| 9 | int GARBAGE_BUFFER_SIZE; |
| 10 | |
| 11 | #define GET_BUF(self) rb_ivar_get(self, buf_ivar_id) |
| 12 | |
| 13 | VALUE rb_thrift_memory_buffer_write(VALUE self, VALUE str) { |
| 14 | VALUE buf = GET_BUF(self); |
| 15 | rb_str_buf_cat(buf, RSTRING(str)->ptr, RSTRING(str)->len); |
| 16 | return Qnil; |
| 17 | } |
| 18 | |
| 19 | VALUE rb_thrift_memory_buffer_read(VALUE self, VALUE length_value) { |
| 20 | int length = FIX2INT(length_value); |
| 21 | |
| 22 | VALUE index_value = rb_ivar_get(self, index_ivar_id); |
| 23 | int index = FIX2INT(index_value); |
| 24 | |
| 25 | VALUE buf = GET_BUF(self); |
| 26 | VALUE data = rb_funcall(buf, slice_method_id, 2, index_value, length_value); |
| 27 | |
| 28 | index += length; |
| 29 | if (index > RSTRING(buf)->len) { |
| 30 | index = RSTRING(buf)->len; |
| 31 | } |
| 32 | if (index >= GARBAGE_BUFFER_SIZE) { |
| 33 | rb_ivar_set(self, buf_ivar_id, rb_funcall(buf, slice_method_id, 2, INT2FIX(index), INT2FIX(-1))); |
| 34 | index = 0; |
| 35 | } |
| 36 | |
| 37 | rb_ivar_set(self, index_ivar_id, INT2FIX(index)); |
| 38 | return data; |
| 39 | } |
| 40 | |
| 41 | void Init_memory_buffer() { |
| 42 | VALUE thrift_memory_buffer_class = rb_const_get(thrift_module, rb_intern("MemoryBuffer")); |
| 43 | rb_define_method(thrift_memory_buffer_class, "write", rb_thrift_memory_buffer_write, 1); |
| 44 | rb_define_method(thrift_memory_buffer_class, "read", rb_thrift_memory_buffer_read, 1); |
| 45 | |
| 46 | buf_ivar_id = rb_intern("@buf"); |
| 47 | index_ivar_id = rb_intern("@index"); |
| 48 | |
| 49 | slice_method_id = rb_intern("slice"); |
| 50 | |
| 51 | GARBAGE_BUFFER_SIZE = FIX2INT(rb_const_get(thrift_memory_buffer_class, rb_intern("GARBAGE_BUFFER_SIZE"))); |
| 52 | } |