Permalink
Browse files

implement Enumerator#inspect

  • Loading branch information...
1 parent de68086 commit 1f07e4b43661a361a4bfd88901051696fda88298 @Watson1978 Watson1978 committed Dec 28, 2011
Showing with 71 additions and 0 deletions.
  1. +71 −0 enumerator.c
View
@@ -470,6 +470,76 @@ enumerator_rewind(VALUE obj, SEL sel)
return obj;
}
+static VALUE
+inspect_enumerator(VALUE obj, VALUE dummy, int recur)
+{
+ struct enumerator *e;
+ const char *cname;
+ VALUE eobj, str;
+ int tainted, untrusted;
+
+ Data_Get_Struct(obj, struct enumerator, e);
+
+ cname = rb_obj_classname(obj);
+
+ if (!e || e->obj == Qundef) {
+ return rb_sprintf("#<%s: uninitialized>", cname);
+ }
+
+ if (recur) {
+ str = rb_sprintf("#<%s: ...>", cname);
+ OBJ_TAINT(str);
+ return str;
+ }
+
+ eobj = e->obj;
+
+ tainted = OBJ_TAINTED(eobj);
+ untrusted = OBJ_UNTRUSTED(eobj);
+
+ /* (1..100).each_cons(2) => "#<Enumerator: 1..100:each_cons(2)>" */
+ str = rb_sprintf("#<%s: ", cname);
+ rb_str_concat(str, rb_inspect(eobj));
+ rb_str_buf_cat2(str, ":");
+ rb_str_buf_cat2(str, sel_getName(e->sel));
+
+ if (e->args) {
+ long argc = RARRAY_LEN(e->args);
+ VALUE *argv = (VALUE*)RARRAY_PTR(e->args);
+
+ rb_str_buf_cat2(str, "(");
+
+ while (argc--) {
+ VALUE arg = *argv++;
+
+ rb_str_concat(str, rb_inspect(arg));
+ rb_str_buf_cat2(str, argc > 0 ? ", " : ")");
+
+ if (OBJ_TAINTED(arg)) tainted = TRUE;
+ if (OBJ_UNTRUSTED(arg)) untrusted = TRUE;
+ }
+ }
+
+ rb_str_buf_cat2(str, ">");
+
+ if (tainted) OBJ_TAINT(str);
+ if (untrusted) OBJ_UNTRUST(str);
+ return str;
+}
+
+/*
+ * call-seq:
+ * e.inspect -> string
+ *
+ * Create a printable version of <i>e</i>.
+ */
+
+static VALUE
+enumerator_inspect(VALUE obj, SEL sel)
+{
+ return rb_exec_recursive(inspect_enumerator, obj, 0);
+}
+
void
Init_Enumerator(void)
{
@@ -489,6 +559,7 @@ Init_Enumerator(void)
rb_objc_define_method(rb_cEnumerator, "with_object", enumerator_with_object, 1);
rb_objc_define_method(rb_cEnumerator, "next", enumerator_next, 0);
rb_objc_define_method(rb_cEnumerator, "rewind", enumerator_rewind, 0);
+ rb_objc_define_method(rb_cEnumerator, "inspect", enumerator_inspect, 0);
rb_eStopIteration = rb_define_class("StopIteration", rb_eIndexError);

0 comments on commit 1f07e4b

Please sign in to comment.