2 * $Id: ext.c 62 2005-06-09 17:42:34Z 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, eStreamError,
52 sym_lossy, sym_level, sym_quality, sym_char, sym_short,
53 sym_long_long, sym_double;
54 static ID id_include, id_serialize, id_push, id_keys,
55 id_to_eet_chunks, id_to_eet_name, id_to_eet_properties,
59 c_free (Eet_File **ef)
76 return Data_Make_Struct (klass, Eet_File *, NULL, c_free, ef);
81 * Eet::File.open(file [, mode] ) -> ef or nil
82 * Eet::File.open(file [, mode] ) { |ef| block } -> nil
84 * If a block isn't specified, Eet::File.open is a synonym for
86 * If a block is given, it will be invoked with the
87 * Eet::File object as a parameter, and the file will be
88 * automatically closed when the block terminates. The call always
89 * returns +nil+ in this case.
92 c_open (int argc, VALUE *argv, VALUE klass)
94 VALUE obj = rb_class_new_instance (argc, argv, klass);
96 if (rb_block_given_p ())
97 return rb_ensure (rb_yield, obj, c_close, obj);
104 * Eet::File.new(file [, mode] ) -> ef or nil
106 * Creates an Eet::File object for _file_.
108 * _file_ is opened with the specified mode (defaulting to "r").
109 * Possible values for _mode_ are "r" for read-only access,
110 * "w" for write-only access and "r+" for read/write access.
113 c_init (int argc, VALUE *argv, VALUE self)
115 VALUE file = Qnil, mode = Qnil;
116 Eet_File **ef = NULL;
117 Eet_File_Mode m = EET_FILE_MODE_READ;
118 const char *tmp, *cfile;
120 Data_Get_Struct (self, Eet_File *, ef);
122 rb_scan_args (argc, argv, "11", &file, &mode);
124 cfile = StringValuePtr (file);
127 tmp = StringValuePtr (mode);
128 if (!strcmp (tmp, "r+"))
129 m = EET_FILE_MODE_READ_WRITE;
130 else if (!strcmp (tmp, "w"))
131 m = EET_FILE_MODE_WRITE;
132 else if (strcmp (tmp, "r"))
133 rb_raise (rb_eArgError, "illegal access mode %s", tmp);
138 *ef = eet_open (cfile, m);
141 case EET_FILE_MODE_READ_WRITE:
142 case EET_FILE_MODE_WRITE:
143 tmp = "Permission denied - %s";
146 tmp = "File not found - %s";
150 rb_raise (rb_eRuntimeError, tmp, cfile);
160 * Closes _ef_ and flushes any pending writes.
161 * _ef_ is unavailable for any further data operations;
162 * an +IOError+ is raised if such an attempt is made.
164 * Eet::File objects are automatically closed when they
165 * are claimed by the garbage collector.
170 Eet_File **ef = NULL;
172 Data_Get_Struct (self, Eet_File *, ef);
185 * ef.list([glob]) -> array
187 * Returns an Array of entries in _ef_ that match the shell glob
188 * _glob_ (defaulting to "*").
191 c_list (int argc, VALUE *argv, VALUE self)
193 VALUE glob = Qnil, ret;
194 Eet_File **ef = NULL;
195 char **entries, *tmp = "*";
198 Data_Get_Struct (self, Eet_File *, ef);
201 switch (eet_mode_get (*ef)) {
202 case EET_FILE_MODE_READ:
203 case EET_FILE_MODE_READ_WRITE:
206 rb_raise (rb_eIOError, "cannot list entries");
209 rb_scan_args (argc, argv, "01", &glob);
212 tmp = StringValuePtr (glob);
216 entries = eet_list (*ef, tmp, &count);
218 for (i = 0; i < count; i++)
219 rb_ary_push (ret, rb_str_new2 (entries[i]));
228 * ef.delete(key) -> ef
230 * Deletes the entry from _ef_ that is stored as _key_.
231 * If the entry cannot be deleted, an +IOError+ is raised,
232 * otherwise _ef_ is returned.
235 c_delete (VALUE self, VALUE key)
237 Eet_File **ef = NULL;
240 Data_Get_Struct (self, Eet_File *, ef);
243 ckey = StringValuePtr (key);
246 if (!eet_delete (*ef, ckey))
247 rb_raise (rb_eIOError, "cannot delete entry - %s", ckey);
254 * ef.read(key) -> string
256 * Reads an entry from _ef_ that is stored as _key_.
257 * If the data cannot be read, an +IOError+ is raised,
258 * otherwise a String is returned that contains the data.
261 c_read (VALUE self, VALUE key)
264 Eet_File **ef = NULL;
269 Data_Get_Struct (self, Eet_File *, ef);
272 ckey = StringValuePtr (key);
275 data = eet_read (*ef, ckey, &size);
277 rb_raise (rb_eIOError, "cannot read entry - %s", ckey);
279 ret = rb_str_new (data, size);
288 * ef.write(key, data [, compress] ) -> integer
290 * Stores _data_ in _ef_ as _key_.
291 * If _compress_ is true (which is the default), the data will be
293 * If the data cannot be written, an +IOError+ is raised,
294 * otherwise a the number of bytes written is returned.
297 c_write (int argc, VALUE *argv, VALUE self)
299 VALUE key = Qnil, buf = Qnil, comp = Qnil;
300 Eet_File **ef = NULL;
304 Data_Get_Struct (self, Eet_File *, ef);
307 rb_scan_args (argc, argv, "21", &key, &buf, &comp);
312 ckey = StringValuePtr (key);
314 cbuf = StringValuePtr (buf);
316 n = eet_write (*ef, ckey,
317 cbuf, RSTRING (buf)->len,
320 rb_raise (rb_eIOError, "couldn't write to file");
327 * ef.read_image(key) -> array
329 * Reads an image entry from _ef_ that is stored as _key_.
330 * If the data cannot be read, an +IOError+ is raised,
331 * otherwise an Array is returned that contains the image data,
332 * the image width, the image height, a boolean that indicates
333 * whether the image has an alpha channel or not and a hash
334 * that contains the compression options that were used to store
335 * the image (see Eet::File#write_image).
338 c_read_image (VALUE self, VALUE key)
341 Eet_File **ef = NULL;
344 int w = 0, h = 0, has_alpha = 0, level = 0, quality = 0, lossy = 0;
346 Data_Get_Struct (self, Eet_File *, ef);
349 ckey = StringValuePtr (key);
352 data = eet_data_image_read (*ef, ckey, &w, &h,
353 &has_alpha, &level, &quality,
356 rb_raise (rb_eIOError, "cannot read entry - %s", ckey);
358 comp = rb_hash_new ();
359 rb_hash_aset (comp, sym_lossy, INT2FIX (lossy));
360 rb_hash_aset (comp, sym_level, INT2FIX (level));
361 rb_hash_aset (comp, sym_quality, INT2FIX (quality));
363 ret = rb_ary_new3 (5, rb_str_new (data, w * h * 4),
364 INT2FIX (w), INT2FIX (h),
365 has_alpha ? Qtrue : Qfalse, comp);
373 * ef.write_image(key, image_data, w, h [, alpha] [, comp] ) -> integer
375 * Stores _image_data_ with width _w_ and height _h_ in _ef_ as _key_.
376 * Pass true for _alpha_ if the image contains an alpha channel.
377 * You can control how the image is compressed by passing _comp_, which
378 * is a hash whose :lossy entry is true if the image should be
379 * compressed lossily. If :lossy is true, the :quality entry
380 * (0-100, default 100) sets the compression quality.
381 * If :lossy is false, the :level entry (0-9, default 9) sets the
382 * compression level. If _comp_ isn't passed, then the
383 * image is stored losslessly.
384 * If the data cannot be written, an +IOError+ is raised,
385 * otherwise a the number of bytes written is returned.
388 c_write_image (int argc, VALUE *argv, VALUE self)
390 VALUE key = Qnil, buf = Qnil, w = Qnil, h = Qnil, has_alpha = Qnil;
391 VALUE comp = Qnil, tmp;
392 Eet_File **ef = NULL;
394 int n, lossy = 0, level = 9, quality = 100;
396 Data_Get_Struct (self, Eet_File *, ef);
399 rb_scan_args (argc, argv, "42", &key, &buf, &w, &h, &has_alpha,
402 if (NIL_P (has_alpha))
405 ckey = StringValuePtr (key);
407 cbuf = StringValuePtr (buf);
408 Check_Type (w, T_FIXNUM);
409 Check_Type (h, T_FIXNUM);
412 Check_Type (comp, T_HASH);
414 tmp = rb_hash_aref (comp, sym_lossy);
416 lossy = FIX2INT (tmp);
418 tmp = rb_hash_aref (comp, sym_level);
420 level = FIX2INT (tmp);
422 tmp = rb_hash_aref (comp, sym_quality);
424 quality = FIX2INT (tmp);
427 if (!RSTRING (buf)->len)
430 n = eet_data_image_write (*ef, ckey, cbuf,
431 FIX2INT (w), FIX2INT (h),
433 level, quality, lossy);
435 rb_raise (rb_eIOError, "couldn't write to file");
441 stream_serialize (VALUE self)
444 struct RArray *stream;
447 ret = rb_str_new2 ("");
449 stream = RARRAY (self);
453 for (i = 0; i < stream->len; i++) {
456 if (rb_obj_is_kind_of (stream->ptr[i], cChunk) == Qfalse)
457 rb_raise (eBadElementError, "stream member is not a Chunk");
459 str = rb_funcall (stream->ptr[i], id_serialize, 0, NULL);
461 rb_str_append (ret, str);
468 chunk_init (VALUE self, VALUE tag, VALUE data)
475 if (rb_funcall (tag, id_include, 1, INT2FIX (0)) == Qtrue) \
476 rb_raise (rb_eArgError, "tag must not contain binary zeroes");
478 /* libeet uses a signed 32bit integer to store the
479 * chunk size, so make sure we don't overflow it
481 len = RSTRING (tag)->len + 1 + RSTRING (data)->len;
482 if (len < 0 || len >= 2147483647L)
483 rb_raise (rb_eArgError, "tag or data too long");
485 rb_ivar_set (self, id_tag, rb_str_dup_frozen (tag));
486 rb_ivar_set (self, id_data, rb_str_dup_frozen (data));
492 chunk_serialize (VALUE self)
495 unsigned int size, buf_len;
497 struct RString *tag, *data;
499 tmp = rb_ivar_get (self, id_tag);
503 tmp = rb_ivar_get (self, id_data);
505 data = RSTRING (tmp);
507 buf_len = 9 + tag->len + data->len;
508 ret = rb_str_buf_new (buf_len);
510 buf = RSTRING (ret)->ptr;
511 RSTRING (ret)->len = buf_len;
513 memcpy (buf, "CHnK", 4);
516 size = tag->len + data->len + 1;
517 size = BSWAP32 (size);
518 memcpy (buf, &size, 4);
521 memcpy (buf, tag->ptr, tag->len);
526 memcpy (buf, data->ptr, data->len);
532 for_each_prop (VALUE tag, VALUE arg, VALUE stream)
534 VALUE value, type, chunks;
537 if (rb_obj_is_kind_of (arg, rb_cArray) == Qfalse)
538 rb_raise (ePropError, "hash value is not an array");
540 value = rb_ary_entry (arg, 0);
544 type = rb_ary_entry (arg, 1);
545 chunks = rb_funcall (value, id_to_eet_chunks, 2, tag, type);
547 len = RARRAY (chunks)->len;
549 for (i = 0; i < len; i++)
550 rb_funcall (stream, id_push, 1, rb_ary_entry (chunks, i));
557 * object.to_eet -> string
559 * Serializes the receiver to EET format.
562 c_to_eet (VALUE self)
564 VALUE props, name, stream, chunk, args[2];
565 #ifndef HAVE_RB_HASH_FOREACH
570 props = rb_funcall (self, id_to_eet_properties, 0);
572 if (rb_obj_is_kind_of (props, rb_cHash) == Qfalse ||
573 !RHASH (props)->tbl->num_entries)
574 rb_raise (ePropError, "invalid EET properties");
576 name = rb_funcall (self, id_to_eet_name, 0);
579 if (!RSTRING (name)->len ||
580 rb_funcall (name, id_include, 1, INT2FIX (0)))
581 rb_raise (eNameError, "invalid EET name");
583 stream = rb_class_new_instance (0, NULL, cStream);
585 #ifdef HAVE_RB_HASH_FOREACH
586 rb_hash_foreach (props, for_each_prop, stream);
588 keys = RARRAY (rb_funcall (props, id_keys, 0));
590 for (i = 0; i < keys->len; i++)
591 for_each_prop (keys->ptr[i],
592 rb_hash_aref (props, keys->ptr[i]),
597 args[1] = rb_funcall (stream, id_serialize, 0);
598 chunk = rb_class_new_instance (2, args, cChunk);
600 return rb_funcall (chunk, id_serialize, 0);
604 int_to_eet_chunks (int argc, VALUE *argv, VALUE self)
606 VALUE tag, type = Qnil, ary, args[2], chunk;
609 rb_scan_args (argc, argv, "11", &tag, &type);
611 ary = rb_ary_new3 (1, self);
613 if (type == sym_char)
615 else if (type == sym_short)
617 else if (type == sym_long_long)
621 args[1] = rb_funcall (ary, rb_intern ("pack"), 1, rb_str_new2 (cfmt));
622 chunk = rb_class_new_instance (2, args, cChunk);
624 return rb_ary_new3 (1, chunk);
628 float_to_eet_chunks (int argc, VALUE *argv, VALUE self)
630 VALUE tag, type = Qnil, args[2], chunk;
635 rb_scan_args (argc, argv, "11", &tag, &type);
639 /* switch locale to make sure we get proper snprintf output */
640 loc = setlocale (LC_NUMERIC, "C");
642 len = snprintf (buf, sizeof (buf) - 1, "%a",
643 type == sym_double ? d : (float) d);
646 setlocale (LC_NUMERIC, loc);
651 args[1] = rb_str_new (buf, len);
652 chunk = rb_class_new_instance (2, args, cChunk);
654 return rb_ary_new3 (1, chunk);
662 m = rb_define_module ("Eet");
664 c = rb_define_class_under (m, "File", rb_cObject);
665 rb_define_alloc_func (c, c_alloc);
666 rb_define_singleton_method (c, "open", c_open, -1);
667 rb_define_method (c, "initialize", c_init, -1);
668 rb_define_method (c, "close", c_close, 0);
669 rb_define_method (c, "list", c_list, -1);
670 rb_define_method (c, "delete", c_delete, 1);
671 rb_define_method (c, "read", c_read, 1);
672 rb_define_method (c, "write", c_write, -1);
673 rb_define_method (c, "read_image", c_read_image, 1);
674 rb_define_method (c, "write_image", c_write_image, -1);
676 cStream = rb_define_class_under (m, "Stream", rb_cArray);
677 rb_define_method (cStream, "serialize", stream_serialize, 0);
679 cChunk = rb_define_class_under (m, "Chunk", rb_cObject);
680 rb_define_method (cChunk, "initialize", chunk_init, 2);
681 rb_define_method (cChunk, "serialize", chunk_serialize, 0);
683 rb_define_attr (cChunk, "tag", 1, 0);
684 rb_define_attr (cChunk, "data", 1, 0);
686 rb_define_method (rb_cObject, "to_eet", c_to_eet, 0);
688 rb_define_method (rb_cInteger, "to_eet_chunks", int_to_eet_chunks, -1);
689 rb_define_method (rb_cFloat, "to_eet_chunks", float_to_eet_chunks, -1);
691 eEetError = rb_define_class_under (m, "EetError", rb_eStandardError);
692 eNameError = rb_define_class_under (m, "NameError", eEetError);
693 ePropError = rb_define_class_under (m, "PropertyError", eEetError);
694 eStreamError = rb_define_class_under (m, "StreamError", eEetError);
695 eBadElementError = rb_define_class_under (m, "BadElementError",
698 id_include = rb_intern ("include?");
699 id_serialize = rb_intern ("serialize");
700 id_push = rb_intern ("push");
701 id_keys = rb_intern ("keys");
702 id_to_eet_chunks = rb_intern ("to_eet_chunks");
703 id_to_eet_name = rb_intern ("to_eet_name");
704 id_to_eet_properties = rb_intern ("to_eet_properties");
705 id_tag = rb_intern ("@tag");
706 id_data = rb_intern ("@data");
707 sym_lossy = ID2SYM (rb_intern ("lossy"));
708 sym_level = ID2SYM (rb_intern ("level"));
709 sym_quality = ID2SYM (rb_intern ("quality"));
710 sym_char = ID2SYM (rb_intern ("char"));
711 sym_short = ID2SYM (rb_intern ("short"));
712 sym_long_long = ID2SYM (rb_intern ("long_long"));
713 sym_double = ID2SYM (rb_intern ("double"));