write(p1)
public
Appends the given string to the
underlying buffer string of
strio. The stream must be opened for writing. If the argument is
not a string, it will be converted to a string using to_s. Returns the number of
bytes written. See IO#write.
Show source
static VALUE
strio_write(VALUE self, VALUE str)
{
struct StringIO *ptr = writable(self);
long len, olen;
rb_encoding *enc, *enc2;
rb_encoding *const ascii8bit = rb_ascii8bit_encoding();
if (!RB_TYPE_P(str, T_STRING))
str = rb_obj_as_string(str);
enc = rb_enc_get(ptr->string);
enc2 = rb_enc_get(str);
if (enc != enc2 && enc != ascii8bit) {
str = rb_str_conv_enc(str, enc2, enc);
}
len = RSTRING_LEN(str);
if (len == 0) return INT2FIX(0);
check_modifiable(ptr);
olen = RSTRING_LEN(ptr->string);
if (ptr->flags & FMODE_APPEND) {
ptr->pos = olen;
}
if (ptr->pos == olen) {
if (enc == ascii8bit || enc2 == ascii8bit) {
rb_enc_str_buf_cat(ptr->string, RSTRING_PTR(str), len, enc);
OBJ_INFECT(ptr->string, str);
}
else {
rb_str_buf_append(ptr->string, str);
}
}
else {
strio_extend(ptr, ptr->pos, len);
memmove(RSTRING_PTR(ptr->string)+ptr->pos, RSTRING_PTR(str), len);
OBJ_INFECT(ptr->string, str);
}
OBJ_INFECT(ptr->string, self);
RB_GC_GUARD(str);
ptr->pos += len;
return LONG2NUM(len);
}