Created
January 27, 2025 09:35
-
-
Save romanbsd/0e8eb6633a86a4782a1d5723b50ceea0 to your computer and use it in GitHub Desktop.
stringio.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ruby.h> | |
#include <sstream> | |
#include <string> | |
class StringIO { | |
private: | |
std::ostringstream oss; | |
public: | |
StringIO() = default; | |
void write(const std::string &data) { | |
oss << data; | |
} | |
std::string read() { | |
return oss.str(); | |
} | |
std::string string() { | |
return oss.str(); | |
} | |
void clear() { | |
oss.str(""); | |
oss.clear(); | |
} | |
}; | |
// Ruby data wrapper for the C++ StringIO class | |
static VALUE rb_cStringIO; | |
static void stringio_free(void *ptr) { | |
delete static_cast<StringIO *>(ptr); | |
} | |
static VALUE stringio_alloc(VALUE klass) { | |
StringIO *ptr = new StringIO(); | |
return Data_Wrap_Struct(klass, nullptr, stringio_free, ptr); | |
} | |
static VALUE stringio_initialize(VALUE self) { | |
rb_iv_set(self, "@__swigtype__", rb_str_new2("_p_std__ostringstream")); | |
return self; | |
} | |
static VALUE stringio_write(VALUE self, VALUE rb_data) { | |
StringIO *ptr; | |
Data_Get_Struct(self, StringIO, ptr); | |
std::string data = StringValueCStr(rb_data); | |
ptr->write(data); | |
return Qnil; | |
} | |
static VALUE stringio_read(VALUE self) { | |
StringIO *ptr; | |
Data_Get_Struct(self, StringIO, ptr); | |
std::string data = ptr->read(); | |
return rb_str_new_cstr(data.c_str()); | |
} | |
static VALUE stringio_string(VALUE self) { | |
StringIO *ptr; | |
Data_Get_Struct(self, StringIO, ptr); | |
std::string data = ptr->string(); | |
return rb_str_new_cstr(data.c_str()); | |
} | |
static VALUE stringio_clear(VALUE self) { | |
StringIO *ptr; | |
Data_Get_Struct(self, StringIO, ptr); | |
ptr->clear(); | |
return Qnil; | |
} | |
extern "C" void Init_stringio() { | |
rb_cStringIO = rb_define_class("StringIO", rb_cObject); | |
rb_define_alloc_func(rb_cStringIO, stringio_alloc); | |
rb_define_method(rb_cStringIO, "initialize", RUBY_METHOD_FUNC(stringio_initialize), 0); | |
rb_define_method(rb_cStringIO, "write", RUBY_METHOD_FUNC(stringio_write), 1); | |
rb_define_method(rb_cStringIO, "read", RUBY_METHOD_FUNC(stringio_read), 0); | |
rb_define_method(rb_cStringIO, "string", RUBY_METHOD_FUNC(stringio_string), 0); | |
rb_define_method(rb_cStringIO, "clear", RUBY_METHOD_FUNC(stringio_clear), 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment