2 * $Id: ext.c 72 2005-07-16 13:15:42Z tilman $
4 * Copyright (c) 2005 Tilman Sauerbeck (tilman at code-monkey de)
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 #define CHECK_KEY(key) \
32 if (rb_funcall (key, id_include, 1, INT2FIX (0)) == Qtrue) \
33 rb_raise (rb_eArgError, "key must not contain binary zeroes");
35 #define CHECK_CLOSED(ef) \
37 rb_raise (rb_eIOError, "closed stream");
39 #ifdef WORDS_BIGENDIAN
41 ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
42 (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
43 #else /* !WORDS_BIGENDIAN */
44 # define BSWAP32(x) (x)
45 #endif /* WORDS_BIGENDIAN */
47 static VALUE c_close (VALUE self);
49 static VALUE cStream, cChunk,
50 eEetError, eNameError, ePropError,
51 sym_lossy, sym_level, sym_quality, sym_char, sym_short,
52 sym_long_long, sym_double;
53 static ID id_include, id_to_s, id_keys, id_pack,
54 id_to_eet_chunks, id_to_eet_name, id_to_eet_properties,
58 c_free (Eet_File **ef)
75 return Data_Make_Struct (klass, Eet_File *, NULL, c_free, ef);
80 * Eet::File.open(file [, mode] ) -> ef or nil
81 * Eet::File.open(file [, mode] ) { |ef| block } -> nil
83 * If a block isn't specified, Eet::File.open is a synonym for
85 * If a block is given, it will be invoked with the
86 * Eet::File object as a parameter, and the file will be
87 * automatically closed when the block terminates. The call always
88 * returns +nil+ in this case.
91 c_open (int argc, VALUE *argv, VALUE klass)
93 VALUE obj = rb_class_new_instance (argc, argv, klass);
95 if (rb_block_given_p ())
96 return rb_ensure (rb_yield, obj, c_close, obj);
103 * Eet::File.new(file [, mode] ) -> ef or nil
105 * Creates an Eet::File object for _file_.
107 * _file_ is opened with the specified mode (defaulting to "r").
108 * Possible values for _mode_ are "r" for read-only access,
109 * "w" for write-only access and "r+" for read/write access.
112 c_init (int argc, VALUE *argv, VALUE self)
114 VALUE file = Qnil, mode = Qnil;
115 Eet_File **ef = NULL;
116 Eet_File_Mode m = EET_FILE_MODE_READ;
117 const char *tmp, *cfile;
119 Data_Get_Struct (self, Eet_File *, ef);
121 rb_scan_args (argc, argv, "11", &file, &mode);
123 cfile = StringValuePtr (file);
126 tmp = StringValuePtr (mode);
127 if (!strcmp (tmp, "r+"))
128 m = EET_FILE_MODE_READ_WRITE;
129 else if (!strcmp (tmp, "w"))
130 m = EET_FILE_MODE_WRITE;
131 else if (strcmp (tmp, "r"))
132 rb_raise (rb_eArgError, "illegal access mode %s", tmp);
137 *ef = eet_open (cfile, m);
140 case EET_FILE_MODE_READ_WRITE:
141 case EET_FILE_MODE_WRITE:
142 tmp = "Permission denied - %s";
145 tmp = "File not found - %s";
149 rb_raise (rb_eRuntimeError, tmp, cfile);
159 * Closes _ef_ and flushes any pending writes.
160 * _ef_ is unavailable for any further data operations;
161 * an +IOError+ is raised if such an attempt is made.
163 * Eet::File objects are automatically closed when they
164 * are claimed by the garbage collector.
169 Eet_File **ef = NULL;
171 Data_Get_Struct (self, Eet_File *, ef);
184 * ef.list([glob]) -> array
186 * Returns an Array of entries in _ef_ that match the shell glob
187 * _glob_ (defaulting to "*").
190 c_list (int argc, VALUE *argv, VALUE self)
192 VALUE glob = Qnil, ret;
193 Eet_File **ef = NULL;
194 char **entries, *tmp = "*";
197 Data_Get_Struct (self, Eet_File *, ef);
200 switch (eet_mode_get (*ef)) {
201 case EET_FILE_MODE_READ:
202 case EET_FILE_MODE_READ_WRITE:
205 rb_raise (rb_eIOError, "cannot list entries");
208 rb_scan_args (argc, argv, "01", &glob);
211 tmp = StringValuePtr (glob);
215 entries = eet_list (*ef, tmp, &count);
217 for (i = 0; i < count; i++)
218 rb_ary_push (ret, rb_str_new2 (entries[i]));
227 * ef.delete(key) -> ef
229 * Deletes the entry from _ef_ that is stored as _key_.
230 * If the entry cannot be deleted, an +IOError+ is raised,
231 * otherwise _ef_ is returned.
234 c_delete (VALUE self, VALUE key)
236 Eet_File **ef = NULL;
239 Data_Get_Struct (self, Eet_File *, ef);
242 ckey = StringValuePtr (key);
245 if (!eet_delete (*ef, ckey))
246 rb_raise (rb_eIOError, "cannot delete entry - %s", ckey);
253 * ef.read(key) -> string
255 * Reads an entry from _ef_ that is stored as _key_.
256 * If the data cannot be read, an +IOError+ is raised,
257 * otherwise a String is returned that contains the data.
260 c_read (VALUE self, VALUE key)
263 Eet_File **ef = NULL;
268 Data_Get_Struct (self, Eet_File *, ef);
271 ckey = StringValuePtr (key);
274 data = eet_read (*ef, ckey, &size);
276 rb_raise (rb_eIOError, "cannot read entry - %s", ckey);
278 ret = rb_str_new (data, size);
287 * ef.write(key, data [, compress] ) -> integer
289 * Stores _data_ in _ef_ as _key_.
290 * If _compress_ is true (which is the default), the data will be
292 * If the data cannot be written, an +IOError+ is raised,
293 * otherwise a the number of bytes written is returned.
296 c_write (int argc, VALUE *argv, VALUE self)
298 VALUE key = Qnil, buf = Qnil, comp = Qnil;
299 Eet_File **ef = NULL;
303 Data_Get_Struct (self, Eet_File *, ef);
306 rb_scan_args (argc, argv, "21", &key, &buf, &comp);
311 ckey = StringValuePtr (key);
313 cbuf = StringValuePtr (buf);
315 n = eet_write (*ef, ckey,
316 cbuf, RSTRING (buf)->len,
319 rb_raise (rb_eIOError, "couldn't write to file");
326 * ef.read_image(key) -> array
328 * Reads an image entry from _ef_ that is stored as _key_.
329 * If the data cannot be read, an +IOError+ is raised,
330 * otherwise an Array is returned that contains the image data,
331 * the image width, the image height, a boolean that indicates
332 * whether the image has an alpha channel or not and a hash
333 * that contains the compression options that were used to store
334 * the image (see Eet::File#write_image).
337 c_read_image (VALUE self, VALUE key)
340 Eet_File **ef = NULL;
343 int w = 0, h = 0, has_alpha = 0, level = 0, quality = 0, lossy = 0;
345 Data_Get_Struct (self, Eet_File *, ef);
348 ckey = StringValuePtr (key);
351 data = eet_data_image_read (*ef, ckey, &w, &h,
352 &has_alpha, &level, &quality,
355 rb_raise (rb_eIOError, "cannot read entry - %s", ckey);
357 comp = rb_hash_new ();
358 rb_hash_aset (comp, sym_lossy, INT2FIX (lossy));
359 rb_hash_aset (comp, sym_level, INT2FIX (level));
360 rb_hash_aset (comp, sym_quality, INT2FIX (quality));
362 ret = rb_ary_new3 (5, rb_str_new (data, w * h * 4),
363 INT2FIX (w), INT2FIX (h),
364 has_alpha ? Qtrue : Qfalse, comp);
372 * ef.write_image(key, image_data, w, h [, alpha] [, comp] ) -> integer
374 * Stores _image_data_ with width _w_ and height _h_ in _ef_ as _key_.
375 * Pass true for _alpha_ if the image contains an alpha channel.
376 * You can control how the image is compressed by passing _comp_, which
377 * is a hash whose :lossy entry is true if the image should be
378 * compressed lossily. If :lossy is true, the :quality entry
379 * (0-100, default 100) sets the compression quality.
380 * If :lossy is false, the :level entry (0-9, default 9) sets the
381 * compression level. If _comp_ isn't passed, then the
382 * image is stored losslessly.
383 * If the data cannot be written, an +IOError+ is raised,
384 * otherwise a the number of bytes written is returned.
387 c_write_image (int argc, VALUE *argv, VALUE self)
389 VALUE key = Qnil, buf = Qnil, w = Qnil, h = Qnil, has_alpha = Qnil;
390 VALUE comp = Qnil, tmp;
391 Eet_File **ef = NULL;
393 int n, lossy = 0, level = 9, quality = 100;
395 Data_Get_Struct (self, Eet_File *, ef);
398 rb_scan_args (argc, argv, "42", &key, &buf, &w, &h, &has_alpha,
401 if (NIL_P (has_alpha))
404 ckey = StringValuePtr (key);
406 cbuf = StringValuePtr (buf);
407 Check_Type (w, T_FIXNUM);
408 Check_Type (h, T_FIXNUM);
411 Check_Type (comp, T_HASH);
413 tmp = rb_hash_aref (comp, sym_lossy);
415 lossy = FIX2INT (tmp);
417 tmp = rb_hash_aref (comp, sym_level);
419 level = FIX2INT (tmp);
421 tmp = rb_hash_aref (comp, sym_quality);
423 quality = FIX2INT (tmp);
426 if (!RSTRING (buf)->len)
429 n = eet_data_image_write (*ef, ckey, cbuf,
430 FIX2INT (w), FIX2INT (h),
432 level, quality, lossy);
434 rb_raise (rb_eIOError, "couldn't write to file");
440 chunk_init (VALUE self, VALUE tag, VALUE data)
442 long tag_len, data_len, tmp;
447 if (rb_funcall (tag, id_include, 1, INT2FIX (0)) == Qtrue)
448 rb_raise (rb_eArgError, "tag must not contain binary zeroes");
450 /* libeet uses a signed 32bit integer to store the
451 * chunk size, so make sure we don't overflow it
453 tag_len = RSTRING (tag)->len;
454 data_len = RSTRING (data)->len;
455 tmp = tag_len + 1 + data_len;
457 if (tmp < tag_len || tmp < data_len || tmp < 1 || tmp >= 2147483647L)
458 rb_raise (rb_eArgError, "tag or data too long");
460 rb_ivar_set (self, id_tag, rb_str_dup_frozen (tag));
461 rb_ivar_set (self, id_data, rb_str_dup_frozen (data));
467 chunk_to_s (VALUE self)
470 unsigned int size, buf_len;
472 struct RString *tag, *data;
474 tmp = rb_ivar_get (self, id_tag);
477 tmp = rb_ivar_get (self, id_data);
478 data = RSTRING (tmp);
480 buf_len = 9 + tag->len + data->len;
481 ret = rb_str_buf_new (buf_len);
483 buf = RSTRING (ret)->ptr;
484 RSTRING (ret)->len = buf_len;
486 memcpy (buf, "CHnK", 4);
489 size = tag->len + data->len + 1;
490 size = BSWAP32 (size);
491 memcpy (buf, &size, 4);
494 memcpy (buf, tag->ptr, tag->len);
499 memcpy (buf, data->ptr, data->len);
505 for_each_prop (VALUE tag, VALUE arg, VALUE stream)
507 VALUE value, type, tmp;
509 if (rb_obj_is_kind_of (arg, rb_cArray) == Qfalse)
510 rb_raise (ePropError, "hash value is not an array");
512 value = rb_ary_entry (arg, 0);
516 type = rb_ary_entry (arg, 1);
517 tmp = rb_funcall (value, id_to_eet_chunks, 2, tag, type);
519 rb_ary_concat (stream, tmp);
526 * object.to_eet -> string
528 * Serializes the receiver to EET format.
531 c_to_eet (VALUE self)
533 VALUE props, name, stream, chunk, args[2];
534 #ifndef HAVE_RB_HASH_FOREACH
539 props = rb_funcall (self, id_to_eet_properties, 0);
541 if (rb_obj_is_kind_of (props, rb_cHash) == Qfalse ||
542 !RHASH (props)->tbl->num_entries)
543 rb_raise (ePropError, "invalid EET properties");
545 name = rb_funcall (self, id_to_eet_name, 0);
548 if (!RSTRING (name)->len ||
549 rb_funcall (name, id_include, 1, INT2FIX (0)))
550 rb_raise (eNameError, "invalid EET name");
552 stream = rb_class_new_instance (0, NULL, cStream);
554 #ifdef HAVE_RB_HASH_FOREACH
555 rb_hash_foreach (props, for_each_prop, stream);
557 keys = RARRAY (rb_funcall (props, id_keys, 0));
559 for (i = 0; i < keys->len; i++)
560 for_each_prop (keys->ptr[i],
561 rb_hash_aref (props, keys->ptr[i]),
566 args[1] = rb_ary_to_s (stream);
568 rb_ary_clear (stream); /* give the GC a hand... */
570 chunk = rb_class_new_instance (2, args, cChunk);
572 return rb_funcall (chunk, id_to_s, 0);
576 int_to_eet_chunks (int argc, VALUE *argv, VALUE self)
578 VALUE tag, type = Qnil, ary, args[2], chunk;
581 rb_scan_args (argc, argv, "11", &tag, &type);
583 ary = rb_ary_new3 (1, self);
585 if (type == sym_char)
587 else if (type == sym_short)
589 else if (type == sym_long_long)
593 args[1] = rb_funcall (ary, id_pack, 1, rb_str_new2 (cfmt));
594 chunk = rb_class_new_instance (2, args, cChunk);
596 return rb_ary_new3 (1, chunk);
600 float_to_eet_chunks (int argc, VALUE *argv, VALUE self)
602 VALUE tag, type = Qnil, args[2], chunk;
607 rb_scan_args (argc, argv, "11", &tag, &type);
611 /* switch locale to make sure we get proper snprintf output */
612 loc = setlocale (LC_NUMERIC, "C");
614 len = snprintf (buf, sizeof (buf) - 1, "%a",
615 type == sym_double ? d : (float) d);
618 setlocale (LC_NUMERIC, loc);
623 args[1] = rb_str_new (buf, len);
624 chunk = rb_class_new_instance (2, args, cChunk);
626 return rb_ary_new3 (1, chunk);
634 m = rb_define_module ("Eet");
636 c = rb_define_class_under (m, "File", rb_cObject);
637 rb_define_alloc_func (c, c_alloc);
638 rb_define_singleton_method (c, "open", c_open, -1);
639 rb_define_method (c, "initialize", c_init, -1);
640 rb_define_method (c, "close", c_close, 0);
641 rb_define_method (c, "list", c_list, -1);
642 rb_define_method (c, "delete", c_delete, 1);
643 rb_define_method (c, "read", c_read, 1);
644 rb_define_method (c, "write", c_write, -1);
645 rb_define_method (c, "read_image", c_read_image, 1);
646 rb_define_method (c, "write_image", c_write_image, -1);
648 cStream = rb_define_class_under (m, "Stream", rb_cArray);
650 cChunk = rb_define_class_under (m, "Chunk", rb_cObject);
651 rb_define_method (cChunk, "initialize", chunk_init, 2);
652 rb_define_method (cChunk, "to_s", chunk_to_s, 0);
654 rb_define_attr (cChunk, "tag", 1, 0);
655 rb_define_attr (cChunk, "data", 1, 0);
657 rb_define_method (rb_cObject, "to_eet", c_to_eet, 0);
659 rb_define_method (rb_cInteger, "to_eet_chunks", int_to_eet_chunks, -1);
660 rb_define_method (rb_cFloat, "to_eet_chunks", float_to_eet_chunks, -1);
662 eEetError = rb_define_class_under (m, "EetError", rb_eStandardError);
663 eNameError = rb_define_class_under (m, "NameError", eEetError);
664 ePropError = rb_define_class_under (m, "PropertyError", eEetError);
666 id_include = rb_intern ("include?");
667 id_to_s = rb_intern ("to_s");
668 id_keys = rb_intern ("keys");
669 id_pack = rb_intern ("pack");
670 id_to_eet_chunks = rb_intern ("to_eet_chunks");
671 id_to_eet_name = rb_intern ("to_eet_name");
672 id_to_eet_properties = rb_intern ("to_eet_properties");
673 id_tag = rb_intern ("@tag");
674 id_data = rb_intern ("@data");
675 sym_lossy = ID2SYM (rb_intern ("lossy"));
676 sym_level = ID2SYM (rb_intern ("level"));
677 sym_quality = ID2SYM (rb_intern ("quality"));
678 sym_char = ID2SYM (rb_intern ("char"));
679 sym_short = ID2SYM (rb_intern ("short"));
680 sym_long_long = ID2SYM (rb_intern ("long_long"));
681 sym_double = ID2SYM (rb_intern ("double"));