1 #include <mruby.h>
2 #include <mruby/class.h>
3 #include <mruby/string.h>
4 #include <mruby/istruct.h>
5
6 static mrb_value
istruct_test_initialize(mrb_state * mrb,mrb_value self)7 istruct_test_initialize(mrb_state *mrb, mrb_value self)
8 {
9 char *string = (char*)mrb_istruct_ptr(self);
10 mrb_int size = mrb_istruct_size();
11 mrb_value object;
12 mrb_get_args(mrb, "o", &object);
13
14 if (mrb_fixnum_p(object)) {
15 strncpy(string, "fixnum", size-1);
16 }
17 #ifndef MRB_WITHOUT_FLOAT
18 else if (mrb_float_p(object)) {
19 strncpy(string, "float", size-1);
20 }
21 #endif
22 else if (mrb_string_p(object)) {
23 strncpy(string, "string", size-1);
24 }
25 else {
26 strncpy(string, "anything", size-1);
27 }
28
29 string[size - 1] = 0; // force NULL at the end
30 return self;
31 }
32
33 static mrb_value
istruct_test_to_s(mrb_state * mrb,mrb_value self)34 istruct_test_to_s(mrb_state *mrb, mrb_value self)
35 {
36 return mrb_str_new_cstr(mrb, (const char*)mrb_istruct_ptr(self));
37 }
38
39 static mrb_value
istruct_test_length(mrb_state * mrb,mrb_value self)40 istruct_test_length(mrb_state *mrb, mrb_value self)
41 {
42 return mrb_fixnum_value(mrb_istruct_size());
43 }
44
45 static mrb_value
istruct_test_test_receive(mrb_state * mrb,mrb_value self)46 istruct_test_test_receive(mrb_state *mrb, mrb_value self)
47 {
48 mrb_value object;
49 mrb_get_args(mrb, "o", &object);
50 if (mrb_obj_class(mrb, object) != mrb_class_get(mrb, "InlineStructTest"))
51 {
52 mrb_raise(mrb, E_TYPE_ERROR, "Expected InlineStructTest");
53 }
54 return mrb_bool_value(((char*)mrb_istruct_ptr(object))[0] == 's');
55 }
56
57 static mrb_value
istruct_test_test_receive_direct(mrb_state * mrb,mrb_value self)58 istruct_test_test_receive_direct(mrb_state *mrb, mrb_value self)
59 {
60 char *ptr;
61 mrb_get_args(mrb, "I", &ptr);
62 return mrb_bool_value(ptr[0] == 's');
63 }
64
65 static mrb_value
istruct_test_mutate(mrb_state * mrb,mrb_value self)66 istruct_test_mutate(mrb_state *mrb, mrb_value self)
67 {
68 char *ptr = (char*)mrb_istruct_ptr(self);
69 memcpy(ptr, "mutate", 6);
70 return mrb_nil_value();
71 }
72
mrb_mruby_inline_struct_gem_test(mrb_state * mrb)73 void mrb_mruby_inline_struct_gem_test(mrb_state *mrb)
74 {
75 struct RClass *cls;
76
77 cls = mrb_define_class(mrb, "InlineStructTest", mrb->object_class);
78 MRB_SET_INSTANCE_TT(cls, MRB_TT_ISTRUCT);
79 mrb_define_method(mrb, cls, "initialize", istruct_test_initialize, MRB_ARGS_REQ(1));
80 mrb_define_method(mrb, cls, "to_s", istruct_test_to_s, MRB_ARGS_NONE());
81 mrb_define_method(mrb, cls, "mutate", istruct_test_mutate, MRB_ARGS_NONE());
82 mrb_define_class_method(mrb, cls, "length", istruct_test_length, MRB_ARGS_NONE());
83 mrb_define_class_method(mrb, cls, "test_receive", istruct_test_test_receive, MRB_ARGS_REQ(1));
84 mrb_define_class_method(mrb, cls, "test_receive_direct", istruct_test_test_receive_direct, MRB_ARGS_REQ(1));
85 }
86