Re-implemented Chunk#initialize in C.
[ruby-eet.git] / ext / ext.c
index 94b21bf4a226af15e522640821bfa8035ab96792..2c99b02b0890853179194349c6249b77b4ced03f 100644 (file)
--- a/ext/ext.c
+++ b/ext/ext.c
@@ -1,5 +1,5 @@
 /*
- * $Id: ext.c 38 2005-05-13 18:30:15Z tilman $
+ * $Id: ext.c 47 2005-05-30 19:19:07Z tilman $
  *
  * Copyright (c) 2005 Tilman Sauerbeck (tilman at code-monkey de)
  *
@@ -44,7 +44,7 @@
 
 static VALUE c_close (VALUE self);
 
-static VALUE id_include;
+static VALUE id_include, id_tag, id_data;
 
 static void
 c_free (Eet_File **ef)
@@ -454,6 +454,30 @@ stream_serialize (VALUE self)
        return ret;
 }
 
+static VALUE
+chunk_init (VALUE self, VALUE tag, VALUE data)
+{
+       unsigned long len;
+
+       StringValue (tag);
+       StringValue (data);
+
+       if (rb_funcall (tag, id_include, 1, INT2FIX (0)) == Qtrue) \
+               rb_raise (rb_eArgError, "tag must not contain binary zeroes");
+
+       /* libeet uses a signed 32bit integer to store the
+        * chunk size, so make sure we don't overflow it
+        */
+       len = RSTRING (tag)->len + 1 + RSTRING (data)->len;
+       if (len < 0 || len >= 2147483647L)
+               rb_raise (rb_eArgError, "tag or data too long");
+
+       rb_ivar_set (self, id_tag, rb_str_dup_frozen (tag));
+       rb_ivar_set (self, id_data, rb_str_dup_frozen (data));
+
+       return self;
+}
+
 static VALUE
 chunk_serialize (VALUE self)
 {
@@ -461,13 +485,6 @@ chunk_serialize (VALUE self)
        unsigned int size, buf_len;
        unsigned char *buf;
        struct RString *tag, *data;
-       static ID id_tag, id_data;
-
-       if (!id_tag)
-               id_tag = rb_intern ("@tag");
-
-       if (!id_data)
-               id_data = rb_intern ("@data");
 
        tmp = rb_ivar_get (self, id_tag);
        StringValue (tmp);
@@ -524,7 +541,13 @@ Init_eet_ext ()
        rb_define_method (cs, "serialize", stream_serialize, 0);
 
        cc = rb_define_class_under (m, "Chunk", rb_cObject);
+       rb_define_method (cc, "initialize", chunk_init, 2);
        rb_define_method (cc, "serialize", chunk_serialize, 0);
 
+       rb_define_attr (cc, "tag", 1, 0);
+       rb_define_attr (cc, "data", 1, 0);
+
        id_include = rb_intern ("include?");
+       id_tag = rb_intern ("@tag");
+       id_data = rb_intern ("@data");
 }