blob: e37c787eb84c88a70fa001895786e8eafc7b0fe0 [file] [log] [blame]
Kevin Clark916f3532009-03-20 04:21:39 +00001/**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
Bryan Duxburyc0166282009-02-02 00:48:17 +000020#include <ruby.h>
21#include <constants.h>
22
23ID buf_ivar_id;
24ID index_ivar_id;
25
26ID slice_method_id;
27
28int GARBAGE_BUFFER_SIZE;
29
30#define GET_BUF(self) rb_ivar_get(self, buf_ivar_id)
31
32VALUE rb_thrift_memory_buffer_write(VALUE self, VALUE str) {
33 VALUE buf = GET_BUF(self);
34 rb_str_buf_cat(buf, RSTRING(str)->ptr, RSTRING(str)->len);
35 return Qnil;
36}
37
38VALUE rb_thrift_memory_buffer_read(VALUE self, VALUE length_value) {
39 int length = FIX2INT(length_value);
40
41 VALUE index_value = rb_ivar_get(self, index_ivar_id);
42 int index = FIX2INT(index_value);
43
44 VALUE buf = GET_BUF(self);
45 VALUE data = rb_funcall(buf, slice_method_id, 2, index_value, length_value);
46
47 index += length;
48 if (index > RSTRING(buf)->len) {
49 index = RSTRING(buf)->len;
50 }
51 if (index >= GARBAGE_BUFFER_SIZE) {
Bryan Duxbury2f20ae42009-03-24 21:10:14 +000052 rb_ivar_set(self, buf_ivar_id, rb_funcall(buf, slice_method_id, 2, INT2FIX(index), INT2FIX(RSTRING(buf)->len - 1)));
Bryan Duxburyc0166282009-02-02 00:48:17 +000053 index = 0;
54 }
55
56 rb_ivar_set(self, index_ivar_id, INT2FIX(index));
57 return data;
58}
59
60void Init_memory_buffer() {
61 VALUE thrift_memory_buffer_class = rb_const_get(thrift_module, rb_intern("MemoryBuffer"));
62 rb_define_method(thrift_memory_buffer_class, "write", rb_thrift_memory_buffer_write, 1);
63 rb_define_method(thrift_memory_buffer_class, "read", rb_thrift_memory_buffer_read, 1);
64
65 buf_ivar_id = rb_intern("@buf");
66 index_ivar_id = rb_intern("@index");
67
68 slice_method_id = rb_intern("slice");
69
70 GARBAGE_BUFFER_SIZE = FIX2INT(rb_const_get(thrift_memory_buffer_class, rb_intern("GARBAGE_BUFFER_SIZE")));
Bryan Duxbury1e80d442009-02-03 18:16:54 +000071}