diff options
Diffstat (limited to 'mrbgems')
35 files changed, 2798 insertions, 101 deletions
diff --git a/mrbgems/mruby-array-ext/mrbgem.rake b/mrbgems/mruby-array-ext/mrbgem.rake new file mode 100644 index 000000000..38e0ad267 --- /dev/null +++ b/mrbgems/mruby-array-ext/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-array-ext') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb new file mode 100644 index 000000000..b3ff9bfca --- /dev/null +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -0,0 +1,98 @@ +class Array + def uniq! + ary = self.dup + result = [] + while ary.size > 0 + result << ary.shift + ary.delete(result.last) + end + if result.size == self.size + nil + else + self.replace(result) + end + end + + def uniq + ary = self.dup + ary.uniq! + ary + end + + def -(elem) + raise TypeError, "can't convert to Array" unless elem.class == Array + + hash = {} + array = [] + elem.each { |x| hash[x] = true } + self.each { |x| array << x unless hash[x] } + array + end + + def |(elem) + raise TypeError, "can't convert to Array" unless elem.class == Array + + ary = self + elem + ary.uniq! or ary + end + + def &(elem) + raise TypeError, "can't convert to Array" unless elem.class == Array + + hash = {} + array = [] + elem.each{|v| hash[v] = true } + self.each do |v| + if hash[v] + array << v + hash.delete v + end + end + array + end + + def flatten(depth=nil) + ar = [] + self.each do |e| + if e.is_a?(Array) && (depth.nil? || depth > 0) + ar += e.flatten(depth.nil? ? nil : depth - 1) + else + ar << e + end + end + ar + end + + def flatten!(depth=nil) + modified = false + ar = [] + self.each do |e| + if e.is_a?(Array) && (depth.nil? || depth > 0) + ar += e.flatten(depth.nil? ? nil : depth - 1) + modified = true + else + ar << e + end + end + if modified + self.replace(ar) + else + nil + end + end + + def compact + result = self.dup + result.compact! + result + end + + def compact! + result = self.select { |e| e != nil } + if result.size == self.size + nil + else + self.replace(result) + end + end +end diff --git a/mrbgems/mruby-array-ext/src/array.c b/mrbgems/mruby-array-ext/src/array.c new file mode 100644 index 000000000..7d7425efd --- /dev/null +++ b/mrbgems/mruby-array-ext/src/array.c @@ -0,0 +1,140 @@ +#include "mruby.h" +#include "mruby/value.h" +#include "mruby/array.h" + +/* + * call-seq: + * Array.try_convert(obj) -> array or nil + * + * Try to convert <i>obj</i> into an array, using +to_ary+ method. + * Returns converted array or +nil+ if <i>obj</i> cannot be converted + * for any reason. This method can be used to check if an argument is an + * array. + * + * Array.try_convert([1]) #=> [1] + * Array.try_convert("1") #=> nil + * + * if tmp = Array.try_convert(arg) + * # the argument is an array + * elsif tmp = String.try_convert(arg) + * # the argument is a string + * end + * + */ + +static mrb_value +mrb_ary_s_try_convert(mrb_state *mrb, mrb_value self) +{ + mrb_value ary; + + mrb_get_args(mrb, "o", &ary); + return mrb_check_array_type(mrb, ary); +} + +/* + * call-seq: + * ary.assoc(obj) -> new_ary or nil + * + * Searches through an array whose elements are also arrays + * comparing _obj_ with the first element of each contained array + * using obj.==. + * Returns the first contained array that matches (that + * is, the first associated array), + * or +nil+ if no match is found. + * See also <code>Array#rassoc</code>. + * + * s1 = [ "colors", "red", "blue", "green" ] + * s2 = [ "letters", "a", "b", "c" ] + * s3 = "foo" + * a = [ s1, s2, s3 ] + * a.assoc("letters") #=> [ "letters", "a", "b", "c" ] + * a.assoc("foo") #=> nil + */ + +static mrb_value +mrb_ary_assoc(mrb_state *mrb, mrb_value ary) +{ + mrb_int i; + mrb_value v, k; + + mrb_get_args(mrb, "o", &k); + + for (i = 0; i < RARRAY_LEN(ary); ++i) { + v = mrb_check_array_type(mrb, RARRAY_PTR(ary)[i]); + if (!mrb_nil_p(v) && RARRAY_LEN(v) > 0 && + mrb_equal(mrb, RARRAY_PTR(v)[0], k)) + return v; + } + return mrb_nil_value(); +} + +/* + * call-seq: + * ary.rassoc(obj) -> new_ary or nil + * + * Searches through the array whose elements are also arrays. Compares + * _obj_ with the second element of each contained array using + * <code>==</code>. Returns the first contained array that matches. See + * also <code>Array#assoc</code>. + * + * a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ] + * a.rassoc("two") #=> [2, "two"] + * a.rassoc("four") #=> nil + */ + +static mrb_value +mrb_ary_rassoc(mrb_state *mrb, mrb_value ary) +{ + mrb_int i; + mrb_value v, value; + + mrb_get_args(mrb, "o", &value); + + for (i = 0; i < RARRAY_LEN(ary); ++i) { + v = RARRAY_PTR(ary)[i]; + if (mrb_type(v) == MRB_TT_ARRAY && + RARRAY_LEN(v) > 1 && + mrb_equal(mrb, RARRAY_PTR(v)[1], value)) + return v; + } + return mrb_nil_value(); +} + +/* + * call-seq: + * ary.at(index) -> obj or nil + * + * Returns the element at _index_. A + * negative index counts from the end of +self+. Returns +nil+ + * if the index is out of range. See also <code>Array#[]</code>. + * + * a = [ "a", "b", "c", "d", "e" ] + * a.at(0) #=> "a" + * a.at(-1) #=> "e" + */ + +static mrb_value +mrb_ary_at(mrb_state *mrb, mrb_value ary) +{ + mrb_int pos; + mrb_get_args(mrb, "i", &pos); + + return mrb_ary_entry(ary, pos); +} + +void +mrb_mruby_array_ext_gem_init(mrb_state* mrb) +{ + struct RClass * a = mrb->array_class; + + mrb_define_class_method(mrb, a, "try_convert", mrb_ary_s_try_convert, ARGS_REQ(1)); + + mrb_define_method(mrb, a, "assoc", mrb_ary_assoc, ARGS_REQ(1)); + mrb_define_method(mrb, a, "at", mrb_ary_at, ARGS_REQ(1)); + mrb_define_method(mrb, a, "rassoc", mrb_ary_rassoc, ARGS_REQ(1)); +} + +void +mrb_mruby_array_ext_gem_final(mrb_state* mrb) +{ +} diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb new file mode 100644 index 000000000..1c441cec4 --- /dev/null +++ b/mrbgems/mruby-array-ext/test/array.rb @@ -0,0 +1,109 @@ +## +# Array(Ext) Test + +assert("Array::try_convert") do + Array.try_convert([1]) == [1] and + Array.try_convert("1").nil? +end + +assert("Array#assoc") do + s1 = [ "colors", "red", "blue", "green" ] + s2 = [ "letters", "a", "b", "c" ] + s3 = "foo" + a = [ s1, s2, s3 ] + + a.assoc("letters") == [ "letters", "a", "b", "c" ] and + a.assoc("foo").nil? +end + +assert("Array#at") do + a = [ "a", "b", "c", "d", "e" ] + a.at(0) == "a" and a.at(-1) == "e" +end + +assert("Array#rassoc") do + a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ] + + a.rassoc("two") == [2, "two"] and + a.rassoc("four").nil? +end + +assert("Array#uniq!") do + a = [1, 2, 3, 1] + a.uniq! + a == [1, 2, 3] +end + +assert("Array#uniq") do + a = [1, 2, 3, 1] + a.uniq == [1, 2, 3] && a == [1, 2, 3, 1] +end + +assert("Array#-") do + a = [1, 2, 3, 1] + b = [1] + c = 1 + e1 = nil + + begin + a - c + rescue => e1 + end + + (a - b) == [2, 3] and e1.class == TypeError and a == [1, 2, 3, 1] +end + +assert("Array#|") do + a = [1, 2, 3, 1] + b = [1, 4] + c = 1 + e1 = nil + + begin + a | c + rescue => e1 + end + + (a | b) == [1, 2, 3, 4] and e1.class == TypeError and a == [1, 2, 3, 1] +end + +assert("Array#&") do + a = [1, 2, 3, 1] + b = [1, 4] + c = 1 + e1 = nil + + begin + a & c + rescue => e1 + end + + (a & b) == [1] and e1.class == TypeError and a == [1, 2, 3, 1] +end + +assert("Array#flatten") do + [1, 2, "3", {4=>5}, :'6'] == [1, 2, "3", {4=>5}, :'6'].flatten and + [1, 2, 3, 4, 5, 6] == [1, 2, [3, 4, 5], 6].flatten and + [1, 2, 3, 4, 5, 6] == [1, 2, [3, [4, 5], 6]].flatten and + [1, [2, [3, [4, [5, [6]]]]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(0) and + [1, 2, [3, [4, [5, [6]]]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(1) and + [1, 2, 3, [4, [5, [6]]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(2) and + [1, 2, 3, 4, [5, [6]]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(3) and + [1, 2, 3, 4, 5, [6]] == [1, [2, [3, [4, [5, [6]]]]]].flatten(4) and + [1, 2, 3, 4, 5, 6] == [1, [2, [3, [4, [5, [6]]]]]].flatten(5) +end + +assert("Array#flatten!") do + [1, 2, 3, 4, 5, 6] == [1, 2, [3, [4, 5], 6]].flatten! +end + +assert("Array#compact") do + a = [1, nil, "2", nil, :t, false, nil] + a.compact == [1, "2", :t, false] && a == [1, nil, "2", nil, :t, false, nil] +end + +assert("Array#compact!") do + a = [1, nil, "2", nil, :t, false, nil] + a.compact! + a == [1, "2", :t, false] +end diff --git a/mrbgems/mruby-enum-ext/mrbgem.rake b/mrbgems/mruby-enum-ext/mrbgem.rake new file mode 100644 index 000000000..758d298dc --- /dev/null +++ b/mrbgems/mruby-enum-ext/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-enum-ext') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb new file mode 100644 index 000000000..f250d39f1 --- /dev/null +++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb @@ -0,0 +1,164 @@ +## +# Enumerable +# +module Enumerable + ## + # call-seq: + # enum.drop(n) -> array + # + # Drops first n elements from <i>enum</i>, and returns rest elements + # in an array. + # + # a = [1, 2, 3, 4, 5, 0] + # a.drop(3) #=> [4, 5, 0] + + def drop(n) + raise TypeError, "expected Integer for 1st argument" unless n.kind_of? Integer + raise ArgumentError, "attempt to drop negative size" if n < 0 + + ary = [] + self.each {|e| n == 0 ? ary << e : n -= 1 } + ary + end + + ## + # call-seq: + # enum.drop_while {|arr| block } -> array + # + # Drops elements up to, but not including, the first element for + # which the block returns +nil+ or +false+ and returns an array + # containing the remaining elements. + # + # a = [1, 2, 3, 4, 5, 0] + # a.drop_while {|i| i < 3 } #=> [3, 4, 5, 0] + + def drop_while(&block) + ary, state = [], false + self.each do |e| + state = true if !state and !block.call(e) + ary << e if state + end + ary + end + + ## + # call-seq: + # enum.take(n) -> array + # + # Returns first n elements from <i>enum</i>. + # + # a = [1, 2, 3, 4, 5, 0] + # a.take(3) #=> [1, 2, 3] + + def take(n) + raise TypeError, "expected Integer for 1st argument" unless n.kind_of? Integer + raise ArgumentError, "attempt to take negative size" if n < 0 + + ary = [] + self.each do |e| + break if ary.size >= n + ary << e + end + ary + end + + ## + # call-seq: + # enum.take_while {|arr| block } -> array + # + # Passes elements to the block until the block returns +nil+ or +false+, + # then stops iterating and returns an array of all prior elements. + # + # + # a = [1, 2, 3, 4, 5, 0] + # a.take_while {|i| i < 3 } #=> [1, 2] + + def take_while(&block) + ary = [] + self.each do |e| + return ary unless block.call(e) + ary << e + end + ary + end + + ## + # call-seq: + # enum.each_cons(n) {...} -> nil + # + # Iterates the given block for each array of consecutive <n> + # elements. + # + # e.g.: + # (1..10).each_cons(3) {|a| p a} + # # outputs below + # [1, 2, 3] + # [2, 3, 4] + # [3, 4, 5] + # [4, 5, 6] + # [5, 6, 7] + # [6, 7, 8] + # [7, 8, 9] + # [8, 9, 10] + + def each_cons(n, &block) + raise TypeError, "expected Integer for 1st argument" unless n.kind_of? Integer + raise ArgumentError, "invalid size" if n <= 0 + + ary = [] + self.each do |e| + ary.shift if ary.size == n + ary << e + block.call(ary.dup) if ary.size == n + end + end + + ## + # call-seq: + # enum.each_slice(n) {...} -> nil + # + # Iterates the given block for each slice of <n> elements. + # + # e.g.: + # (1..10).each_slice(3) {|a| p a} + # # outputs below + # [1, 2, 3] + # [4, 5, 6] + # [7, 8, 9] + # [10] + + def each_slice(n, &block) + raise TypeError, "expected Integer for 1st argument" unless n.kind_of? Integer + raise ArgumentError, "invalid slice size" if n <= 0 + + ary = [] + self.each do |e| + ary << e + if ary.size == n + block.call(ary) + ary = [] + end + end + block.call(ary) unless ary.empty? + end + + ## + # call-seq: + # enum.group_by {| obj | block } -> a_hash + # + # Returns a hash, which keys are evaluated result from the + # block, and values are arrays of elements in <i>enum</i> + # corresponding to the key. + # + # (1..6).group_by {|i| i%3} #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]} + + def group_by(&block) + h = {} + self.each do |e| + key = block.call(e) + h.key?(key) ? (h[key] << e) : (h[key] = [e]) + end + h + end + +end diff --git a/mrbgems/mruby-enum-ext/test/enum.rb b/mrbgems/mruby-enum-ext/test/enum.rb new file mode 100644 index 000000000..aa56cdf84 --- /dev/null +++ b/mrbgems/mruby-enum-ext/test/enum.rb @@ -0,0 +1,44 @@ +## +# Enumerable(Ext) Test + +assert("Enumerable#drop") do + a = [1, 2, 3, 4, 5, 0] + + assert_equal a.drop(3), [4, 5, 0] + assert_equal a.drop(6), [] +end + +assert("Enumerable#drop_while") do + a = [1, 2, 3, 4, 5, 0] + assert_equal a.drop_while {|i| i < 3 }, [3, 4, 5, 0] +end + +assert("Enumerable#take") do + a = [1, 2, 3, 4, 5, 0] + assert_equal a.take(3), [1, 2, 3] +end + +assert("Enumerable#take_while") do + a = [1, 2, 3, 4, 5, 0] + assert_equal a.take_while {|i| i < 3 }, [1, 2] +end + +assert("Enumerable#each_cons") do + a = [] + (1..5).each_cons(3){|e| a << e} + assert_equal a, [[1, 2, 3], [2, 3, 4], [3, 4, 5]] +end + +assert("Enumerable#each_slice") do + a = [] + (1..10).each_slice(3){|e| a << e} + assert_equal a, [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] +end + +assert("Enumerable#group_by") do + r = (1..6).group_by {|i| i % 3 } + assert_equal r[0], [3, 6] + assert_equal r[1], [1, 4] + assert_equal r[2], [2, 5] +end + diff --git a/mrbgems/mruby-eval/mrbgem.rake b/mrbgems/mruby-eval/mrbgem.rake new file mode 100644 index 000000000..f80cf1b9e --- /dev/null +++ b/mrbgems/mruby-eval/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-eval') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-eval/src/eval.c b/mrbgems/mruby-eval/src/eval.c new file mode 100644 index 000000000..039558596 --- /dev/null +++ b/mrbgems/mruby-eval/src/eval.c @@ -0,0 +1,23 @@ +#include "mruby.h" +#include "mruby/compile.h" + +static mrb_value +f_eval(mrb_state *mrb, mrb_value self) +{ + char *s; + int len; + + mrb_get_args(mrb, "s", &s, &len); + return mrb_load_nstring(mrb, s, len); +} + +void +mrb_mruby_eval_gem_init(mrb_state* mrb) +{ + mrb_define_class_method(mrb, mrb->kernel_module, "eval", f_eval, ARGS_REQ(1)); +} + +void +mrb_mruby_eval_gem_final(mrb_state* mrb) +{ +} diff --git a/mrbgems/mruby-hash-ext/mrbgem.rake b/mrbgems/mruby-hash-ext/mrbgem.rake new file mode 100644 index 000000000..3163c8c88 --- /dev/null +++ b/mrbgems/mruby-hash-ext/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-hash-ext') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb new file mode 100644 index 000000000..3e1bac0a2 --- /dev/null +++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb @@ -0,0 +1,12 @@ +class Hash + def merge!(other, &block) + if block + other.each_key{|k| + self[k] = (self.has_key?(k))? block.call(k, self[k], other[k]): other[k] + } + else + other.each_key{|k| self[k] = other[k]} + end + self + end +end diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb new file mode 100644 index 000000000..98eb313a4 --- /dev/null +++ b/mrbgems/mruby-hash-ext/test/hash.rb @@ -0,0 +1,20 @@ +## +# Hash(Ext) Test + +assert('Hash#merge!') do + a = { 'abc_key' => 'abc_value', 'cba_key' => 'cba_value' } + b = { 'cba_key' => 'XXX', 'xyz_key' => 'xyz_value' } + + result_1 = a.merge! b + + a = { 'abc_key' => 'abc_value', 'cba_key' => 'cba_value' } + result_2 = a.merge!(b) do |key, original, new| + original + end + + result_1 == {'abc_key' => 'abc_value', 'cba_key' => 'XXX', + 'xyz_key' => 'xyz_value' } and + result_2 == {'abc_key' => 'abc_value', 'cba_key' => 'cba_value', + 'xyz_key' => 'xyz_value' } +end + diff --git a/mrbgems/mruby-math/src/math.c b/mrbgems/mruby-math/src/math.c index 9955d9862..76058250f 100644 --- a/mrbgems/mruby-math/src/math.c +++ b/mrbgems/mruby-math/src/math.c @@ -26,13 +26,13 @@ double erfc(double x); -/* +/* ** Implementations of error functions ** credits to http://www.digitalmars.com/archives/cplusplus/3634.html */ /* Implementation of Error function */ -double +double erf(double x) { static const double two_sqrtpi = 1.128379167095512574; @@ -55,24 +55,24 @@ erf(double x) } /* Implementation of complementary Error function */ -double +double erfc(double x) { - static const double one_sqrtpi= 0.564189583547756287; - double a = 1; - double b = x; - double c = x; - double d = x*x+0.5; + static const double one_sqrtpi= 0.564189583547756287; + double a = 1; + double b = x; + double c = x; + double d = x*x+0.5; double q1; double q2 = b/d; double n = 1.0; double t; if (fabs(x) < 2.2) { - return 1.0 - erf(x); - } - if (x < 0.0) { /*signbit(x)*/ - return 2.0 - erfc(-x); - } + return 1.0 - erf(x); + } + if (x < 0.0) { /*signbit(x)*/ + return 2.0 - erfc(-x); + } do { t = a*n+b*x; a = b; @@ -306,7 +306,7 @@ math_asinh(mrb_state *mrb, mrb_value obj) mrb_float x; mrb_get_args(mrb, "f", &x); - + x = asinh(x); return mrb_float_value(x); @@ -477,10 +477,10 @@ static mrb_value math_sqrt(mrb_state *mrb, mrb_value obj) { mrb_float x; - + mrb_get_args(mrb, "f", &x); x = sqrt(x); - + return mrb_float_value(x); } @@ -544,7 +544,7 @@ math_frexp(mrb_state *mrb, mrb_value obj) { mrb_float x; int exp; - + mrb_get_args(mrb, "f", &x); x = frexp(x, &exp); @@ -633,13 +633,13 @@ mrb_mruby_math_gem_init(mrb_state* mrb) { struct RClass *mrb_math; mrb_math = mrb_define_module(mrb, "Math"); - + #ifdef M_PI mrb_define_const(mrb, mrb_math, "PI", mrb_float_value(M_PI)); #else mrb_define_const(mrb, mrb_math, "PI", mrb_float_value(atan(1.0)*4.0)); #endif - + #ifdef M_E mrb_define_const(mrb, mrb_math, "E", mrb_float_value(M_E)); #else @@ -660,7 +660,7 @@ mrb_mruby_math_gem_init(mrb_state* mrb) mrb_define_module_function(mrb, mrb_math, "acos", math_acos, ARGS_REQ(1)); mrb_define_module_function(mrb, mrb_math, "atan", math_atan, ARGS_REQ(1)); mrb_define_module_function(mrb, mrb_math, "atan2", math_atan2, ARGS_REQ(2)); - + mrb_define_module_function(mrb, mrb_math, "sinh", math_sinh, ARGS_REQ(1)); mrb_define_module_function(mrb, mrb_math, "cosh", math_cosh, ARGS_REQ(1)); mrb_define_module_function(mrb, mrb_math, "tanh", math_tanh, ARGS_REQ(1)); diff --git a/mrbgems/mruby-numeric-ext/mrbgem.rake b/mrbgems/mruby-numeric-ext/mrbgem.rake new file mode 100644 index 000000000..69c4fde4c --- /dev/null +++ b/mrbgems/mruby-numeric-ext/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-numeric-ext') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-numeric-ext/src/numeric_ext.c b/mrbgems/mruby-numeric-ext/src/numeric_ext.c new file mode 100644 index 000000000..09904c1a9 --- /dev/null +++ b/mrbgems/mruby-numeric-ext/src/numeric_ext.c @@ -0,0 +1,31 @@ +#include <limits.h> +#include "mruby.h" +#include "mruby/numeric.h" + +static mrb_value +mrb_int_chr(mrb_state *mrb, mrb_value x) +{ + mrb_int chr; + char c; + + chr = mrb_fixnum(x); + if (chr >= (1 << CHAR_BIT)) { + mrb_raisef(mrb, E_RANGE_ERROR, "%" PRIdMRB_INT " out of char range", chr); + } + c = (char)chr; + + return mrb_str_new(mrb, &c, 1); +} + +void +mrb_mruby_numeric_ext_gem_init(mrb_state* mrb) +{ + struct RClass *i = mrb_class_get(mrb, "Integer"); + + mrb_define_method(mrb, i, "chr", mrb_int_chr, ARGS_NONE()); +} + +void +mrb_mruby_numeric_ext_gem_final(mrb_state* mrb) +{ +} diff --git a/mrbgems/mruby-numeric-ext/test/numeric.rb b/mrbgems/mruby-numeric-ext/test/numeric.rb new file mode 100644 index 000000000..6c1cf0fce --- /dev/null +++ b/mrbgems/mruby-numeric-ext/test/numeric.rb @@ -0,0 +1,10 @@ +## +# Numeric(Ext) Test + +assert('Integer#chr') do + assert_equal(65.chr, "A") + assert_equal(0x42.chr, "B") + + # multibyte encoding (not support yet) + assert_raise(RangeError) { 12345.chr } +end diff --git a/mrbgems/mruby-print/mrbgem.rake b/mrbgems/mruby-print/mrbgem.rake new file mode 100644 index 000000000..dc7831280 --- /dev/null +++ b/mrbgems/mruby-print/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-print') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-print/mrblib/print.rb b/mrbgems/mruby-print/mrblib/print.rb new file mode 100644 index 000000000..38a10661b --- /dev/null +++ b/mrbgems/mruby-print/mrblib/print.rb @@ -0,0 +1,64 @@ +## +# Kernel +# +# ISO 15.3.1 +module Kernel + ## + # Invoke method +print+ on STDOUT and passing +*args+ + # + # ISO 15.3.1.2.10 + def print(*args) + i = 0 + len = args.size + while i < len + __printstr__ args[i].to_s + i += 1 + end + end + + ## + # Invoke method +puts+ on STDOUT and passing +*args*+ + # + # ISO 15.3.1.2.11 + def puts(*args) + i = 0 + len = args.size + while i < len + s = args[i].to_s + __printstr__ s + __printstr__ "\n" if (s[-1] != "\n") + i += 1 + end + __printstr__ "\n" if len == 0 + nil + end + + ## + # Print human readable object description + # + # ISO 15.3.1.3.34 + def p(*args) + i = 0 + len = args.size + while i < len + __printstr__ args[i].inspect + __printstr__ "\n" + i += 1 + end + args[0] + end + + unless Kernel.respond_to?(:sprintf) + def printf(*args) + raise NotImplementedError.new('printf not available') + end + def sprintf(*args) + raise NotImplementedError.new('sprintf not available') + end + else + def printf(*args) + __printstr__(sprintf(*args)) + nil + end + end +end diff --git a/mrbgems/mruby-print/src/print.c b/mrbgems/mruby-print/src/print.c new file mode 100644 index 000000000..608e3cc2d --- /dev/null +++ b/mrbgems/mruby-print/src/print.c @@ -0,0 +1,44 @@ +#include "mruby.h" +#include "mruby/string.h" +#include <stdio.h> + +static void +printstr(mrb_state *mrb, mrb_value obj) +{ + struct RString *str; + char *s; + int len; + + if (mrb_string_p(obj)) { + str = mrb_str_ptr(obj); + s = str->ptr; + len = str->len; + fwrite(s, len, 1, stdout); + } +} + +/* 15.3.1.2.9 */ +/* 15.3.1.3.34 */ +mrb_value +mrb_printstr(mrb_state *mrb, mrb_value self) +{ + mrb_value argv; + + mrb_get_args(mrb, "o", &argv); + printstr(mrb, argv); + + return argv; +} + +void +mrb_mruby_print_gem_init(mrb_state* mrb) +{ + struct RClass *krn; + krn = mrb->kernel_module; + mrb_define_method(mrb, krn, "__printstr__", mrb_printstr, ARGS_REQ(1)); +} + +void +mrb_mruby_print_gem_final(mrb_state* mrb) +{ +} diff --git a/mrbgems/mruby-random/mrbgem.rake b/mrbgems/mruby-random/mrbgem.rake new file mode 100644 index 000000000..7c2b2ddd5 --- /dev/null +++ b/mrbgems/mruby-random/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-random') do |spec| + spec.license = 'MIT, BSD New(mt19937ar)' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-random/src/mt19937ar.c b/mrbgems/mruby-random/src/mt19937ar.c new file mode 100644 index 000000000..8e3295a82 --- /dev/null +++ b/mrbgems/mruby-random/src/mt19937ar.c @@ -0,0 +1,232 @@ +/* + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + Copyright (C) 2005, Mutsuo Saito, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + Any feedback is very welcome. + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) +*/ + +#include <stdio.h> +#include "mt19937ar.h" + +/* Period parameters */ +//#define N 624 +#define M 397 +#define MATRIX_A 0x9908b0dfUL /* constant vector a */ +#define UPPER_MASK 0x80000000UL /* most significant w-r bits */ +#define LOWER_MASK 0x7fffffffUL /* least significant r bits */ + +static unsigned long mt[N]; /* the array for the state vector */ +static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ + +void mrb_random_init_genrand(mt_state *t, unsigned long s) +{ + t->mt[0]= s & 0xffffffffUL; + for (t->mti=1; t->mti<N; t->mti++) { + t->mt[t->mti] = + (1812433253UL * (t->mt[t->mti-1] ^ (t->mt[t->mti-1] >> 30)) + t->mti); + t->mt[t->mti] &= 0xffffffffUL; + } +} + +unsigned long mrb_random_genrand_int32(mt_state *t) +{ + unsigned long y; + static unsigned long mag01[2]={0x0UL, MATRIX_A}; + /* mag01[x] = x * MATRIX_A for x=0,1 */ + + if (t->mti >= N) { /* generate N words at one time */ + int kk; + + if (t->mti == N+1) /* if init_genrand() has not been called, */ + mrb_random_init_genrand(t, 5489UL); /* a default initial seed is used */ + + for (kk=0;kk<N-M;kk++) { + y = (t->mt[kk]&UPPER_MASK)|(t->mt[kk+1]&LOWER_MASK); + t->mt[kk] = t->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; + } + for (;kk<N-1;kk++) { + y = (t->mt[kk]&UPPER_MASK)|(t->mt[kk+1]&LOWER_MASK); + t->mt[kk] = t->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; + } + y = (t->mt[N-1]&UPPER_MASK)|(t->mt[0]&LOWER_MASK); + t->mt[N-1] = t->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; + + t->mti = 0; + } + + y = t->mt[t->mti++]; + + /* Tempering */ + y ^= (y >> 11); + y ^= (y << 7) & 0x9d2c5680UL; + y ^= (y << 15) & 0xefc60000UL; + y ^= (y >> 18); + + t->gen_int = y; + + return y; +} + +double mrb_random_genrand_real1(mt_state *t) +{ + mrb_random_genrand_int32(t); + t->gen_dbl = t->gen_int*(1.0/4294967295.0); + return t->gen_dbl; + /* divided by 2^32-1 */ +} + +/* initializes mt[N] with a seed */ +void init_genrand(unsigned long s) +{ + mt[0]= s & 0xffffffffUL; + for (mti=1; mti<N; mti++) { + mt[mti] = + (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + /* In the previous versions, MSBs of the seed affect */ + /* only MSBs of the array mt[]. */ + /* 2002/01/09 modified by Makoto Matsumoto */ + mt[mti] &= 0xffffffffUL; + /* for >32 bit machines */ + } +} + +/* initialize by an array with array-length */ +/* init_key is the array for initializing keys */ +/* key_length is its length */ +/* slight change for C++, 2004/2/26 */ +void init_by_array(unsigned long init_key[], int key_length) +{ + int i, j, k; + init_genrand(19650218UL); + i=1; j=0; + k = (N>key_length ? N : key_length); + for (; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + + init_key[j] + j; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; j++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + if (j>=key_length) j=0; + } + for (k=N-1; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) + - i; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + } + + mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ +} + +/* generates a random number on [0,0xffffffff]-interval */ +unsigned long genrand_int32(void) +{ + unsigned long y; + static unsigned long mag01[2]={0x0UL, MATRIX_A}; + /* mag01[x] = x * MATRIX_A for x=0,1 */ + + if (mti >= N) { /* generate N words at one time */ + int kk; + + if (mti == N+1) /* if init_genrand() has not been called, */ + init_genrand(5489UL); /* a default initial seed is used */ + + for (kk=0;kk<N-M;kk++) { + y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); + mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; + } + for (;kk<N-1;kk++) { + y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); + mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; + } + y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); + mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; + + mti = 0; + } + + y = mt[mti++]; + + /* Tempering */ + y ^= (y >> 11); + y ^= (y << 7) & 0x9d2c5680UL; + y ^= (y << 15) & 0xefc60000UL; + y ^= (y >> 18); + + return y; +} + +/* generates a random number on [0,0x7fffffff]-interval */ +long genrand_int31(void) +{ + return (long)(genrand_int32()>>1); +} + +/* generates a random number on [0,1]-real-interval */ +double genrand_real1(void) +{ + return genrand_int32()*(1.0/4294967295.0); + /* divided by 2^32-1 */ +} + +/* generates a random number on [0,1)-real-interval */ +double genrand_real2(void) +{ + return genrand_int32()*(1.0/4294967296.0); + /* divided by 2^32 */ +} + +/* generates a random number on (0,1)-real-interval */ +double genrand_real3(void) +{ + return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); + /* divided by 2^32 */ +} + +/* generates a random number on [0,1) with 53-bit resolution*/ +double genrand_res53(void) +{ + unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; + return(a*67108864.0+b)*(1.0/9007199254740992.0); +} +/* These real versions are due to Isaku Wada, 2002/01/09 added */ diff --git a/mrbgems/mruby-random/src/mt19937ar.h b/mrbgems/mruby-random/src/mt19937ar.h new file mode 100644 index 000000000..3f36cb1ff --- /dev/null +++ b/mrbgems/mruby-random/src/mt19937ar.h @@ -0,0 +1,87 @@ +/* + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + Copyright (C) 2005, Mutsuo Saito + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + Any feedback is very welcome. + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) +*/ + +#define N 624 + +typedef struct { + unsigned long mt[N]; + int mti; + union { + unsigned long gen_int; + double gen_dbl; + }; +} mt_state; + +void mrb_random_init_genrand(mt_state *, unsigned long); +unsigned long mrb_random_genrand_int32(mt_state *); +double mrb_random_genrand_real1(mt_state *t); + +/* initializes mt[N] with a seed */ +void init_genrand(unsigned long s); + +/* initialize by an array with array-length */ +/* init_key is the array for initializing keys */ +/* key_length is its length */ +/* slight change for C++, 2004/2/26 */ +void init_by_array(unsigned long init_key[], int key_length); + +/* generates a random number on [0,0xffffffff]-interval */ +unsigned long genrand_int32(void); + +/* generates a random number on [0,0x7fffffff]-interval */ +long genrand_int31(void); + +/* These real versions are due to Isaku Wada, 2002/01/09 added */ +/* generates a random number on [0,1]-real-interval */ +double genrand_real1(void); + +/* generates a random number on [0,1)-real-interval */ +double genrand_real2(void); + +/* generates a random number on (0,1)-real-interval */ +double genrand_real3(void); + +/* generates a random number on [0,1) with 53-bit resolution*/ +double genrand_res53(void); diff --git a/mrbgems/mruby-random/src/random.c b/mrbgems/mruby-random/src/random.c new file mode 100644 index 000000000..6500b3f84 --- /dev/null +++ b/mrbgems/mruby-random/src/random.c @@ -0,0 +1,233 @@ +/* +** random.c - Random module +** +** See Copyright Notice in mruby.h +*/ + +#include "mruby.h" +#include "mruby/variable.h" +#include "mruby/data.h" +#include "mt19937ar.h" + +#include <time.h> + +#define GLOBAL_RAND_SEED_KEY "$mrb_g_rand_seed" +#define INSTANCE_RAND_SEED_KEY "$mrb_i_rand_seed" +#define MT_STATE_KEY "$mrb_i_mt_state" + +static void mt_state_free(mrb_state *mrb, void *p) +{ +} + +static const struct mrb_data_type mt_state_type = { + MT_STATE_KEY, mt_state_free, +}; + +static mt_state *mrb_mt_get_context(mrb_state *mrb, mrb_value self) +{ + mt_state *t; + mrb_value context; + + context = mrb_iv_get(mrb, self, mrb_intern(mrb, MT_STATE_KEY)); + t = (mt_state *)mrb_check_datatype(mrb, context, &mt_state_type); + if (!t) + mrb_raise(mrb, E_RUNTIME_ERROR, "mt_state get from mrb_iv_get failed"); + + return t; +} + +static void mt_g_srand(unsigned long seed) +{ + init_genrand(seed); +} + +static unsigned long mt_g_rand() +{ + return genrand_int32(); +} + +static double mt_g_rand_real() +{ + return genrand_real1(); +} + +static mrb_value mrb_random_mt_g_srand(mrb_state *mrb, mrb_value seed) +{ + if (mrb_nil_p(seed)) { + seed = mrb_fixnum_value(time(NULL) + mt_g_rand()); + if (mrb_fixnum(seed) < 0) { + seed = mrb_fixnum_value( 0 - mrb_fixnum(seed)); + } + } + + mt_g_srand((unsigned) mrb_fixnum(seed)); + + return seed; +} + +static mrb_value mrb_random_mt_g_rand(mrb_state *mrb, mrb_value max) +{ + mrb_value value; + + if (mrb_fixnum(max) == 0) { + value = mrb_float_value(mt_g_rand_real()); + } else { + value = mrb_fixnum_value(mt_g_rand() % mrb_fixnum(max)); + } + + return value; +} + +static void mt_srand(mt_state *t, unsigned long seed) +{ + mrb_random_init_genrand(t, seed); +} + +static unsigned long mt_rand(mt_state *t) +{ + return mrb_random_genrand_int32(t); +} + +static double mt_rand_real(mt_state *t) +{ + return mrb_random_genrand_real1(t); +} + +static mrb_value mrb_random_mt_srand(mrb_state *mrb, mt_state *t, mrb_value seed) +{ + if (mrb_nil_p(seed)) { + seed = mrb_fixnum_value(time(NULL) + mt_rand(t)); + if (mrb_fixnum(seed) < 0) { + seed = mrb_fixnum_value( 0 - mrb_fixnum(seed)); + } + } + + mt_srand(t, (unsigned) mrb_fixnum(seed)); + + return seed; +} + +static mrb_value mrb_random_mt_rand(mrb_state *mrb, mt_state *t, mrb_value max) +{ + mrb_value value; + + if (mrb_fixnum(max) == 0) { + value = mrb_float_value(mt_rand_real(t)); + } else { + value = mrb_fixnum_value(mt_rand(t) % mrb_fixnum(max)); + } + + return value; +} + +static mrb_value get_opt(mrb_state* mrb) +{ + mrb_value arg; + + arg = mrb_fixnum_value(0); + mrb_get_args(mrb, "|o", &arg); + + if (!mrb_nil_p(arg)) { + if (!mrb_fixnum_p(arg)) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument type"); + } + arg = mrb_check_convert_type(mrb, arg, MRB_TT_FIXNUM, "Fixnum", "to_int"); + if (mrb_fixnum(arg) < 0) { + arg = mrb_fixnum_value(0 - mrb_fixnum(arg)); + } + } + return arg; +} + +static mrb_value mrb_random_g_rand(mrb_state *mrb, mrb_value self) +{ + mrb_value max; + mrb_value seed; + + max = get_opt(mrb); + seed = mrb_gv_get(mrb, mrb_intern(mrb, GLOBAL_RAND_SEED_KEY)); + if (mrb_nil_p(seed)) { + mrb_random_mt_g_srand(mrb, mrb_nil_value()); + } + return mrb_random_mt_g_rand(mrb, max); +} + +static mrb_value mrb_random_g_srand(mrb_state *mrb, mrb_value self) +{ + mrb_value seed; + mrb_value old_seed; + + seed = get_opt(mrb); + seed = mrb_random_mt_g_srand(mrb, seed); + old_seed = mrb_gv_get(mrb, mrb_intern(mrb, GLOBAL_RAND_SEED_KEY)); + mrb_gv_set(mrb, mrb_intern(mrb, GLOBAL_RAND_SEED_KEY), seed); + return old_seed; +} + +static mrb_value mrb_random_init(mrb_state *mrb, mrb_value self) +{ + mrb_value seed; + + + mt_state *t = (mt_state *)mrb_malloc(mrb, sizeof(mt_state)); + t->mti = N + 1; + + seed = get_opt(mrb); + seed = mrb_random_mt_srand(mrb, t, seed); + mrb_iv_set(mrb, self, mrb_intern(mrb, INSTANCE_RAND_SEED_KEY), seed); + mrb_iv_set(mrb, self, mrb_intern(mrb, MT_STATE_KEY), + mrb_obj_value(Data_Wrap_Struct(mrb, mrb->object_class, &mt_state_type, (void*) t))); + return self; +} + +static mrb_value mrb_random_rand(mrb_state *mrb, mrb_value self) +{ + mrb_value max; + mrb_value seed; + mt_state *t = mrb_mt_get_context(mrb, self); + + max = get_opt(mrb); + seed = mrb_iv_get(mrb, self, mrb_intern(mrb, INSTANCE_RAND_SEED_KEY)); + if (mrb_nil_p(seed)) { + mrb_random_mt_srand(mrb, t, mrb_nil_value()); + } + mrb_iv_set(mrb, self, mrb_intern(mrb, MT_STATE_KEY), + mrb_obj_value(Data_Wrap_Struct(mrb, mrb->object_class, &mt_state_type, (void*) t))); + return mrb_random_mt_rand(mrb, t, max); +} + +static mrb_value mrb_random_srand(mrb_state *mrb, mrb_value self) +{ + mrb_value seed; + mrb_value old_seed; + mt_state *t = mrb_mt_get_context(mrb, self); + + seed = get_opt(mrb); + seed = mrb_random_mt_srand(mrb, t, seed); + old_seed = mrb_iv_get(mrb, self, mrb_intern(mrb, INSTANCE_RAND_SEED_KEY)); + mrb_iv_set(mrb, self, mrb_intern(mrb, INSTANCE_RAND_SEED_KEY), seed); + mrb_iv_set(mrb, self, mrb_intern(mrb, MT_STATE_KEY), + mrb_obj_value(Data_Wrap_Struct(mrb, mrb->object_class, &mt_state_type, (void*) t))); + return old_seed; +} + +void mrb_mruby_random_gem_init(mrb_state *mrb) +{ + struct RClass *random; + + mrb_define_method(mrb, mrb->kernel_module, "rand", mrb_random_g_rand, ARGS_OPT(1)); + mrb_define_method(mrb, mrb->kernel_module, "srand", mrb_random_g_srand, ARGS_OPT(1)); + + random = mrb_define_class(mrb, "Random", mrb->object_class); + mrb_define_class_method(mrb, random, "rand", mrb_random_g_rand, ARGS_OPT(1)); + mrb_define_class_method(mrb, random, "srand", mrb_random_g_srand, ARGS_OPT(1)); + + mrb_define_method(mrb, random, "initialize", mrb_random_init, ARGS_OPT(1)); + mrb_define_method(mrb, random, "rand", mrb_random_rand, ARGS_OPT(1)); + mrb_define_method(mrb, random, "srand", mrb_random_srand, ARGS_OPT(1)); +} + +void mrb_mruby_random_gem_final(mrb_state *mrb) +{ +} + diff --git a/mrbgems/mruby-random/src/random.h b/mrbgems/mruby-random/src/random.h new file mode 100644 index 000000000..3dc5d4e77 --- /dev/null +++ b/mrbgems/mruby-random/src/random.h @@ -0,0 +1,12 @@ +/* +// random.h - Random module +// +// See Copyright Notice in mruby.h +*/ + +#ifndef RANDOM_H +#define RANDOM_H + +void mrb_mruby_random_gem_init(mrb_state *mrb); + +#endif diff --git a/mrbgems/mruby-random/test/random.rb b/mrbgems/mruby-random/test/random.rb new file mode 100644 index 000000000..01d231d5c --- /dev/null +++ b/mrbgems/mruby-random/test/random.rb @@ -0,0 +1,32 @@ +## +# Random Test + +assert("Random#srand") do + r1 = Random.new(123) + r2 = Random.new(123) + r1.rand == r2.rand +end + +assert("Kernel::srand") do + srand(234) + r1 = rand + srand(234) + r2 = rand + r1 == r2 +end + +assert("Random::srand") do + Random.srand(345) + r1 = rand + srand(345) + r2 = Random.rand + r1 == r2 +end + +assert("fixnum") do + rand(3).class == Fixnum +end + +assert("float") do + rand.class == Float +end diff --git a/mrbgems/mruby-sprintf/mrbgem.rake b/mrbgems/mruby-sprintf/mrbgem.rake new file mode 100644 index 000000000..8772a5174 --- /dev/null +++ b/mrbgems/mruby-sprintf/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-sprintf') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-sprintf/src/kernel.c b/mrbgems/mruby-sprintf/src/kernel.c new file mode 100644 index 000000000..8f54a3d85 --- /dev/null +++ b/mrbgems/mruby-sprintf/src/kernel.c @@ -0,0 +1,30 @@ +/* +** kernel.c - Kernel module suppliment +** +** See Copyright Notice in mruby.h +*/ + +#include "mruby.h" + +mrb_value mrb_f_sprintf(mrb_state *mrb, mrb_value obj); /* in sprintf.c */ + +void +mrb_mruby_sprintf_gem_init(mrb_state* mrb) +{ + struct RClass *krn; + + if (mrb->kernel_module == NULL) { + mrb->kernel_module = mrb_define_module(mrb, "Kernel"); /* Might be PARANOID. */ + } + krn = mrb->kernel_module; + + mrb_define_method(mrb, krn, "sprintf", mrb_f_sprintf, ARGS_ANY()); + mrb_define_method(mrb, krn, "format", mrb_f_sprintf, ARGS_ANY()); +} + +void +mrb_mruby_sprintf_gem_final(mrb_state* mrb) +{ + /* nothing to do. */ +} + diff --git a/mrbgems/mruby-sprintf/src/sprintf.c b/mrbgems/mruby-sprintf/src/sprintf.c new file mode 100644 index 000000000..fed730c74 --- /dev/null +++ b/mrbgems/mruby-sprintf/src/sprintf.c @@ -0,0 +1,1106 @@ +/* +** sprintf.c - Kernel.#sprintf +** +** See Copyright Notice in mruby.h +*/ + +#include "mruby.h" + +#include <limits.h> +#include <stdio.h> +#include <string.h> +#include "mruby/string.h" +#include "mruby/hash.h" +#include "mruby/numeric.h" +#include <math.h> +#include <ctype.h> + +#ifdef _MSC_VER +#include <float.h> +#endif + +#ifdef HAVE_IEEEFP_H +#include <ieeefp.h> +#endif + +#define BIT_DIGITS(N) (((N)*146)/485 + 1) /* log2(10) =~ 146/485 */ +#define BITSPERDIG (sizeof(mrb_int)*CHAR_BIT) +#define EXTENDSIGN(n, l) (((~0 << (n)) >> (((n)*(l)) % BITSPERDIG)) & ~(~0 << (n))) + +static void fmt_setup(char*,size_t,int,int,mrb_int,mrb_int); + +static char* +remove_sign_bits(char *str, int base) +{ + char *t; + + t = str; + if (base == 16) { + while (*t == 'f') { + t++; + } + } + else if (base == 8) { + *t |= EXTENDSIGN(3, strlen(t)); + while (*t == '7') { + t++; + } + } + else if (base == 2) { + while (*t == '1') { + t++; + } + } + + return t; +} + +static char +sign_bits(int base, const char *p) +{ + char c; + + switch (base) { + case 16: + if (*p == 'X') c = 'F'; + else c = 'f'; + break; + case 8: + c = '7'; break; + case 2: + c = '1'; break; + default: + c = '.'; break; + } + return c; +} + +static mrb_value +mrb_fix2binstr(mrb_state *mrb, mrb_value x, int base) +{ + char buf[64], *b = buf + sizeof buf; + mrb_int num = mrb_fixnum(x); + unsigned long val = (unsigned long)num; + char d; + + if (base != 2) { + mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid radix %S", mrb_fixnum_value(base)); + } + + if (val >= (1 << 10)) + val &= 0x3ff; + + if (val == 0) { + return mrb_str_new(mrb, "0", 1); + } + *--b = '\0'; + do { + *--b = mrb_digitmap[(int)(val % base)]; + } while (val /= base); + + if (num < 0) { + b = remove_sign_bits(b, base); + switch (base) { + case 16: d = 'f'; break; + case 8: d = '7'; break; + case 2: d = '1'; break; + default: d = 0; break; + } + + if (d && *b != d) { + *--b = d; + } + } + + return mrb_str_new_cstr(mrb, b); +} + +#define FNONE 0 +#define FSHARP 1 +#define FMINUS 2 +#define FPLUS 4 +#define FZERO 8 +#define FSPACE 16 +#define FWIDTH 32 +#define FPREC 64 +#define FPREC0 128 + +#define CHECK(l) do {\ +/* int cr = ENC_CODERANGE(result);*/\ + while (blen + (l) >= bsiz) {\ + bsiz*=2;\ + }\ + mrb_str_resize(mrb, result, bsiz);\ +/* ENC_CODERANGE_SET(result, cr);*/\ + buf = RSTRING_PTR(result);\ +} while (0) + +#define PUSH(s, l) do { \ + CHECK(l);\ + memcpy(&buf[blen], s, l);\ + blen += (l);\ +} while (0) + +#define FILL(c, l) do { \ + CHECK(l);\ + memset(&buf[blen], c, l);\ + blen += (l);\ +} while (0) + +#define GETARG() (!mrb_undef_p(nextvalue) ? nextvalue : \ + posarg == -1 ? \ + (mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with numbered", mrb_fixnum_value(nextarg)), mrb_undef_value()) : \ + posarg == -2 ? \ + (mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%S) mixed with named", mrb_fixnum_value(nextarg)), mrb_undef_value()) : \ + (posarg = nextarg++, GETNTHARG(posarg))) + +#define GETPOSARG(n) (posarg > 0 ? \ + (mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after unnumbered(%S)", mrb_fixnum_value(n), mrb_fixnum_value(posarg)), mrb_undef_value()) : \ + posarg == -2 ? \ + (mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%S) after named", mrb_fixnum_value(n)), mrb_undef_value()) : \ + ((n < 1) ? \ + (mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid index - %S$", mrb_fixnum_value(n)), mrb_undef_value()) : \ + (posarg = -1, GETNTHARG(n)))) + +#define GETNTHARG(nth) \ + ((nth >= argc) ? (mrb_raise(mrb, E_ARGUMENT_ERROR, "too few arguments"), mrb_undef_value()) : argv[nth]) + +#define GETNAMEARG(id, name, len) ( \ + posarg > 0 ? \ + (mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after unnumbered(%S)", mrb_str_new(mrb, (name), (len)), mrb_fixnum_value(posarg)), mrb_undef_value()) : \ + posarg == -1 ? \ + (mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%S after numbered", mrb_str_new(mrb, (name), (len))), mrb_undef_value()) : \ + (posarg = -2, mrb_hash_fetch(mrb, get_hash(mrb, &hash, argc, argv), id, mrb_undef_value()))) + +#define GETNUM(n, val) \ + for (; p < end && ISDIGIT(*p); p++) {\ + int next_n = 10 * n + (*p - '0'); \ + if (next_n / 10 != n) {\ + mrb_raise(mrb, E_ARGUMENT_ERROR, #val " too big"); \ + } \ + n = next_n; \ + } \ + if (p >= end) { \ + mrb_raise(mrb, E_ARGUMENT_ERROR, "malformed format string - %*[0-9]"); \ + } + +#define GETASTER(num) do { \ + t = p++; \ + n = 0; \ + GETNUM(n, val); \ + if (*p == '$') { \ + tmp = GETPOSARG(n); \ + } \ + else { \ + tmp = GETARG(); \ + p = t; \ + } \ + num = mrb_fixnum(tmp); \ +} while (0) + +static mrb_value +get_hash(mrb_state *mrb, mrb_value *hash, int argc, const mrb_value *argv) +{ + mrb_value tmp; + + if (!mrb_undef_p(*hash)) return *hash; + if (argc != 2) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "one hash required"); + } + tmp = mrb_check_convert_type(mrb, argv[1], MRB_TT_HASH, "Hash", "to_hash"); + if (mrb_nil_p(tmp)) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "one hash required"); + } + return (*hash = tmp); +} + +/* + * call-seq: + * format(format_string [, arguments...] ) -> string + * sprintf(format_string [, arguments...] ) -> string + * + * Returns the string resulting from applying <i>format_string</i> to + * any additional arguments. Within the format string, any characters + * other than format sequences are copied to the result. + * + * The syntax of a format sequence is follows. + * + * %[flags][width][.precision]type + * + * A format + * sequence consists of a percent sign, followed by optional flags, + * width, and precision indicators, then terminated with a field type + * character. The field type controls how the corresponding + * <code>sprintf</code> argument is to be interpreted, while the flags + * modify that interpretation. + * + * The field type characters are: + * + * Field | Integer Format + * ------+-------------------------------------------------------------- + * b | Convert argument as a binary number. + * | Negative numbers will be displayed as a two's complement + * | prefixed with `..1'. + * B | Equivalent to `b', but uses an uppercase 0B for prefix + * | in the alternative format by #. + * d | Convert argument as a decimal number. + * i | Identical to `d'. + * o | Convert argument as an octal number. + * | Negative numbers will be displayed as a two's complement + * | prefixed with `..7'. + * u | Identical to `d'. + * x | Convert argument as a hexadecimal number. + * | Negative numbers will be displayed as a two's complement + * | prefixed with `..f' (representing an infinite string of + * | leading 'ff's). + * X | Equivalent to `x', but uses uppercase letters. + * + * Field | Float Format + * ------+-------------------------------------------------------------- + * e | Convert floating point argument into exponential notation + * | with one digit before the decimal point as [-]d.dddddde[+-]dd. + * | The precision specifies the number of digits after the decimal + * | point (defaulting to six). + * E | Equivalent to `e', but uses an uppercase E to indicate + * | the exponent. + * f | Convert floating point argument as [-]ddd.dddddd, + * | where the precision specifies the number of digits after + * | the decimal point. + * g | Convert a floating point number using exponential form + * | if the exponent is less than -4 or greater than or + * | equal to the precision, or in dd.dddd form otherwise. + * | The precision specifies the number of significant digits. + * G | Equivalent to `g', but use an uppercase `E' in exponent form. + * a | Convert floating point argument as [-]0xh.hhhhp[+-]dd, + * | which is consisted from optional sign, "0x", fraction part + * | as hexadecimal, "p", and exponential part as decimal. + * A | Equivalent to `a', but use uppercase `X' and `P'. + * + * Field | Other Format + * ------+-------------------------------------------------------------- + * c | Argument is the numeric code for a single character or + * | a single character string itself. + * p | The valuing of argument.inspect. + * s | Argument is a string to be substituted. If the format + * | sequence contains a precision, at most that many characters + * | will be copied. + * % | A percent sign itself will be displayed. No argument taken. + * + * The flags modifies the behavior of the formats. + * The flag characters are: + * + * Flag | Applies to | Meaning + * ---------+---------------+----------------------------------------- + * space | bBdiouxX | Leave a space at the start of + * | aAeEfgG | non-negative numbers. + * | (numeric fmt) | For `o', `x', `X', `b' and `B', use + * | | a minus sign with absolute value for + * | | negative values. + * ---------+---------------+----------------------------------------- + * (digit)$ | all | Specifies the absolute argument number + * | | for this field. Absolute and relative + * | | argument numbers cannot be mixed in a + * | | sprintf string. + * ---------+---------------+----------------------------------------- + * # | bBoxX | Use an alternative format. + * | aAeEfgG | For the conversions `o', increase the precision + * | | until the first digit will be `0' if + * | | it is not formatted as complements. + * | | For the conversions `x', `X', `b' and `B' + * | | on non-zero, prefix the result with ``0x'', + * | | ``0X'', ``0b'' and ``0B'', respectively. + * | | For `a', `A', `e', `E', `f', `g', and 'G', + * | | force a decimal point to be added, + * | | even if no digits follow. + * | | For `g' and 'G', do not remove trailing zeros. + * ---------+---------------+----------------------------------------- + * + | bBdiouxX | Add a leading plus sign to non-negative + * | aAeEfgG | numbers. + * | (numeric fmt) | For `o', `x', `X', `b' and `B', use + * | | a minus sign with absolute value for + * | | negative values. + * ---------+---------------+----------------------------------------- + * - | all | Left-justify the result of this conversion. + * ---------+---------------+----------------------------------------- + * 0 (zero) | bBdiouxX | Pad with zeros, not spaces. + * | aAeEfgG | For `o', `x', `X', `b' and `B', radix-1 + * | (numeric fmt) | is used for negative numbers formatted as + * | | complements. + * ---------+---------------+----------------------------------------- + * * | all | Use the next argument as the field width. + * | | If negative, left-justify the result. If the + * | | asterisk is followed by a number and a dollar + * | | sign, use the indicated argument as the width. + * + * Examples of flags: + * + * # `+' and space flag specifies the sign of non-negative numbers. + * sprintf("%d", 123) #=> "123" + * sprintf("%+d", 123) #=> "+123" + * sprintf("% d", 123) #=> " 123" + * + * # `#' flag for `o' increases number of digits to show `0'. + * # `+' and space flag changes format of negative numbers. + * sprintf("%o", 123) #=> "173" + * sprintf("%#o", 123) #=> "0173" + * sprintf("%+o", -123) #=> "-173" + * sprintf("%o", -123) #=> "..7605" + * sprintf("%#o", -123) #=> "..7605" + * + * # `#' flag for `x' add a prefix `0x' for non-zero numbers. + * # `+' and space flag disables complements for negative numbers. + * sprintf("%x", 123) #=> "7b" + * sprintf("%#x", 123) #=> "0x7b" + * sprintf("%+x", -123) #=> "-7b" + * sprintf("%x", -123) #=> "..f85" + * sprintf("%#x", -123) #=> "0x..f85" + * sprintf("%#x", 0) #=> "0" + * + * # `#' for `X' uses the prefix `0X'. + * sprintf("%X", 123) #=> "7B" + * sprintf("%#X", 123) #=> "0X7B" + * + * # `#' flag for `b' add a prefix `0b' for non-zero numbers. + * # `+' and space flag disables complements for negative numbers. + * sprintf("%b", 123) #=> "1111011" + * sprintf("%#b", 123) #=> "0b1111011" + * sprintf("%+b", -123) #=> "-1111011" + * sprintf("%b", -123) #=> "..10000101" + * sprintf("%#b", -123) #=> "0b..10000101" + * sprintf("%#b", 0) #=> "0" + * + * # `#' for `B' uses the prefix `0B'. + * sprintf("%B", 123) #=> "1111011" + * sprintf("%#B", 123) #=> "0B1111011" + * + * # `#' for `e' forces to show the decimal point. + * sprintf("%.0e", 1) #=> "1e+00" + * sprintf("%#.0e", 1) #=> "1.e+00" + * + * # `#' for `f' forces to show the decimal point. + * sprintf("%.0f", 1234) #=> "1234" + * sprintf("%#.0f", 1234) #=> "1234." + * + * # `#' for `g' forces to show the decimal point. + * # It also disables stripping lowest zeros. + * sprintf("%g", 123.4) #=> "123.4" + * sprintf("%#g", 123.4) #=> "123.400" + * sprintf("%g", 123456) #=> "123456" + * sprintf("%#g", 123456) #=> "123456." + * + * The field width is an optional integer, followed optionally by a + * period and a precision. The width specifies the minimum number of + * characters that will be written to the result for this field. + * + * Examples of width: + * + * # padding is done by spaces, width=20 + * # 0 or radix-1. <------------------> + * sprintf("%20d", 123) #=> " 123" + * sprintf("%+20d", 123) #=> " +123" + * sprintf("%020d", 123) #=> "00000000000000000123" + * sprintf("%+020d", 123) #=> "+0000000000000000123" + * sprintf("% 020d", 123) #=> " 0000000000000000123" + * sprintf("%-20d", 123) #=> "123 " + * sprintf("%-+20d", 123) #=> "+123 " + * sprintf("%- 20d", 123) #=> " 123 " + * sprintf("%020x", -123) #=> "..ffffffffffffffff85" + * + * For + * numeric fields, the precision controls the number of decimal places + * displayed. For string fields, the precision determines the maximum + * number of characters to be copied from the string. (Thus, the format + * sequence <code>%10.10s</code> will always contribute exactly ten + * characters to the result.) + * + * Examples of precisions: + * + * # precision for `d', 'o', 'x' and 'b' is + * # minimum number of digits <------> + * sprintf("%20.8d", 123) #=> " 00000123" + * sprintf("%20.8o", 123) #=> " 00000173" + * sprintf("%20.8x", 123) #=> " 0000007b" + * sprintf("%20.8b", 123) #=> " 01111011" + * sprintf("%20.8d", -123) #=> " -00000123" + * sprintf("%20.8o", -123) #=> " ..777605" + * sprintf("%20.8x", -123) #=> " ..ffff85" + * sprintf("%20.8b", -11) #=> " ..110101" + * + * # "0x" and "0b" for `#x' and `#b' is not counted for + * # precision but "0" for `#o' is counted. <------> + * sprintf("%#20.8d", 123) #=> " 00000123" + * sprintf("%#20.8o", 123) #=> " 00000173" + * sprintf("%#20.8x", 123) #=> " 0x0000007b" + * sprintf("%#20.8b", 123) #=> " 0b01111011" + * sprintf("%#20.8d", -123) #=> " -00000123" + * sprintf("%#20.8o", -123) #=> " ..777605" + * sprintf("%#20.8x", -123) #=> " 0x..ffff85" + * sprintf("%#20.8b", -11) #=> " 0b..110101" + * + * # precision for `e' is number of + * # digits after the decimal point <------> + * sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03" + * + * # precision for `f' is number of + * # digits after the decimal point <------> + * sprintf("%20.8f", 1234.56789) #=> " 1234.56789000" + * + * # precision for `g' is number of + * # significant digits <-------> + * sprintf("%20.8g", 1234.56789) #=> " 1234.5679" + * + * # <-------> + * sprintf("%20.8g", 123456789) #=> " 1.2345679e+08" + * + * # precision for `s' is + * # maximum number of characters <------> + * sprintf("%20.8s", "string test") #=> " string t" + * + * Examples: + * + * sprintf("%d %04x", 123, 123) #=> "123 007b" + * sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'" + * sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello" + * sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8" + * sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23" + * sprintf("%u", -123) #=> "-123" + * + * For more complex formatting, Ruby supports a reference by name. + * %<name>s style uses format style, but %{name} style doesn't. + * + * Exapmles: + * sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 }) + * #=> 1 : 2.000000 + * sprintf("%{foo}f", { :foo => 1 }) + * # => "1f" + */ + +mrb_value +mrb_f_sprintf(mrb_state *mrb, mrb_value obj) +{ + int argc; + mrb_value *argv; + + mrb_get_args(mrb, "*", &argv, &argc); + + if (argc <= 0) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "too few arguments"); + return mrb_nil_value(); + } + else { + return mrb_str_format(mrb, argc - 1, argv + 1, argv[0]); + } +} + +mrb_value +mrb_str_format(mrb_state *mrb, int argc, const mrb_value *argv, mrb_value fmt) +{ + const char *p, *end; + char *buf; + mrb_int blen; + mrb_int bsiz; + mrb_value result; + mrb_int n; + mrb_int width; + mrb_int prec; + int flags = FNONE; + int nextarg = 1; + int posarg = 0; + mrb_value nextvalue; + mrb_value tmp; + mrb_value str; + mrb_value hash = mrb_undef_value(); + +#define CHECK_FOR_WIDTH(f) \ + if ((f) & FWIDTH) { \ + mrb_raise(mrb, E_ARGUMENT_ERROR, "width given twice"); \ + } \ + if ((f) & FPREC0) { \ + mrb_raise(mrb, E_ARGUMENT_ERROR, "width after precision"); \ + } +#define CHECK_FOR_FLAGS(f) \ + if ((f) & FWIDTH) { \ + mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after width"); \ + } \ + if ((f) & FPREC0) { \ + mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after precision"); \ + } + + ++argc; + --argv; + fmt = mrb_str_to_str(mrb, fmt); + p = RSTRING_PTR(fmt); + end = p + RSTRING_LEN(fmt); + blen = 0; + bsiz = 120; + result = mrb_str_buf_new(mrb, bsiz); + buf = RSTRING_PTR(result); + memset(buf, 0, bsiz); + + for (; p < end; p++) { + const char *t; + mrb_sym id = 0; + + for (t = p; t < end && *t != '%'; t++) ; + PUSH(p, t - p); + if (t >= end) + goto sprint_exit; /* end of fmt string */ + + p = t + 1; /* skip `%' */ + + width = prec = -1; + nextvalue = mrb_undef_value(); + +retry: + switch (*p) { + default: + mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed format string - \\%%S", mrb_str_new(mrb, p, 1)); + break; + + case ' ': + CHECK_FOR_FLAGS(flags); + flags |= FSPACE; + p++; + goto retry; + + case '#': + CHECK_FOR_FLAGS(flags); + flags |= FSHARP; + p++; + goto retry; + + case '+': + CHECK_FOR_FLAGS(flags); + flags |= FPLUS; + p++; + goto retry; + + case '-': + CHECK_FOR_FLAGS(flags); + flags |= FMINUS; + p++; + goto retry; + + case '0': + CHECK_FOR_FLAGS(flags); + flags |= FZERO; + p++; + goto retry; + + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + n = 0; + GETNUM(n, width); + if (*p == '$') { + if (!mrb_undef_p(nextvalue)) { + mrb_raisef(mrb, E_ARGUMENT_ERROR, "value given twice - %S$", mrb_fixnum_value(n)); + } + nextvalue = GETPOSARG(n); + p++; + goto retry; + } + CHECK_FOR_WIDTH(flags); + width = n; + flags |= FWIDTH; + goto retry; + + case '<': + case '{': { + const char *start = p; + char term = (*p == '<') ? '>' : '}'; + mrb_value symname; + + for (; p < end && *p != term; ) + p++; + if (id) { + mrb_raisef(mrb, E_ARGUMENT_ERROR, "name%S after <%S>", + mrb_str_new(mrb, start, p - start + 1), mrb_sym2str(mrb, id)); + } + symname = mrb_str_new(mrb, start + 1, p - start - 1); + id = mrb_intern_str(mrb, symname); + nextvalue = GETNAMEARG(mrb_symbol_value(id), start, (int)(p - start + 1)); + if (mrb_undef_p(nextvalue)) { + mrb_raisef(mrb, E_KEY_ERROR, "key%S not found", mrb_str_new(mrb, start, p - start + 1)); + } + if (term == '}') goto format_s; + p++; + goto retry; + } + + case '*': + CHECK_FOR_WIDTH(flags); + flags |= FWIDTH; + GETASTER(width); + if (width < 0) { + flags |= FMINUS; + width = -width; + } + p++; + goto retry; + + case '.': + if (flags & FPREC0) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "precision given twice"); + } + flags |= FPREC|FPREC0; + + prec = 0; + p++; + if (*p == '*') { + GETASTER(prec); + if (prec < 0) { /* ignore negative precision */ + flags &= ~FPREC; + } + p++; + goto retry; + } + + GETNUM(prec, precision); + goto retry; + + case '\n': + case '\0': + p--; + + case '%': + if (flags != FNONE) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid format character - %"); + } + PUSH("%", 1); + break; + + case 'c': { + mrb_value val = GETARG(); + mrb_value tmp; + unsigned int c; + + tmp = mrb_check_string_type(mrb, val); + if (!mrb_nil_p(tmp)) { + if (RSTRING_LEN(tmp) != 1 ) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "%c requires a character"); + } + c = RSTRING_PTR(tmp)[0]; + n = 1; + } + else { + c = mrb_fixnum(val); + n = 1; + } + if (n <= 0) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid character"); + } + if (!(flags & FWIDTH)) { + CHECK(n); + buf[blen] = c; + blen += n; + } + else if ((flags & FMINUS)) { + CHECK(n); + buf[blen] = c; + blen += n; + FILL(' ', width-1); + } + else { + FILL(' ', width-1); + CHECK(n); + buf[blen] = c; + blen += n; + } + } + break; + + case 's': + case 'p': + format_s: + { + mrb_value arg = GETARG(); + mrb_int len; + mrb_int slen; + + if (*p == 'p') arg = mrb_inspect(mrb, arg); + str = mrb_obj_as_string(mrb, arg); + len = RSTRING_LEN(str); + RSTRING_LEN(result) = blen; + if (flags&(FPREC|FWIDTH)) { + slen = RSTRING_LEN(str); + if (slen < 0) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid mbstring sequence"); + } + if ((flags&FPREC) && (prec < slen)) { + char *p = RSTRING_PTR(str) + prec; + slen = prec; + len = p - RSTRING_PTR(str); + } + /* need to adjust multi-byte string pos */ + if ((flags&FWIDTH) && (width > slen)) { + width -= (int)slen; + if (!(flags&FMINUS)) { + CHECK(width); + while (width--) { + buf[blen++] = ' '; + } + } + CHECK(len); + memcpy(&buf[blen], RSTRING_PTR(str), len); + blen += len; + if (flags&FMINUS) { + CHECK(width); + while (width--) { + buf[blen++] = ' '; + } + } + break; + } + } + PUSH(RSTRING_PTR(str), len); + } + break; + + case 'd': + case 'i': + case 'o': + case 'x': + case 'X': + case 'b': + case 'B': + case 'u': { + mrb_value val = GETARG(); + char fbuf[32], nbuf[64], *s; + const char *prefix = NULL; + int sign = 0, dots = 0; + char sc = 0; + mrb_int v = 0, org_v = 0; + int base; + mrb_int len; + + switch (*p) { + case 'd': + case 'i': + case 'u': + sign = 1; break; + case 'o': + case 'x': + case 'X': + case 'b': + case 'B': + if (flags&(FPLUS|FSPACE)) sign = 1; + break; + default: + break; + } + if (flags & FSHARP) { + switch (*p) { + case 'o': prefix = "0"; break; + case 'x': prefix = "0x"; break; + case 'X': prefix = "0X"; break; + case 'b': prefix = "0b"; break; + case 'B': prefix = "0B"; break; + default: break; + } + } + + bin_retry: + switch (mrb_type(val)) { + case MRB_TT_FLOAT: + if (FIXABLE(mrb_float(val))) { + val = mrb_fixnum_value((mrb_int)mrb_float(val)); + goto bin_retry; + } + val = mrb_flo_to_fixnum(mrb, val); + if (mrb_fixnum_p(val)) goto bin_retry; + break; + case MRB_TT_STRING: + val = mrb_str_to_inum(mrb, val, 0, TRUE); + goto bin_retry; + case MRB_TT_FIXNUM: + v = mrb_fixnum(val); + break; + default: + val = mrb_Integer(mrb, val); + goto bin_retry; + } + + switch (*p) { + case 'o': + base = 8; break; + case 'x': + case 'X': + base = 16; break; + case 'b': + case 'B': + base = 2; break; + case 'u': + case 'd': + case 'i': + default: + base = 10; break; + } + + if (base == 2) { + org_v = v; + if ( v < 0 && !sign ) { + val = mrb_fix2binstr(mrb, mrb_fixnum_value(v), base); + dots = 1; + } + else { + val = mrb_fixnum_to_str(mrb, mrb_fixnum_value(v), base); + } + v = mrb_fixnum(mrb_str_to_inum(mrb, val, 10, 0/*Qfalse*/)); + } + if (sign) { + char c = *p; + if (c == 'i') c = 'd'; /* %d and %i are identical */ + if (base == 2) c = 'd'; + if (v < 0) { + v = -v; + sc = '-'; + width--; + } + else if (flags & FPLUS) { + sc = '+'; + width--; + } + else if (flags & FSPACE) { + sc = ' '; + width--; + } + snprintf(fbuf, sizeof(fbuf), "%%l%c", c); + snprintf(nbuf, sizeof(nbuf), fbuf, v); + s = nbuf; + } + else { + char c = *p; + if (c == 'X') c = 'x'; + if (base == 2) c = 'd'; + s = nbuf; + if (v < 0) { + dots = 1; + } + snprintf(fbuf, sizeof(fbuf), "%%l%c", c); + snprintf(++s, sizeof(nbuf) - 1, fbuf, v); + if (v < 0) { + char d; + + s = remove_sign_bits(s, base); + switch (base) { + case 16: d = 'f'; break; + case 8: d = '7'; break; + case 2: d = '1'; break; + default: d = 0; break; + } + + if (d && *s != d) { + *--s = d; + } + } + } + { + size_t size; + size = strlen(s); + /* PARANOID: assert(size <= MRB_INT_MAX) */ + len = (mrb_int)size; + } + + if (dots) { + prec -= 2; + width -= 2; + } + + if (*p == 'X') { + char *pp = s; + int c; + while ((c = (int)(unsigned char)*pp) != 0) { + *pp = toupper(c); + pp++; + } + } + + if (prefix && !prefix[1]) { /* octal */ + if (dots) { + prefix = NULL; + } + else if (len == 1 && *s == '0') { + len = 0; + if (flags & FPREC) prec--; + } + else if ((flags & FPREC) && (prec > len)) { + prefix = NULL; + } + } + else if (len == 1 && *s == '0') { + prefix = NULL; + } + + if (prefix) { + size_t size; + size = strlen(prefix); + /* PARANOID: assert(size <= MRB_INT_MAX). + * this check is absolutely paranoid. */ + width -= (mrb_int)size; + } + + if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) { + prec = width; + width = 0; + } + else { + if (prec < len) { + if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0; + prec = len; + } + width -= prec; + } + + if (!(flags&FMINUS)) { + CHECK(width); + while (width-- > 0) { + buf[blen++] = ' '; + } + } + + if (sc) PUSH(&sc, 1); + + if (prefix) { + int plen = (int)strlen(prefix); + PUSH(prefix, plen); + } + CHECK(prec - len); + if (dots) PUSH("..", 2); + + if (v < 0 || (base == 2 && org_v < 0)) { + char c = sign_bits(base, p); + while (len < prec--) { + buf[blen++] = c; + } + } + else if ((flags & (FMINUS|FPREC)) != FMINUS) { + char c = '0'; + while (len < prec--) { + buf[blen++] = c; + } + } + + PUSH(s, len); + CHECK(width); + while (width-- > 0) { + buf[blen++] = ' '; + } + } + break; + + case 'f': + case 'g': + case 'G': + case 'e': + case 'E': + case 'a': + case 'A': { + mrb_value val = GETARG(); + double fval; + int i, need = 6; + char fbuf[32]; + + fval = mrb_float(mrb_Float(mrb, val)); + if (isnan(fval) || isinf(fval)) { + const char *expr; + const int elen = 3; + + if (isnan(fval)) { + expr = "NaN"; + } + else { + expr = "Inf"; + } + need = elen; + if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS)) + need++; + if ((flags & FWIDTH) && need < width) + need = width; + + CHECK(need + 1); + n = snprintf(&buf[blen], need + 1, "%*s", need, ""); + if (flags & FMINUS) { + if (!isnan(fval) && fval < 0.0) + buf[blen++] = '-'; + else if (flags & FPLUS) + buf[blen++] = '+'; + else if (flags & FSPACE) + blen++; + memcpy(&buf[blen], expr, elen); + } + else { + if (!isnan(fval) && fval < 0.0) + buf[blen + need - elen - 1] = '-'; + else if (flags & FPLUS) + buf[blen + need - elen - 1] = '+'; + else if ((flags & FSPACE) && need > width) + blen++; + memcpy(&buf[blen + need - elen], expr, elen); + } + blen += strlen(&buf[blen]); + break; + } + + fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec); + need = 0; + if (*p != 'e' && *p != 'E') { + i = INT_MIN; + frexp(fval, &i); + if (i > 0) + need = BIT_DIGITS(i); + } + need += (flags&FPREC) ? prec : 6; + if ((flags&FWIDTH) && need < width) + need = width; + need += 20; + + CHECK(need); + n = snprintf(&buf[blen], need, fbuf, fval); + blen += n; + } + break; + } + flags = FNONE; + } + + sprint_exit: +#if 0 + /* XXX - We cannot validate the number of arguments if (digit)$ style used. + */ + if (posarg >= 0 && nextarg < argc) { + const char *mesg = "too many arguments for format string"; + if (mrb_test(ruby_debug)) mrb_raise(mrb, E_ARGUMENT_ERROR, mesg); + if (mrb_test(ruby_verbose)) mrb_warn("%s", mesg); + } +#endif + mrb_str_resize(mrb, result, blen); + + return result; +} + +static void +fmt_setup(char *buf, size_t size, int c, int flags, mrb_int width, mrb_int prec) +{ + char *end = buf + size; + int n; + + *buf++ = '%'; + if (flags & FSHARP) *buf++ = '#'; + if (flags & FPLUS) *buf++ = '+'; + if (flags & FMINUS) *buf++ = '-'; + if (flags & FZERO) *buf++ = '0'; + if (flags & FSPACE) *buf++ = ' '; + + if (flags & FWIDTH) { + n = snprintf(buf, end - buf, "%d", (int)width); + buf += n; + } + + if (flags & FPREC) { + n = snprintf(buf, end - buf, ".%d", (int)prec); + buf += n; + } + + *buf++ = c; + *buf = '\0'; +} diff --git a/mrbgems/mruby-sprintf/test/sprintf.rb b/mrbgems/mruby-sprintf/test/sprintf.rb new file mode 100644 index 000000000..52e94fb83 --- /dev/null +++ b/mrbgems/mruby-sprintf/test/sprintf.rb @@ -0,0 +1,3 @@ +## +# Kernel#sprintf Kernel#format Test + diff --git a/mrbgems/mruby-string-ext/mrbgem.rake b/mrbgems/mruby-string-ext/mrbgem.rake new file mode 100644 index 000000000..83db97eb4 --- /dev/null +++ b/mrbgems/mruby-string-ext/mrbgem.rake @@ -0,0 +1,4 @@ +MRuby::Gem::Specification.new('mruby-string-ext') do |spec| + spec.license = 'MIT' + spec.authors = 'mruby developers' +end diff --git a/mrbgems/mruby-string-ext/mrblib/string.rb b/mrbgems/mruby-string-ext/mrblib/string.rb new file mode 100644 index 000000000..142a63882 --- /dev/null +++ b/mrbgems/mruby-string-ext/mrblib/string.rb @@ -0,0 +1,38 @@ +class String + def lstrip + a = 0 + z = self.size - 1 + a += 1 while " \f\n\r\t\v".include?(self[a]) and a <= z + (z >= 0) ? self[a..z] : "" + end + + def rstrip + a = 0 + z = self.size - 1 + z -= 1 while " \f\n\r\t\v\0".include?(self[z]) and a <= z + (z >= 0) ? self[a..z] : "" + end + + def strip + a = 0 + z = self.size - 1 + a += 1 while " \f\n\r\t\v".include?(self[a]) and a <= z + z -= 1 while " \f\n\r\t\v\0".include?(self[z]) and a <= z + (z >= 0) ? self[a..z] : "" + end + + def lstrip! + s = self.lstrip + (s == self) ? nil : self.replace(s) + end + + def rstrip! + s = self.rstrip + (s == self) ? nil : self.replace(s) + end + + def strip! + s = self.strip + (s == self) ? nil : self.replace(s) + end +end diff --git a/mrbgems/mruby-string-ext/src/string.c b/mrbgems/mruby-string-ext/src/string.c new file mode 100644 index 000000000..b10b021a2 --- /dev/null +++ b/mrbgems/mruby-string-ext/src/string.c @@ -0,0 +1,31 @@ +#include "mruby.h" +#include "mruby/string.h" + +static mrb_value +mrb_str_getbyte(mrb_state *mrb, mrb_value str) +{ + mrb_int pos; + mrb_get_args(mrb, "i", &pos); + + if (pos < 0) + pos += RSTRING_LEN(str); + if (pos < 0 || RSTRING_LEN(str) <= pos) + return mrb_nil_value(); + + return mrb_fixnum_value((unsigned char)RSTRING_PTR(str)[pos]); +} + + +void +mrb_mruby_string_ext_gem_init(mrb_state* mrb) +{ + struct RClass * s = mrb->string_class; + + mrb_define_method(mrb, s, "dump", mrb_str_dump, ARGS_NONE()); + mrb_define_method(mrb, s, "getbyte", mrb_str_getbyte, ARGS_REQ(1)); +} + +void +mrb_mruby_string_ext_gem_final(mrb_state* mrb) +{ +} diff --git a/mrbgems/mruby-string-ext/test/string.rb b/mrbgems/mruby-string-ext/test/string.rb new file mode 100644 index 000000000..eaff81890 --- /dev/null +++ b/mrbgems/mruby-string-ext/test/string.rb @@ -0,0 +1,72 @@ +## +# String(Ext) Test + +assert('String#getbyte') do + str1 = "hello" + bytes1 = [104, 101, 108, 108, 111] + assert_equal bytes1[0], str1.getbyte(0) + assert_equal bytes1[-1], str1.getbyte(-1) + assert_equal bytes1[6], str1.getbyte(6) + + str2 = "\xFF" + bytes2 = [0xFF] + assert_equal bytes2[0], str2.getbyte(0) +end + +assert('String#dump') do + "foo".dump == "\"foo\"" +end + +assert('String#strip') do + s = " abc " + s.strip + "".strip == "" and " \t\r\n\f\v".strip == "" and + "\0a\0".strip == "\0a" and + "abc".strip == "abc" and + " abc".strip == "abc" and + "abc ".strip == "abc" and + " abc ".strip == "abc" and + s == " abc " +end + +assert('String#lstrip') do + s = " abc " + s.lstrip + "".lstrip == "" and " \t\r\n\f\v".lstrip == "" and + "\0a\0".lstrip == "\0a\0" and + "abc".lstrip == "abc" and + " abc".lstrip == "abc" and + "abc ".lstrip == "abc " and + " abc ".lstrip == "abc " and + s == " abc " +end + +assert('String#rstrip') do + s = " abc " + s.rstrip + "".rstrip == "" and " \t\r\n\f\v".rstrip == "" and + "\0a\0".rstrip == "\0a" and + "abc".rstrip == "abc" and + " abc".rstrip == " abc" and + "abc ".rstrip == "abc" and + " abc ".rstrip == " abc" and + s == " abc " +end + +assert('String#strip!') do + s = " abc " + t = "abc" + s.strip! == "abc" and s == "abc" and t.strip! == nil +end + +assert('String#lstrip!') do + s = " abc " + t = "abc " + s.lstrip! == "abc " and s == "abc " and t.lstrip! == nil +end + +assert('String#rstrip!') do + s = " abc " + t = " abc" + s.rstrip! == " abc" and s == " abc" and t.rstrip! == nil +end diff --git a/mrbgems/mruby-struct/src/struct.c b/mrbgems/mruby-struct/src/struct.c index a49d8244b..20ea8b5c5 100644 --- a/mrbgems/mruby-struct/src/struct.c +++ b/mrbgems/mruby-struct/src/struct.c @@ -49,7 +49,7 @@ mrb_struct_iv_get(mrb_state *mrb, mrb_value c, const char *name) mrb_value mrb_struct_s_members(mrb_state *mrb, mrb_value klass) { - mrb_value members = struct_ivar_get(mrb, klass, mrb_intern(mrb, "__members__")); + mrb_value members = struct_ivar_get(mrb, klass, mrb_intern2(mrb, "__members__", 11)); if (mrb_nil_p(members)) { mrb_raise(mrb, E_TYPE_ERROR, "uninitialized struct"); @@ -66,8 +66,9 @@ mrb_struct_members(mrb_state *mrb, mrb_value s) mrb_value members = mrb_struct_s_members(mrb, mrb_obj_value(mrb_obj_class(mrb, s))); if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct")) { if (RSTRUCT_LEN(s) != RARRAY_LEN(members)) { - mrb_raisef(mrb, E_TYPE_ERROR, "struct size differs (%ld required %ld given)", - RARRAY_LEN(members), RSTRUCT_LEN(s)); + mrb_raisef(mrb, E_TYPE_ERROR, + "struct size differs (%S required %S given)", + mrb_fixnum_value(RARRAY_LEN(members)), mrb_fixnum_value(RSTRUCT_LEN(s))); } } return members; @@ -112,7 +113,7 @@ mrb_value mrb_struct_getmember(mrb_state *mrb, mrb_value obj, mrb_sym id) { mrb_value members, slot, *ptr, *ptr_members; - long i, len; + mrb_int i, len; ptr = RSTRUCT_PTR(obj); members = mrb_struct_members(mrb, obj); @@ -124,7 +125,7 @@ mrb_struct_getmember(mrb_state *mrb, mrb_value obj, mrb_sym id) return ptr[i]; } } - mrb_raisef(mrb, E_NAME_ERROR, "%s is not struct member", mrb_sym2name(mrb, id)); + mrb_raisef(mrb, E_NAME_ERROR, "%S is not struct member", mrb_sym2str(mrb, id)); return mrb_nil_value(); /* not reached */ } @@ -166,7 +167,7 @@ mrb_id_attrset(mrb_state *mrb, mrb_sym id) { const char *name; char *buf; - int len; + size_t len; mrb_sym mid; name = mrb_sym2name_len(mrb, id, &len); @@ -184,7 +185,8 @@ static mrb_value mrb_struct_set(mrb_state *mrb, mrb_value obj, mrb_value val) { const char *name; - int i, len; + int i; + size_t len; mrb_sym mid; mrb_value members, slot, *ptr, *ptr_members; @@ -202,8 +204,8 @@ mrb_struct_set(mrb_state *mrb, mrb_value obj, mrb_value val) return ptr[i] = val; } } - mrb_raisef(mrb, E_NAME_ERROR, "`%s' is not a struct member", - mrb_sym2name(mrb, mid)); + mrb_raisef(mrb, E_NAME_ERROR, "`%S' is not a struct member", + mrb_sym2str(mrb, mid)); return mrb_nil_value(); /* not reached */ } @@ -236,7 +238,7 @@ make_struct(mrb_state *mrb, mrb_value name, mrb_value members, struct RClass * k { mrb_value nstr, *ptr_members; mrb_sym id; - long i, len; + mrb_int i, len; struct RClass *c; if (mrb_nil_p(name)) { @@ -247,7 +249,7 @@ make_struct(mrb_state *mrb, mrb_value name, mrb_value members, struct RClass * k name = mrb_str_to_str(mrb, name); id = mrb_to_id(mrb, name); if (!mrb_is_const_id(id)) { - mrb_raisef(mrb, E_NAME_ERROR, "identifier %s needs to be constant", mrb_string_value_ptr(mrb, name)); + mrb_raisef(mrb, E_NAME_ERROR, "identifier %S needs to be constant", name); } if (mrb_const_defined_at(mrb, klass, id)) { mrb_warn("redefining constant Struct::%s", mrb_string_value_ptr(mrb, name)); @@ -257,7 +259,7 @@ make_struct(mrb_state *mrb, mrb_value name, mrb_value members, struct RClass * k } MRB_SET_INSTANCE_TT(c, MRB_TT_ARRAY); nstr = mrb_obj_value(c); - mrb_iv_set(mrb, nstr, mrb_intern(mrb, "__members__"), members); + mrb_iv_set(mrb, nstr, mrb_intern2(mrb, "__members__", 11), members); mrb_define_class_method(mrb, c, "new", mrb_instance_new, ARGS_ANY()); mrb_define_class_method(mrb, c, "[]", mrb_instance_new, ARGS_ANY()); @@ -288,7 +290,7 @@ mrb_struct_define(mrb_state *mrb, const char *name, ...) char *mem; if (!name) nm = mrb_nil_value(); - else nm = mrb_str_new2(mrb, name); + else nm = mrb_str_new_cstr(mrb, name); ary = mrb_ary_new(mrb); va_start(ar, name); @@ -341,7 +343,7 @@ mrb_struct_s_def(mrb_state *mrb, mrb_value klass) mrb_value name, rest; mrb_value *pargv; int argcnt; - long i; + mrb_int i; mrb_value b, st; mrb_sym id; mrb_value *argv; @@ -352,8 +354,8 @@ mrb_struct_s_def(mrb_state *mrb, mrb_value klass) mrb_get_args(mrb, "*&", &argv, &argc, &b); if (argc == 0) { /* special case to avoid crash */ rest = mrb_ary_new(mrb); - } - else { + } + else { if (argc > 0) name = argv[0]; if (argc > 1) rest = argv[1]; if (mrb_array_p(rest)) { @@ -378,7 +380,7 @@ mrb_struct_s_def(mrb_state *mrb, mrb_value klass) id = mrb_to_id(mrb, RARRAY_PTR(rest)[i]); RARRAY_PTR(rest)[i] = mrb_symbol_value(id); } - } + } st = make_struct(mrb, name, rest, struct_class(mrb)); if (!mrb_nil_p(b)) { mrb_funcall(mrb, b, "call", 1, &st); @@ -392,7 +394,7 @@ num_members(mrb_state *mrb, struct RClass *klass) { mrb_value members; - members = struct_ivar_get(mrb, mrb_obj_value(klass), mrb_intern(mrb, "__members__")); + members = struct_ivar_get(mrb, mrb_obj_value(klass), mrb_intern2(mrb, "__members__", 11)); if (!mrb_array_p(members)) { mrb_raise(mrb, E_TYPE_ERROR, "broken members"); } @@ -444,7 +446,7 @@ inspect_struct(mrb_state *mrb, mrb_value s, int recur) const char *cn = mrb_class_name(mrb, mrb_obj_class(mrb, s)); mrb_value members, str = mrb_str_new(mrb, "#<struct ", 9); mrb_value *ptr, *ptr_members; - long i, len; + mrb_int i, len; if (cn) { mrb_str_append(mrb, str, mrb_str_new_cstr(mrb, cn)); @@ -471,7 +473,7 @@ inspect_struct(mrb_state *mrb, mrb_value s, int recur) id = mrb_symbol(slot); if (mrb_is_local_id(id) || mrb_is_const_id(id)) { const char *name; - int len; + size_t len; name = mrb_sym2name_len(mrb, id, &len); mrb_str_append(mrb, str, mrb_str_new(mrb, name, len)); @@ -531,7 +533,7 @@ static mrb_value mrb_struct_aref_id(mrb_state *mrb, mrb_value s, mrb_sym id) { mrb_value *ptr, members, *ptr_members; - long i, len; + mrb_int i, len; ptr = RSTRUCT_PTR(s); members = mrb_struct_members(mrb, s); @@ -542,7 +544,7 @@ mrb_struct_aref_id(mrb_state *mrb, mrb_value s, mrb_sym id) return ptr[i]; } } - mrb_raisef(mrb, E_NAME_ERROR, "no member '%s' in struct", mrb_sym2name(mrb, id)); + mrb_raisef(mrb, E_NAME_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id)); return mrb_nil_value(); /* not reached */ } @@ -568,7 +570,7 @@ mrb_struct_aref_id(mrb_state *mrb, mrb_value s, mrb_sym id) mrb_value mrb_struct_aref_n(mrb_state *mrb, mrb_value s, mrb_value idx) { - long i; + mrb_int i; if (mrb_string_p(idx) || mrb_symbol_p(idx)) { return mrb_struct_aref_id(mrb, s, mrb_to_id(mrb, idx)); @@ -577,11 +579,13 @@ mrb_struct_aref_n(mrb_state *mrb, mrb_value s, mrb_value idx) i = mrb_fixnum(idx); if (i < 0) i = RSTRUCT_LEN(s) + i; if (i < 0) - mrb_raisef(mrb, E_INDEX_ERROR, "offset %ld too small for struct(size:%ld)", - i, RSTRUCT_LEN(s)); + mrb_raisef(mrb, E_INDEX_ERROR, + "offset %S too small for struct(size:%S)", + mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s))); if (RSTRUCT_LEN(s) <= i) - mrb_raisef(mrb, E_INDEX_ERROR, "offset %ld too large for struct(size:%ld)", - i, RSTRUCT_LEN(s)); + mrb_raisef(mrb, E_INDEX_ERROR, + "offset %S too large for struct(size:%S)", + mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s))); return RSTRUCT_PTR(s)[i]; } @@ -598,13 +602,14 @@ static mrb_value mrb_struct_aset_id(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val) { mrb_value members, *ptr, *ptr_members; - long i, len; + mrb_int i, len; members = mrb_struct_members(mrb, s); len = RARRAY_LEN(members); if (RSTRUCT_LEN(s) != len) { - mrb_raisef(mrb, E_TYPE_ERROR, "struct size differs (%ld required %ld given)", - len, RSTRUCT_LEN(s)); + mrb_raisef(mrb, E_TYPE_ERROR, + "struct size differs (%S required %S given)", + mrb_fixnum_value(len), mrb_fixnum_value(RSTRUCT_LEN(s))); } ptr = RSTRUCT_PTR(s); ptr_members = RARRAY_PTR(members); @@ -614,7 +619,7 @@ mrb_struct_aset_id(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val) return val; } } - mrb_raisef(mrb, E_NAME_ERROR, "no member '%s' in struct", mrb_sym2name(mrb, id)); + mrb_raisef(mrb, E_NAME_ERROR, "no member '%S' in struct", mrb_sym2str(mrb, id)); return val; /* not reach */ } @@ -643,7 +648,7 @@ mrb_struct_aset_id(mrb_state *mrb, mrb_value s, mrb_sym id, mrb_value val) mrb_value mrb_struct_aset(mrb_state *mrb, mrb_value s) { - long i; + mrb_int i; mrb_value idx; mrb_value val; @@ -656,12 +661,14 @@ mrb_struct_aset(mrb_state *mrb, mrb_value s) i = mrb_fixnum(idx); if (i < 0) i = RSTRUCT_LEN(s) + i; if (i < 0) { - mrb_raisef(mrb, E_INDEX_ERROR, "offset %ld too small for struct(size:%ld)", - i, RSTRUCT_LEN(s)); + mrb_raisef(mrb, E_INDEX_ERROR, + "offset %S too small for struct(size:%S)", + mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s))); } if (RSTRUCT_LEN(s) <= i) { - mrb_raisef(mrb, E_INDEX_ERROR, "offset %ld too large for struct(size:%ld)", - i, RSTRUCT_LEN(s)); + mrb_raisef(mrb, E_INDEX_ERROR, + "offset %S too large for struct(size:%S)", + mrb_fixnum_value(i), mrb_fixnum_value(RSTRUCT_LEN(s))); } return RSTRUCT_PTR(s)[i] = val; } @@ -689,22 +696,35 @@ mrb_struct_equal(mrb_state *mrb, mrb_value s) { mrb_value s2; mrb_value *ptr, *ptr2; - long i, len; + mrb_int i, len; + mrb_bool equal_p; mrb_get_args(mrb, "o", &s2); - if (mrb_obj_equal(mrb, s, s2)) return mrb_true_value(); - if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct")) return mrb_false_value(); - if (mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) return mrb_false_value(); - if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) { + if (mrb_obj_equal(mrb, s, s2)) { + equal_p = 1; + } + else if (!strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s)), "Struct") || + mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) { + equal_p = 0; + } + else if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) { mrb_bug("inconsistent struct"); /* should never happen */ + equal_p = 0; /* This substuture is just to suppress warnings. never called. */ } - ptr = RSTRUCT_PTR(s); - ptr2 = RSTRUCT_PTR(s2); - len = RSTRUCT_LEN(s); - for (i=0; i<len; i++) { - if (!mrb_equal(mrb, ptr[i], ptr2[i])) return mrb_false_value(); + else { + ptr = RSTRUCT_PTR(s); + ptr2 = RSTRUCT_PTR(s2); + len = RSTRUCT_LEN(s); + equal_p = 1; + for (i=0; i<len; i++) { + if (!mrb_equal(mrb, ptr[i], ptr2[i])) { + equal_p = 0; + break; + } + } } - return mrb_true_value(); + + return mrb_bool_value(equal_p); } /* 15.2.18.4.12(x) */ @@ -720,23 +740,35 @@ mrb_struct_eql(mrb_state *mrb, mrb_value s) { mrb_value s2; mrb_value *ptr, *ptr2; - long i, len; + mrb_int i, len; + mrb_bool eql_p; mrb_get_args(mrb, "o", &s2); - if (mrb_obj_equal(mrb, s, s2)) return mrb_true_value(); - if (strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s2)), "Struct")) return mrb_false_value(); - if (mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) return mrb_false_value(); - if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) { + if (mrb_obj_equal(mrb, s, s2)) { + eql_p = 1; + } + else if (strcmp(mrb_class_name(mrb, mrb_obj_class(mrb, s2)), "Struct") || + mrb_obj_class(mrb, s) != mrb_obj_class(mrb, s2)) { + eql_p = 0; + } + else if (RSTRUCT_LEN(s) != RSTRUCT_LEN(s2)) { mrb_bug("inconsistent struct"); /* should never happen */ + eql_p = 0; /* This substuture is just to suppress warnings. never called. */ } - - ptr = RSTRUCT_PTR(s); - ptr2 = RSTRUCT_PTR(s2); - len = RSTRUCT_LEN(s); - for (i=0; i<len; i++) { - if (!mrb_eql(mrb, ptr[i], ptr2[i])) return mrb_false_value(); + else { + ptr = RSTRUCT_PTR(s); + ptr2 = RSTRUCT_PTR(s2); + len = RSTRUCT_LEN(s); + eql_p = 1; + for (i=0; i<len; i++) { + if (!mrb_eql(mrb, ptr[i], ptr2[i])) { + eql_p = 0; + break; + } + } } - return mrb_true_value(); + + return mrb_bool_value(eql_p); } /* diff --git a/mrbgems/mruby-time/src/time.c b/mrbgems/mruby-time/src/time.c index ecc9090f1..0ffc0e6f8 100644 --- a/mrbgems/mruby-time/src/time.c +++ b/mrbgems/mruby-time/src/time.c @@ -6,7 +6,6 @@ #include "mruby.h" -#include <string.h> #include <stdio.h> #include <time.h> #include "mruby/class.h" @@ -87,11 +86,6 @@ timegm(struct tm *tm) * second level. Also, there are only 2 timezones, namely UTC and LOCAL. */ -#ifndef mrb_bool_value -#define mrb_bool_value(val) ((val) ? mrb_true_value() : mrb_false_value()) -#endif - - enum mrb_timezone { MRB_TIMEZONE_NONE = 0, MRB_TIMEZONE_UTC = 1, @@ -130,7 +124,7 @@ mrb_time_free(mrb_state *mrb, void *ptr) static struct mrb_data_type mrb_time_type = { "Time", mrb_time_free }; /** Updates the datetime of a mrb_time based on it's timezone and -seconds setting. Returns self on cussess, NULL of failure. */ +seconds setting. Returns self on success, NULL of failure. */ static struct mrb_time* mrb_time_update_datetime(struct mrb_time *self) { @@ -242,8 +236,8 @@ mrb_time_at(mrb_state *mrb, mrb_value self) static struct mrb_time* time_mktime(mrb_state *mrb, mrb_int ayear, mrb_int amonth, mrb_int aday, - mrb_int ahour, mrb_int amin, mrb_int asec, mrb_int ausec, - enum mrb_timezone timezone) + mrb_int ahour, mrb_int amin, mrb_int asec, mrb_int ausec, + enum mrb_timezone timezone) { time_t nowsecs; struct tm nowtime = { 0 }; @@ -278,7 +272,7 @@ mrb_time_gm(mrb_state *mrb, mrb_value self) mrb_get_args(mrb, "i|iiiiii", &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec); return mrb_time_wrap(mrb, mrb_class_ptr(self), - time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_UTC)); + time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_UTC)); } @@ -292,7 +286,7 @@ mrb_time_local(mrb_state *mrb, mrb_value self) mrb_get_args(mrb, "i|iiiiii", &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec); return mrb_time_wrap(mrb, mrb_class_ptr(self), - time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_LOCAL)); + time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_LOCAL)); } @@ -301,15 +295,14 @@ mrb_time_eq(mrb_state *mrb, mrb_value self) { mrb_value other; struct mrb_time *tm1, *tm2; + mrb_bool eq_p; mrb_get_args(mrb, "o", &other); tm1 = (struct mrb_time *)mrb_get_datatype(mrb, self, &mrb_time_type); tm2 = (struct mrb_time *)mrb_get_datatype(mrb, other, &mrb_time_type); - if (!tm1 || !tm2) return mrb_false_value(); - if (tm1->sec == tm2->sec && tm1->usec == tm2->usec) { - return mrb_true_value(); - } - return mrb_false_value(); + eq_p = tm1 && tm2 && tm1->sec == tm2->sec && tm1->usec == tm2->usec; + + return mrb_bool_value(eq_p); } static mrb_value @@ -437,10 +430,10 @@ mrb_time_asctime(mrb_state *mrb, mrb_value self) if (!tm) return mrb_nil_value(); d = &tm->datetime; len = snprintf(buf, sizeof(buf), "%s %s %02d %02d:%02d:%02d %s%d", - wday_names[d->tm_wday], mon_names[d->tm_mon], d->tm_mday, - d->tm_hour, d->tm_min, d->tm_sec, - tm->timezone == MRB_TIMEZONE_UTC ? "UTC " : "", - d->tm_year + 1900); + wday_names[d->tm_wday], mon_names[d->tm_mon], d->tm_mday, + d->tm_hour, d->tm_min, d->tm_sec, + tm->timezone == MRB_TIMEZONE_UTC ? "UTC " : "", + d->tm_year + 1900); return mrb_str_new(mrb, buf, len); } @@ -528,9 +521,11 @@ mrb_time_initialize(mrb_state *mrb, mrb_value self) if (tm) { mrb_time_free(mrb, tm); } + DATA_TYPE(self) = &mrb_time_type; + DATA_PTR(self) = NULL; n = mrb_get_args(mrb, "|iiiiiii", - &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec); + &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec); if (n == 0) { tm = current_mrb_time(mrb); } @@ -538,7 +533,6 @@ mrb_time_initialize(mrb_state *mrb, mrb_value self) tm = time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_LOCAL); } DATA_PTR(self) = tm; - DATA_TYPE(self) = &mrb_time_type; return self; } |
