blob: a607ae2f5867aee744a2c919939c5400a2f3ed24 [file] [log] [blame]
Bryan Duxburyc0166282009-02-02 00:48:17 +00001#include <ruby.h>
2#include <constants.h>
3
4ID buf_ivar_id;
5ID index_ivar_id;
6
7ID slice_method_id;
8
9int GARBAGE_BUFFER_SIZE;
10
11#define GET_BUF(self) rb_ivar_get(self, buf_ivar_id)
12
13VALUE 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
19VALUE 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
41void 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}