Skip to content

Instantly share code, notes, and snippets.

@swarley
Created October 30, 2019 23:47
Show Gist options
  • Save swarley/cddfaf6f79096262d747ca98f2fb955e to your computer and use it in GitHub Desktop.
Save swarley/cddfaf6f79096262d747ca98f2fb955e to your computer and use it in GitHub Desktop.
#include <ruby.h>
#include <ctype.h>
#define MAX_LENGTH 2000
VALUE rb_mBigBrain = Qnil;
int bigbrain_find_ideal(char *str) {
int len = strlen(str);
char* loc;
if(len <= MAX_LENGTH)
return len;
for(loc = &str[MAX_LENGTH]; loc > str && !isspace(*loc); loc--);
if (loc == str)
return MAX_LENGTH;
else
return (loc + 1) - str;
}
VALUE bigbrain_split_message(VALUE self, VALUE str) {
char* cstr = StringValueCStr(str);
int len = strlen(cstr);
int index = 0;
int ending_index = len;
int ideal_size;
VALUE rb_msg_arr = rb_ary_new();
if(len > MAX_LENGTH) {
while((len - index) >= MAX_LENGTH) {
ideal_size = bigbrain_find_ideal(&cstr[index]);
rb_ary_push(rb_msg_arr, rb_str_new(&cstr[index], (long)ideal_size));
index += ideal_size;
}
}
do {
ending_index--;
} while(isspace(cstr[ending_index]));
rb_ary_push(rb_msg_arr, rb_str_new(&cstr[index], (ending_index + 1) - index));
return rb_msg_arr;
}
void Init_bigbrain() {
rb_mBigBrain = rb_define_module("BigBrain");
rb_define_const(rb_mBigBrain, "MAX_LENGTH", INT2NUM(MAX_LENGTH));
rb_define_module_function(rb_mBigBrain, "split_message", bigbrain_split_message, 1);
}
// vim: set sts=4 ts=4 sw=4 expandtab:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment