repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/binding.rb
opal/corelib/binding.rb
# backtick_javascript: true class ::Binding # @private def initialize(jseval, scope_variables = [], receiver = undefined, source_location = nil) @jseval, @scope_variables, @receiver, @source_location = \ jseval, scope_variables, receiver, source_location receiver = js_eval('self') if `typeof receiver === "undefined"` end def js_eval(*args) if @jseval @jseval.call(*args) else ::Kernel.raise 'Evaluation on a Proc#binding is not supported' end end def local_variable_get(symbol) js_eval(symbol) rescue ::Exception ::Kernel.raise ::NameError, "local variable `#{symbol}' is not defined for #{inspect}" end def local_variable_set(symbol, value) `Opal.Binding.tmp_value = value` js_eval("#{symbol} = Opal.Binding.tmp_value") `delete Opal.Binding.tmp_value` value end def local_variables @scope_variables end def local_variable_defined?(value) @scope_variables.include?(value) end def eval(str, file = nil, line = nil) return receiver if str == 'self' ::Kernel.eval(str, self, file, line) end attr_reader :receiver, :source_location end module ::Kernel def binding ::Kernel.raise "Opal doesn't support dynamic calls to binding" end end TOPLEVEL_BINDING = ::Binding.new( %x{ function(js) { return (new Function("self", "return " + js))(self); } }, [], self, ['<main>', 0] )
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/kernel.rb
opal/corelib/kernel.rb
# helpers: truthy, coerce_to, respond_to, Opal, deny_frozen_access, freeze, freeze_props, jsid, each_ivar, slice # use_strict: true # backtick_javascript: true module ::Kernel def =~(obj) false end def !~(obj) !(self =~ obj) end def ===(other) object_id == other.object_id || self == other end def <=>(other) %x{ // set guard for infinite recursion self.$$comparable = true; var x = #{self == other}; if (x && x !== nil) { return 0; } return nil; } end def method(name) %x{ var meth = self[$jsid(name)]; if (meth && !meth.$$stub) { return #{::Method.new(self, `meth.$$owner || #{self.class}`, `meth`, name)}; } var respond_to_missing = self['$respond_to_missing?']; if (respond_to_missing.$$pristine || !respond_to_missing.call(self, name, true)) { #{::Kernel.raise ::NameError.new("undefined method `#{name}' for class `#{self.class}'", name)}; } meth = function wrapper() { var method_missing = self.$method_missing; if (method_missing == null) { #{::Kernel.raise ::NameError.new("undefined method `#{name}' for class `#{self.class}'", name)}; } method_missing.$$p = wrapper.$$p; return method_missing.apply(self, [name].concat($slice(arguments))); }; meth.$$parameters = [['rest']] meth.$$arity = -1; return #{::Method.new(self, self.class, `meth`, name)}; } end def methods(all = true) %x{ if ($truthy(#{all})) { return Opal.methods(self); } else { return Opal.own_methods(self); } } end def public_methods(all = true) %x{ if ($truthy(#{all})) { return Opal.methods(self); } else { return Opal.receiver_methods(self); } } end def Array(object) %x{ var coerced; if (object === nil) { return []; } if (object.$$is_array) { return object; } coerced = #{::Opal.coerce_to?(object, ::Array, :to_ary)}; if (coerced !== nil) { return coerced; } coerced = #{::Opal.coerce_to?(object, ::Array, :to_a)}; if (coerced !== nil) { return coerced; } return [object]; } end def at_exit(&block) $__at_exit__ ||= [] $__at_exit__ << block block end def caller(start = 1, length = nil) %x{ var stack, result; stack = new Error().$backtrace(); result = []; for (var i = #{start} + 1, ii = stack.length; i < ii; i++) { if (!stack[i].match(/runtime\//)) { result.push(stack[i]); } } if (length != nil) result = result.slice(0, length); return result; } end def caller_locations(*args) caller(*args).map do |loc| ::Thread::Backtrace::Location.new(loc) end end def class `self.$$class` end def copy_instance_variables(other) %x{ var keys = Object.keys(other), i, ii, name; for (i = 0, ii = keys.length; i < ii; i++) { name = keys[i]; if (name.charAt(0) !== '$' && other.hasOwnProperty(name)) { self[name] = other[name]; } } } end def copy_singleton_methods(other) %x{ var i, name, names, length; if (other.hasOwnProperty('$$meta') && other.$$meta !== null) { var other_singleton_class = Opal.get_singleton_class(other); var self_singleton_class = Opal.get_singleton_class(self); names = Object.getOwnPropertyNames(other_singleton_class.$$prototype); for (i = 0, length = names.length; i < length; i++) { name = names[i]; if (Opal.is_method(name)) { self_singleton_class.$$prototype[name] = other_singleton_class.$$prototype[name]; } } self_singleton_class.$$const = Object.assign({}, other_singleton_class.$$const); Object.setPrototypeOf( self_singleton_class.$$prototype, Object.getPrototypeOf(other_singleton_class.$$prototype) ); } for (i = 0, names = Object.getOwnPropertyNames(other), length = names.length; i < length; i++) { name = names[i]; if (name.charAt(0) === '$' && name.charAt(1) !== '$' && other.hasOwnProperty(name)) { self[name] = other[name]; } } } end def clone(freeze: nil) unless freeze.nil? || freeze == true || freeze == false raise ArgumentError, "unexpected value for freeze: #{freeze.class}" end copy = self.class.allocate copy.copy_instance_variables(self) copy.copy_singleton_methods(self) copy.initialize_clone(self, freeze: freeze) if freeze == true || (freeze.nil? && frozen?) copy.freeze end copy end def initialize_clone(other, freeze: nil) initialize_copy(other) self end def define_singleton_method(name, method = undefined, &block) singleton_class.define_method(name, method, &block) end def dup copy = self.class.allocate copy.copy_instance_variables(self) copy.initialize_dup(self) copy end def initialize_dup(other) initialize_copy(other) end def enum_for(method = :each, *args, &block) ::Enumerator.for(self, method, *args, &block) end def equal?(other) `self === other` end def exit(status = true) $__at_exit__ ||= [] until $__at_exit__.empty? block = $__at_exit__.pop block.call end %x{ if (status.$$is_boolean) { status = status ? 0 : 1; } else { status = $coerce_to(status, #{::Integer}, 'to_int') } Opal.exit(status); } nil end def extend(*mods) %x{ if (mods.length == 0) { #{raise ::ArgumentError, 'wrong number of arguments (given 0, expected 1+)'} } $deny_frozen_access(self); var singleton = #{singleton_class}; for (var i = mods.length - 1; i >= 0; i--) { var mod = mods[i]; if (!mod.$$is_module) { #{::Kernel.raise ::TypeError, "wrong argument type #{`mod`.class} (expected Module)"}; } #{`mod`.append_features `singleton`}; #{`mod`.extend_object self}; #{`mod`.extended self}; } } self end def freeze return self if frozen? %x{ if (typeof(self) === "object") { $freeze_props(self); return $freeze(self); } return self; } end def frozen? %x{ switch (typeof(self)) { case "string": case "symbol": case "number": case "boolean": return true; case "object": case "function": return (self.$$frozen || false); default: return false; } } end def gets(*args) $stdin.gets(*args) end def hash __id__ end def initialize_copy(other) end `var inspect_stack = []` def inspect ivs = '' id = __id__ if `inspect_stack`.include? id ivs = ' ...' else `inspect_stack` << id pushed = true instance_variables.each do |i| ivar = instance_variable_get(i) inspect = Opal.inspect(ivar) ivs += " #{i}=#{inspect}" end end "#<#{self.class}:0x#{id.to_s(16)}#{ivs}>" rescue => e "#<#{self.class}:0x#{id.to_s(16)}>" ensure `inspect_stack`.pop if pushed end def instance_of?(klass) %x{ if (!klass.$$is_class && !klass.$$is_module) { #{::Kernel.raise ::TypeError, 'class or module required'}; } return self.$$class === klass; } end def instance_variable_defined?(name) name = ::Opal.instance_variable_name!(name) `Opal.hasOwnProperty.call(self, name.substr(1))` end def instance_variable_get(name) name = ::Opal.instance_variable_name!(name) %x{ var ivar = self[Opal.ivar(name.substr(1))]; return ivar == null ? nil : ivar; } end def instance_variable_set(name, value) `$deny_frozen_access(self)` name = ::Opal.instance_variable_name!(name) `self[Opal.ivar(name.substr(1))] = value` end def remove_instance_variable(name) name = ::Opal.instance_variable_name!(name) %x{ var key = Opal.ivar(name.substr(1)), val; if (self.hasOwnProperty(key)) { val = self[key]; delete self[key]; return val; } } ::Kernel.raise ::NameError, "instance variable #{name} not defined" end def instance_variables %x{ var result = [], name; $each_ivar(self, function(name) { if (name[name.length-1] === '$') { name = name.slice(0, name.length - 1); } result.push('@' + name); }); return result; } end def Integer(value, base = undefined, exception: true) %x{ var i, str, base_digits; exception = $truthy(#{exception}); if (!value.$$is_string) { if (base !== undefined) { if (exception) { #{::Kernel.raise ::ArgumentError, 'base specified for non string value'} } else { return nil; } } if (value === nil) { if (exception) { #{::Kernel.raise ::TypeError, "can't convert nil into Integer"} } else { return nil; } } if (value.$$is_number) { if (value === Infinity || value === -Infinity || isNaN(value)) { if (exception) { #{::Kernel.raise ::FloatDomainError, value} } else { return nil; } } return Math.floor(value); } if (#{value.respond_to?(:to_int)}) { i = #{value.to_int}; if (Opal.is_a(i, #{::Integer})) { return i; } } if (#{value.respond_to?(:to_i)}) { i = #{value.to_i}; if (Opal.is_a(i, #{::Integer})) { return i; } } if (exception) { #{::Kernel.raise ::TypeError, "can't convert #{value.class} into Integer"} } else { return nil; } } if (value === "0") { return 0; } if (base === undefined) { base = 0; } else { base = $coerce_to(base, #{::Integer}, 'to_int'); if (base === 1 || base < 0 || base > 36) { if (exception) { #{::Kernel.raise ::ArgumentError, "invalid radix #{base}"} } else { return nil; } } } str = value.toLowerCase(); str = str.replace(/(\d)_(?=\d)/g, '$1'); str = str.replace(/^(\s*[+-]?)(0[bodx]?)/, function (_, head, flag) { switch (flag) { case '0b': if (base === 0 || base === 2) { base = 2; return head; } // no-break case '0': case '0o': if (base === 0 || base === 8) { base = 8; return head; } // no-break case '0d': if (base === 0 || base === 10) { base = 10; return head; } // no-break case '0x': if (base === 0 || base === 16) { base = 16; return head; } // no-break } if (exception) { #{::Kernel.raise ::ArgumentError, "invalid value for Integer(): \"#{value}\""} } else { return nil; } }); base = (base === 0 ? 10 : base); base_digits = '0-' + (base <= 10 ? base - 1 : '9a-' + String.fromCharCode(97 + (base - 11))); if (!(new RegExp('^\\s*[+-]?[' + base_digits + ']+\\s*$')).test(str)) { if (exception) { #{::Kernel.raise ::ArgumentError, "invalid value for Integer(): \"#{value}\""} } else { return nil; } } i = parseInt(str, base); if (isNaN(i)) { if (exception) { #{::Kernel.raise ::ArgumentError, "invalid value for Integer(): \"#{value}\""} } else { return nil; } } return i; } end def Float(value, exception: true) %x{ var str; exception = $truthy(#{exception}); if (value === nil) { if (exception) { #{::Kernel.raise ::TypeError, "can't convert nil into Float"} } else { return nil; } } if (value.$$is_string) { str = value.toString(); str = str.replace(/(\d)_(?=\d)/g, '$1'); //Special case for hex strings only: if (/^\s*[-+]?0[xX][0-9a-fA-F]+\s*$/.test(str)) { return #{::Kernel.Integer(`str`)}; } if (!/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/.test(str)) { if (exception) { #{::Kernel.raise ::ArgumentError, "invalid value for Float(): \"#{value}\""} } else { return nil; } } return parseFloat(str); } if (exception) { return #{::Opal.coerce_to!(value, ::Float, :to_f)}; } else { return $coerce_to(value, #{::Float}, 'to_f'); } } end def Hash(arg) return {} if arg.nil? || arg == [] return arg if ::Hash === arg ::Opal.coerce_to!(arg, ::Hash, :to_hash) end def is_a?(klass) %x{ if (!klass.$$is_class && !klass.$$is_module) { #{::Kernel.raise ::TypeError, 'class or module required'}; } return Opal.is_a(self, klass); } end def itself self end def lambda(&block) `Opal.lambda(block)` end def load(file) file = ::Opal.coerce_to!(file, ::String, :to_str) `Opal.load(#{file})` end def loop return enum_for(:loop) { ::Float::INFINITY } unless block_given? while true begin yield rescue ::StopIteration => e return e.result end end self end def nil? false end def printf(*args) return if args.empty? io = `args[0].$$is_string` ? $stdout : args.shift io.write format(*args) nil end def proc(&block) unless block ::Kernel.raise ::ArgumentError, 'tried to create Proc object without a block' end `block.$$is_lambda = false` block end def puts(*strs) $stdout.puts(*strs) end def p(*args) args.each { |obj| $stdout.puts obj.inspect } args.length <= 1 ? args[0] : args end def print(*strs) $stdout.print(*strs) end def readline(*args) $stdin.readline(*args) end def warn(*strs, uplevel: nil) if uplevel uplevel = ::Opal.coerce_to!(uplevel, ::Integer, :to_str) ::Kernel.raise ::ArgumentError, "negative level (#{uplevel})" if uplevel < 0 location = caller(uplevel + 1, 1).first&.split(':in `')&.first location = "#{location}: " if location strs = strs.map { |s| "#{location}warning: #{s}" } end $stderr.puts(*strs) unless $VERBOSE.nil? || strs.empty? end def raise(exception = undefined, string = nil, backtrace = nil) %x{ if (exception == null && #{$!} !== nil) { throw #{$!}; } if (exception == null) { exception = #{::RuntimeError.new ''}; } else if ($respond_to(exception, '$to_str')) { exception = #{::RuntimeError.new exception.to_str}; } // using respond_to? and not an undefined check to avoid method_missing matching as true else if (exception.$$is_class && $respond_to(exception, '$exception')) { exception = #{exception.exception string}; } else if (exception.$$is_exception) { // exception is fine } else { exception = #{::TypeError.new 'exception class/object expected'}; } if (backtrace !== nil) { exception.$set_backtrace(backtrace); } if (#{$!} !== nil) { Opal.exceptions.push(#{$!}); } #{$!} = exception; throw exception; } end def rand(max = undefined) %x{ if (max === undefined) { return #{::Random::DEFAULT.rand}; } if (max.$$is_number) { if (max < 0) { max = Math.abs(max); } if (max % 1 !== 0) { max = max.$to_i(); } if (max === 0) { max = undefined; } } } ::Random::DEFAULT.rand(max) end def respond_to?(name, include_all = false) %x{ var body = self[$jsid(name)]; if (typeof(body) === "function" && !body.$$stub) { return true; } if (self['$respond_to_missing?'].$$pristine === true) { return false; } else { return #{respond_to_missing?(name, include_all)}; } } end def respond_to_missing?(method_name, include_all = false) false end ::Opal.pristine(self, :respond_to?, :respond_to_missing?) def require(file) %x{ // As Object.require refers to Kernel.require once Kernel has been loaded the String // class may not be available yet, the coercion requires both String and Array to be loaded. if (typeof #{file} !== 'string' && Opal.String && Opal.Array) { #{file = ::Opal.coerce_to!(file, ::String, :to_str) } } return Opal.require(#{file}) } end def require_relative(file) ::Opal.try_convert!(file, ::String, :to_str) file = ::File.expand_path ::File.join(`Opal.current_file`, '..', file) `Opal.require(#{file})` end # `path` should be the full path to be found in registered modules (`Opal.modules`) def require_tree(path, autoload: false) %x{ var result = []; path = #{::File.expand_path(path)} path = Opal.normalize(path); if (path === '.') path = ''; for (var name in Opal.modules) { if (#{`name`.start_with?(path)}) { if(!#{autoload}) { result.push([name, Opal.require(name)]); } else { result.push([name, true]); // do nothing, delegated to a autoloading } } } return result; } end def singleton_class `Opal.get_singleton_class(self)` end def sleep(seconds = nil) %x{ if (seconds === nil) { #{::Kernel.raise ::TypeError, "can't convert NilClass into time interval"} } if (!seconds.$$is_number) { #{::Kernel.raise ::TypeError, "can't convert #{seconds.class} into time interval"} } if (seconds < 0) { #{::Kernel.raise ::ArgumentError, 'time interval must be positive'} } var get_time = Opal.global.performance ? function() {return performance.now()} : function() {return new Date()} var t = get_time(); while (get_time() - t <= seconds * 1000); return Math.round(seconds); } end def srand(seed = Random.new_seed) ::Random.srand(seed) end def String(str) ::Opal.coerce_to?(str, ::String, :to_str) || ::Opal.coerce_to!(str, ::String, :to_s) end def tap(&block) yield self self end def to_proc self end def to_s `Opal.fallback_to_s(self)` end def catch(tag = nil) tag ||= ::Object.new yield(tag) rescue ::UncaughtThrowError => e return e.value if e.tag == tag ::Kernel.raise end def throw(tag, obj = nil) ::Kernel.raise ::UncaughtThrowError.new(tag, obj) end # basic implementation of open, delegate to File.open def open(*args, &block) ::File.open(*args, &block) end def yield_self return enum_for(:yield_self) { 1 } unless block_given? yield self end alias fail raise alias kind_of? is_a? alias object_id __id__ alias public_send __send__ alias send __send__ alias then yield_self alias to_enum enum_for end class ::Object # Object.require has been set to runtime.js Opal.require # Now we have Kernel loaded, make sure Object.require refers to Kernel.require # which is what ruby does and allows for overwriting by autoloaders `delete $Object.$$prototype.$require` include ::Kernel end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/enumerator.rb
opal/corelib/enumerator.rb
# helpers: slice, coerce_to, deny_frozen_access # backtick_javascript: true # use_strict: true require 'corelib/enumerable' class ::Enumerator include ::Enumerable `self.$$prototype.$$is_enumerator = true` def self.for(object, method = :each, *args, &block) %x{ var obj = #{allocate}; obj.object = object; obj.size = block; obj.method = method; obj.args = args; obj.cursor = 0; return obj; } end def initialize(*, &block) `$deny_frozen_access(self)` @cursor = 0 if block @object = Generator.new(&block) @method = :each @args = [] @size = `arguments[0] || nil` if @size && !@size.respond_to?(:call) @size = `$coerce_to(#{@size}, #{::Integer}, 'to_int')` end else @object = `arguments[0]` @method = `arguments[1] || "each"` @args = `$slice(arguments, 2)` @size = nil end end def each(*args, &block) return self if block.nil? && args.empty? args = @args + args return self.class.new(@object, @method, *args) if block.nil? @object.__send__(@method, *args, &block) end def size @size.respond_to?(:call) ? @size.call(*@args) : @size end def with_index(offset = 0, &block) offset = if offset `$coerce_to(offset, #{::Integer}, 'to_int')` else 0 end return enum_for(:with_index, offset) { size } unless block %x{ var result, index = offset; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = block(param, index); index++; return value; } return self.$each(); } end def each_with_index(&block) return enum_for(:each_with_index) { size } unless block_given? super @object end def rewind @cursor = 0 self end def peek_values @values ||= map { |*i| i } ::Kernel.raise ::StopIteration, 'iteration reached an end' if @cursor >= @values.length @values[@cursor] end def peek values = peek_values values.length <= 1 ? values[0] : values end def next_values out = peek_values @cursor += 1 out end def next values = next_values values.length <= 1 ? values[0] : values end def feed(arg) raise NotImplementedError, "Opal doesn't support Enumerator#feed" end def +(other) ::Enumerator::Chain.new(self, other) end def inspect result = "#<#{self.class}: #{@object.inspect}:#{@method}" if @args.any? result += "(#{@args.inspect[::Range.new(1, -2)]})" end result + '>' end alias with_object each_with_object autoload :ArithmeticSequence, 'corelib/enumerator/arithmetic_sequence' autoload :Chain, 'corelib/enumerator/chain' autoload :Generator, 'corelib/enumerator/generator' autoload :Lazy, 'corelib/enumerator/lazy' autoload :Yielder, 'corelib/enumerator/yielder' end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/dir.rb
opal/corelib/dir.rb
# backtick_javascript: true class ::Dir class << self def chdir(dir) prev_cwd = `Opal.current_dir` `Opal.current_dir = #{dir}` yield ensure `Opal.current_dir = #{prev_cwd}` end def pwd `Opal.current_dir || '.'` end def home ::ENV['HOME'] || '.' end alias getwd pwd end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/number.rb
opal/corelib/number.rb
# backtick_javascript: true # use_strict: true require 'corelib/numeric' class ::Number < ::Numeric ::Opal.bridge(`Number`, self) `Opal.prop(self.$$prototype, '$$is_number', true)` `self.$$is_number_class = true` `var number_id_map = new Map()` class << self def allocate ::Kernel.raise ::TypeError, "allocator undefined for #{name}" end undef :new end def coerce(other) %x{ if (other === nil) { #{::Kernel.raise ::TypeError, "can't convert #{other.class} into Float"}; } else if (other.$$is_string) { return [#{::Kernel.Float(other)}, self]; } else if (#{other.respond_to?(:to_f)}) { return [#{::Opal.coerce_to!(other, ::Float, :to_f)}, self]; } else if (other.$$is_number) { return [other, self]; } else { #{::Kernel.raise ::TypeError, "can't convert #{other.class} into Float"}; } } end def __id__ %x{ // Binary-safe integers if (self|0 === self) { return (self * 2) + 1; } else { if (number_id_map.has(self)) { return number_id_map.get(self); } var id = Opal.uid(); number_id_map.set(self, id); return id; } } end def hash %x{ // Binary-safe integers if (self|0 === self) { return #{__id__} } else { return self.toString().$hash(); } } end def +(other) %x{ if (other.$$is_number) { return self + other; } else { return #{__coerced__ :+, other}; } } end def -(other) %x{ if (other.$$is_number) { return self - other; } else { return #{__coerced__ :-, other}; } } end def *(other) %x{ if (other.$$is_number) { return self * other; } else { return #{__coerced__ :*, other}; } } end def /(other) %x{ if (other.$$is_number) { return self / other; } else { return #{__coerced__ :/, other}; } } end def %(other) %x{ if (other.$$is_number) { if (other == -Infinity) { return other; } else if (other == 0) { #{::Kernel.raise ::ZeroDivisionError, 'divided by 0'}; } else if (other < 0 || self < 0) { return (self % other + other) % other; } else { return self % other; } } else { return #{__coerced__ :%, other}; } } end def &(other) %x{ if (other.$$is_number) { return self & other; } else { return #{__coerced__ :&, other}; } } end def |(other) %x{ if (other.$$is_number) { return self | other; } else { return #{__coerced__ :|, other}; } } end def ^(other) %x{ if (other.$$is_number) { return self ^ other; } else { return #{__coerced__ :^, other}; } } end def <(other) %x{ if (other.$$is_number) { return self < other; } else { return #{__coerced__ :<, other}; } } end def <=(other) %x{ if (other.$$is_number) { return self <= other; } else { return #{__coerced__ :<=, other}; } } end def >(other) %x{ if (other.$$is_number) { return self > other; } else { return #{__coerced__ :>, other}; } } end def >=(other) %x{ if (other.$$is_number) { return self >= other; } else { return #{__coerced__ :>=, other}; } } end # Compute the result of the spaceship operator inside its own function so it # can be optimized despite a try/finally construct. %x{ var spaceship_operator = function(self, other) { if (other.$$is_number) { if (isNaN(self) || isNaN(other)) { return nil; } if (self > other) { return 1; } else if (self < other) { return -1; } else { return 0; } } else { return #{__coerced__ :<=>, `other`}; } } } def <=>(other) `spaceship_operator(self, other)` rescue ::ArgumentError nil end def <<(count) count = ::Opal.coerce_to! count, ::Integer, :to_int `#{count} > 0 ? self << #{count} : self >> -#{count}` end def >>(count) count = ::Opal.coerce_to! count, ::Integer, :to_int `#{count} > 0 ? self >> #{count} : self << -#{count}` end def [](bit) bit = ::Opal.coerce_to! bit, ::Integer, :to_int %x{ if (#{bit} < 0) { return 0; } if (#{bit} >= 32) { return #{ self } < 0 ? 1 : 0; } return (self >> #{bit}) & 1; } end def +@ `+self` end def -@ `-self` end def ~ `~self` end def **(other) if ::Integer === other if !(::Integer === self) || other > 0 `Math.pow(self, other)` else ::Rational.new(self, 1)**other end elsif self < 0 && (::Float === other || ::Rational === other) ::Complex.new(self, 0)**other.to_f elsif `other.$$is_number != null` `Math.pow(self, other)` else __coerced__ :**, other end end def ==(other) %x{ if (other.$$is_number) { return self.valueOf() === other.valueOf(); } else if (#{other.respond_to? :==}) { return #{other == self}; } else { return false; } } end alias === == def abs `Math.abs(self)` end def abs2 `Math.abs(self * self)` end def allbits?(mask) mask = ::Opal.coerce_to! mask, ::Integer, :to_int `(self & mask) == mask` end def anybits?(mask) mask = ::Opal.coerce_to! mask, ::Integer, :to_int `(self & mask) !== 0` end def angle return self if nan? %x{ if (self == 0) { if (1 / self > 0) { return 0; } else { return Math.PI; } } else if (self < 0) { return Math.PI; } else { return 0; } } end def bit_length unless ::Integer === self ::Kernel.raise ::NoMethodError.new("undefined method `bit_length` for #{self}:Float", 'bit_length') end %x{ if (self === 0 || self === -1) { return 0; } var result = 0, value = self < 0 ? ~self : self; while (value != 0) { result += 1; value >>>= 1; } return result; } end def ceil(ndigits = 0) %x{ var f = #{to_f}; if (f % 1 === 0 && ndigits >= 0) { return f; } var factor = Math.pow(10, ndigits), result = Math.ceil(f * factor) / factor; if (f % 1 === 0) { result = Math.round(result); } return result; } end def chr(encoding = undefined) `Opal.str(String.fromCodePoint(self), encoding || "BINARY")` end def denominator if nan? || infinite? 1 else super end end def downto(stop, &block) unless block_given? return enum_for(:downto, stop) do ::Kernel.raise ::ArgumentError, "comparison of #{self.class} with #{stop.class} failed" unless ::Numeric === stop stop > self ? 0 : self - stop + 1 end end %x{ if (!stop.$$is_number) { #{::Kernel.raise ::ArgumentError, "comparison of #{self.class} with #{stop.class} failed"} } for (var i = self; i >= stop; i--) { block(i); } } self end def equal?(other) self == other || `isNaN(self) && isNaN(other)` end def even? `self % 2 === 0` end def floor(ndigits = 0) %x{ var f = #{to_f}; if (f % 1 === 0 && ndigits >= 0) { return f; } var factor = Math.pow(10, ndigits), result = Math.floor(f * factor) / factor; if (f % 1 === 0) { result = Math.round(result); } return result; } end def gcd(other) unless ::Integer === other ::Kernel.raise ::TypeError, 'not an integer' end %x{ var min = Math.abs(self), max = Math.abs(other); while (min > 0) { var tmp = min; min = max % min; max = tmp; } return max; } end def gcdlcm(other) [gcd(other), lcm(other)] end def integer? `self % 1 === 0` end def is_a?(klass) return true if klass == ::Integer && ::Integer === self return true if klass == ::Integer && ::Integer === self return true if klass == ::Float && ::Float === self super end def instance_of?(klass) return true if klass == ::Integer && ::Integer === self return true if klass == ::Integer && ::Integer === self return true if klass == ::Float && ::Float === self super end def lcm(other) unless ::Integer === other ::Kernel.raise ::TypeError, 'not an integer' end %x{ if (self == 0 || other == 0) { return 0; } else { return Math.abs(self * other / #{gcd(other)}); } } end def next `self + 1` end def nobits?(mask) mask = ::Opal.coerce_to! mask, ::Integer, :to_int `(self & mask) == 0` end def nonzero? `self == 0 ? nil : self` end def numerator if nan? || infinite? self else super end end def odd? `self % 2 !== 0` end def ord self end def pow(b, m = undefined) %x{ if (self == 0) { #{::Kernel.raise ::ZeroDivisionError, 'divided by 0'} } if (m === undefined) { return #{self**b}; } else { if (!(#{::Integer === b})) { #{::Kernel.raise ::TypeError, 'Integer#pow() 2nd argument not allowed unless a 1st argument is integer'} } if (b < 0) { #{::Kernel.raise ::TypeError, 'Integer#pow() 1st argument cannot be negative when 2nd argument specified'} } if (!(#{::Integer === m})) { #{::Kernel.raise ::TypeError, 'Integer#pow() 2nd argument not allowed unless all arguments are integers'} } if (m === 0) { #{::Kernel.raise ::ZeroDivisionError, 'divided by 0'} } return #{(self**b) % m} } } end def pred `self - 1` end def quo(other) if ::Integer === self super else self / other end end def rationalize(eps = undefined) %x{ if (arguments.length > 1) { #{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} for 0..1)"}; } } if ::Integer === self ::Rational.new(self, 1) elsif infinite? ::Kernel.raise ::FloatDomainError, 'Infinity' elsif nan? ::Kernel.raise ::FloatDomainError, 'NaN' elsif `eps == null` f, n = ::Math.frexp self f = ::Math.ldexp(f, ::Float::MANT_DIG).to_i n -= ::Float::MANT_DIG ::Rational.new(2 * f, 1 << (1 - n)).rationalize(::Rational.new(1, 1 << (1 - n))) else to_r.rationalize(eps) end end def remainder(y) self - y * (self / y).truncate end def round(ndigits = undefined) if ::Integer === self if `ndigits == null` return self end if ::Float === ndigits && ndigits.infinite? ::Kernel.raise ::RangeError, 'Infinity' end ndigits = ::Opal.coerce_to!(ndigits, ::Integer, :to_int) if ndigits < ::Integer::MIN ::Kernel.raise ::RangeError, 'out of bounds' end if `ndigits >= 0` return self end ndigits = `-ndigits` %x{ if (0.415241 * ndigits - 0.125 > #{size}) { return 0; } var f = Math.pow(10, ndigits), x = Math.floor((Math.abs(self) + f / 2) / f) * f; return self < 0 ? -x : x; } else if nan? && `ndigits == null` ::Kernel.raise ::FloatDomainError, 'NaN' end ndigits = ::Opal.coerce_to!(`ndigits || 0`, ::Integer, :to_int) if ndigits <= 0 if nan? ::Kernel.raise ::RangeError, 'NaN' elsif infinite? ::Kernel.raise ::FloatDomainError, 'Infinity' end elsif ndigits == 0 return `Math.round(self)` elsif nan? || infinite? return self end _, exp = ::Math.frexp(self) if ndigits >= (::Float::DIG + 2) - (exp > 0 ? exp / 4 : exp / 3 - 1) return self end if ndigits < 0 - (exp > 0 ? exp / 3 + 1 : exp / 4) return 0 end `Math.round(self * Math.pow(10, ndigits)) / Math.pow(10, ndigits)` end end def times(&block) return enum_for(:times) { self } unless block %x{ for (var i = 0; i < self; i++) { block(i); } } self end def to_f self end def to_i `self < 0 ? Math.ceil(self) : Math.floor(self)` end def to_r if ::Integer === self ::Rational.new(self, 1) else f, e = ::Math.frexp(self) f = ::Math.ldexp(f, ::Float::MANT_DIG).to_i e -= ::Float::MANT_DIG (f * (::Float::RADIX**e)).to_r end end def to_s(base = 10) base = ::Opal.coerce_to! base, ::Integer, :to_int if base < 2 || base > 36 ::Kernel.raise ::ArgumentError, "invalid radix #{base}" end # Don't lose the negative zero if self == 0 && `1/self === -Infinity` return '-0.0' end `self.toString(base)` end def truncate(ndigits = 0) %x{ var f = #{to_f}; if (f % 1 === 0 && ndigits >= 0) { return f; } var factor = Math.pow(10, ndigits), result = parseInt(f * factor, 10) / factor; if (f % 1 === 0) { result = Math.round(result); } return result; } end def digits(base = 10) if self < 0 ::Kernel.raise ::Math::DomainError, 'out of domain' end base = ::Opal.coerce_to! base, ::Integer, :to_int if base < 2 ::Kernel.raise ::ArgumentError, "invalid radix #{base}" end %x{ if (self != parseInt(self)) #{::Kernel.raise ::NoMethodError, "undefined method `digits' for #{inspect}"} var value = self, result = []; if (self == 0) { return [0]; } while (value != 0) { result.push(value % base); value = parseInt(value / base, 10); } return result; } end def divmod(other) if nan? || other.nan? ::Kernel.raise ::FloatDomainError, 'NaN' elsif infinite? ::Kernel.raise ::FloatDomainError, 'Infinity' else super end end def upto(stop, &block) unless block_given? return enum_for(:upto, stop) do ::Kernel.raise ::ArgumentError, "comparison of #{self.class} with #{stop.class} failed" unless ::Numeric === stop stop < self ? 0 : stop - self + 1 end end %x{ if (!stop.$$is_number) { #{::Kernel.raise ::ArgumentError, "comparison of #{self.class} with #{stop.class} failed"} } for (var i = self; i <= stop; i++) { block(i); } } self end def zero? `self == 0` end # Since bitwise operations are 32 bit, declare it to be so. def size 4 end def nan? `isNaN(self)` end def finite? `self != Infinity && self != -Infinity && !isNaN(self)` end def infinite? %x{ if (self == Infinity) { return +1; } else if (self == -Infinity) { return -1; } else { return nil; } } end def positive? `self != 0 && (self == Infinity || 1 / self > 0)` end def negative? `self == -Infinity || 1 / self < 0` end %x{ function numberToUint8Array(num) { var uint8array = new Uint8Array(8); new DataView(uint8array.buffer).setFloat64(0, num, true); return uint8array; } function uint8ArrayToNumber(arr) { return new DataView(arr.buffer).getFloat64(0, true); } function incrementNumberBit(num) { var arr = numberToUint8Array(num); for (var i = 0; i < arr.length; i++) { if (arr[i] === 0xff) { arr[i] = 0; } else { arr[i]++; break; } } return uint8ArrayToNumber(arr); } function decrementNumberBit(num) { var arr = numberToUint8Array(num); for (var i = 0; i < arr.length; i++) { if (arr[i] === 0) { arr[i] = 0xff; } else { arr[i]--; break; } } return uint8ArrayToNumber(arr); } } def next_float return ::Float::INFINITY if self == ::Float::INFINITY return ::Float::NAN if nan? if self >= 0 # Math.abs() is needed to handle -0.0 `incrementNumberBit(Math.abs(self))` else `decrementNumberBit(self)` end end def prev_float return -::Float::INFINITY if self == -::Float::INFINITY return ::Float::NAN if nan? if self > 0 `decrementNumberBit(self)` else `-incrementNumberBit(Math.abs(self))` end end alias arg angle alias eql? == alias fdiv / alias inspect to_s alias kind_of? is_a? alias magnitude abs alias modulo % alias object_id __id__ alias phase angle alias succ next alias to_int to_i end ::Fixnum = ::Number class ::Integer < ::Numeric `self.$$is_number_class = true` `self.$$is_integer_class = true` class << self def allocate ::Kernel.raise ::TypeError, "allocator undefined for #{name}" end undef :new def sqrt(n) n = ::Opal.coerce_to!(n, ::Integer, :to_int) %x{ if (n < 0) { #{::Kernel.raise ::Math::DomainError, 'Numerical argument is out of domain - "isqrt"'} } return parseInt(Math.sqrt(n), 10); } end def try_convert(object) Opal.coerce_to?(object, self, :to_int) end end self::MAX = `Math.pow(2, 30) - 1` self::MIN = `-Math.pow(2, 30)` end class ::Float < ::Numeric `self.$$is_number_class = true` class << self def allocate ::Kernel.raise ::TypeError, "allocator undefined for #{name}" end undef :new def ===(other) `!!other.$$is_number` end end self::INFINITY = `Infinity` self::MAX = `Number.MAX_VALUE` self::MIN = `Number.MIN_VALUE` self::NAN = `NaN` self::DIG = 15 self::MANT_DIG = 53 self::RADIX = 2 self::EPSILON = `Number.EPSILON || 2.2204460492503130808472633361816E-16` end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/class.rb
opal/corelib/class.rb
# backtick_javascript: true # use_strict: true require 'corelib/module' class ::Class def self.new(superclass = Object, &block) %x{ if (!superclass.$$is_class) { throw Opal.TypeError.$new("superclass must be a Class"); } var klass = Opal.allocate_class(nil, superclass); superclass.$inherited(klass); #{`klass`.class_exec(self, &block) if block_given?} return klass; } end def allocate %x{ var obj = new self.$$constructor(); obj.$$id = Opal.uid(); return obj; } end def clone(freeze: nil) unless freeze.nil? || freeze == true || freeze == false raise ArgumentError, "unexpected value for freeze: #{freeze.class}" end copy = `Opal.allocate_class(nil, self.$$super)` copy.copy_instance_variables(self) copy.copy_singleton_methods(self) copy.initialize_clone(self, freeze: freeze) if freeze == true || (freeze.nil? && frozen?) copy.freeze end copy end def dup copy = `Opal.allocate_class(nil, self.$$super)` copy.copy_instance_variables(self) copy.initialize_dup(self) copy end def descendants subclasses + subclasses.map(&:descendants).flatten end def inherited(cls) end def new(*args, &block) %x{ var object = #{allocate}; Opal.send(object, object.$initialize, args, block); return object; } end def subclasses %x{ if (typeof WeakRef !== 'undefined') { var i, subclass, out = []; for (i = 0; i < self.$$subclasses.length; i++) { subclass = self.$$subclasses[i].deref(); if (subclass !== undefined) { out.push(subclass); } } return out; } else { return self.$$subclasses; } } end def superclass `self.$$super || nil` end def to_s %x{ var singleton_of = self.$$singleton_of; if (singleton_of && singleton_of.$$is_a_module) { return #{"#<Class:#{`singleton_of`.name}>"}; } else if (singleton_of) { // a singleton class created from an object return #{"#<Class:#<#{`singleton_of.$$class`.name}:0x#{`Opal.id(singleton_of)`.to_s(16)}>>"}; } return #{super()}; } end def attached_object %x{ if (self.$$singleton_of != null) { return self.$$singleton_of; } else { #{::Kernel.raise ::TypeError, "`#{self}' is not a singleton class"} } } end alias inspect to_s end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string.rb
opal/corelib/string.rb
# helpers: coerce_to, respond_to, global_regexp, prop, opal32_init, opal32_add, transform_regexp, str # backtick_javascript: true # depends on: # require 'corelib/comparable' # required by mini # require 'corelib/regexp' # required by mini class ::String < `String` include ::Comparable attr_reader :encoding, :internal_encoding # these 2 are set to defaults at the end of corelib/string/encoding.rb %x{ const MAX_STR_LEN = Number.MAX_SAFE_INTEGER; Opal.prop(#{self}.$$prototype, '$$is_string', true); var string_id_map = new Map(); function first_char(str) { return String.fromCodePoint(str.codePointAt(0)); } // UTF-16 aware find_index_of, args: // str: string // search: the string to search for in str // search_l: is optional, if given must be search.$length(), do NOT use search.length // last: boolean, optional too, if true returns the last index otherwise the first function find_index_of(str, search, search_l, last) { let search_f = (search.length === 1) ? search : first_char(search); let i = 0, col = [], l = 0, idx = -1; for (const c of str) { if (col.length > 0) { for (const e of col) { if (e.l < l) { e.search += c; e.l++; } if (e.l === l) { if (e.search == search) { if (last) idx = e.index; else return e.index; } e.search = null; } } if (!col[0].search) col.shift(); } if (search_f == c) { if (search.length === 1) { if (last) idx = i; else return i; } else { if (l === 0) l = search_l || search.$length(); if (l === 1) { if (last) idx = i; else return i; } else col.push({ index: i, search: c, l: 1 }); } } i++; } return idx; } // multi byte character aware find_byte_index_of, args: // str: string // search: the string to search for in str // search_l: is optional, if given must be search.$length(), do NOT use search.length // last: boolean, optional too, if true returns the last index otherwise the first function find_byte_index_of(str, search, search_l, offset, last) { let search_f; if (search.length === 0 || search.length === 1) search_f = search; else search_f = first_char(search); let i = 0, col = [], l = 0, idx = -1, hit_boundary = (offset === 0) ? true : false; if (last) l = search_l || search.$length(); for (const c of str) { if (col.length > 0) { for (const e of col) { if (e.l < l) { e.search += c; e.l++; } if (e.l === l) { if (e.search == search) { if (last) idx = e.index; else return e.index; } e.search = null; } } if (!col[0].search) col.shift(); } if (!(!last && offset > 0 && i < offset)) { if (last && ((l < 2 && i > offset) || (i > offset + l))) { break; } else if (search_f == c) { if (search.length === 1) { if (last && i <= offset) idx = i; else return i; } else { if (l === 0) l = search_l || search.$length(); if (l === 1) { if (last && i <= offset) idx = i; else return i; } else if (!(last && i > offset)) col.push({ index: i, search: c, l: 1 }); } } } i += c.$bytesize(); if (offset === i) hit_boundary = true; } if (!last && i < offset) return -1; if (last && offset > i) { if (search.length === 0) return i; return idx; } if ((!hit_boundary) && (idx > -1 || search.length === 0)) #{raise IndexError, "offset #{`offset`} does not land on character boundary"}; if (search.length === 0) return offset; return idx; } // UTF-16 aware cut_from_end, cuts characters from end // str: the string to cut // cut_l: the length, count of characters to cut function cut_from_end(str, cut_l) { let i = str.length - 1, curr_cp; for (; i >= 0; i--) { curr_cp = str.codePointAt(i); if (curr_cp >= 0xDC00 && curr_cp <= 0xDFFF) continue; // low surrogate, get the full code point cut_l--; if (cut_l === 0) break; } return str.slice(0, i); } function padding(padstr, width) { let result_l = 0, result = '', p_l = padstr.length, padstr_l = p_l === 1 ? p_l : padstr.$length(); while (result_l < width) { result += padstr; result_l += padstr_l; } if (result_l === width) return result; if (p_l === padstr_l) return result.slice(0, width); return cut_from_end(result, result_l - width); } function starts_with_low_surrogate(str) { if (str.length === 0) return false; let cp = str.codePointAt(0); if (cp >= 0xDC00 && cp <= 0xDFFF) return true; return false; } function ends_with_high_surrogate(str) { if (str.length === 0) return false; let cp = str.codePointAt(str.length - 1); if (cp >= 0xD800 && cp <= 0xDBFF) return true; return false; } function starts_with(str, prefix) { return (str.length >= prefix.length && !ends_with_high_surrogate(prefix) && str.startsWith(prefix)); } function ends_with(str, suffix) { return (str.length >= suffix.length && !starts_with_low_surrogate(suffix) && str.endsWith(suffix)); } let GRAPHEME_SEGMENTER; // initialized on demand by #each_grapheme_cluster below using: function grapheme_segmenter() { if (!GRAPHEME_SEGMENTER) { // Leaving the locale parameter as undefined, indicating browsers default locale. // Depending on implementation quality and default locale, there is a chance, // that grapheme segmentation results differ. GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, { granularity: "grapheme" }); } return GRAPHEME_SEGMENTER; } function char_class_from_char_sets(sets) { function explode_sequences_in_character_set(set_s) { var result = [], i, len = set_s.length, curr_char, skip_next_dash, code_point_from, code_point_upto, code_point; for (i = 0; i < len; i++) { curr_char = set_s[i]; if (curr_char === '-' && i > 0 && i < (len - 1) && !skip_next_dash) { code_point_from = set_s[i - 1].codePointAt(0); code_point_upto = set_s[i + 1].codePointAt(0); if (code_point_from > code_point_upto) { #{::Kernel.raise ::ArgumentError, "invalid range \"#{`code_point_from`}-#{`code_point_upto`}\" in string transliteration"} } for (code_point = code_point_from + 1; code_point < code_point_upto + 1; code_point++) { if (code_point >= 0xD800 && code_point <= 0xDFFF) code_point = 0xE000; // exclude surrogate range result.push(String.fromCodePoint(code_point)); } skip_next_dash = true; i++; } else { skip_next_dash = (curr_char === '\\'); result.push(curr_char); } } return result; } function intersection(setA, setB) { if (setA.length === 0) { return setB; } var result = [], i, len = setA.length, chr; for (i = 0; i < len; i++) { chr = setA[i]; if (setB.indexOf(chr) !== -1) { result.push(chr); } } return result; } var i, len, set, set_s, neg, chr, tmp, pos_intersection = [], neg_intersection = []; for (i = 0, len = sets.length; i < len; i++) { set = $coerce_to(sets[i], #{::String}, 'to_str'); set_s = []; for (const c of set) { let cd = c.codePointAt(0); if (cd < 0xD800 || cd > 0xDFFF) set_s.push(c); // exclude surrogate range } neg = (set_s[0] === '^' && set_s.length > 1); set_s = explode_sequences_in_character_set(neg ? set_s.slice(1) : set_s); if (neg) { neg_intersection = intersection(neg_intersection, set_s); } else { pos_intersection = intersection(pos_intersection, set_s); } } if (pos_intersection.length > 0 && neg_intersection.length > 0) { tmp = []; for (i = 0, len = pos_intersection.length; i < len; i++) { chr = pos_intersection[i]; if (neg_intersection.indexOf(chr) === -1) { tmp.push(chr); } } pos_intersection = tmp; neg_intersection = []; } if (pos_intersection.length > 0) { return '[' + #{::Regexp.escape(`pos_intersection.join('')`)} + ']'; } if (neg_intersection.length > 0) { return '[^' + #{::Regexp.escape(`neg_intersection.join('')`)} + ']'; } return null; } function slice_by_string(string, index, length) { if (length != null) #{::Kernel.raise ::TypeError}; if (find_index_of(string, index) === -1) return nil; return index.toString(); } function slice_by_regexp(string, index, length) { let match = string.match(index); if (match === null) { #{$~ = nil} return nil; } #{$~ = ::MatchData.new(`index`, `match`)} if (length == null) return match[0]; length = $coerce_to(length, #{::Integer}, 'to_int'); if (length < 0 && -length < match.length) { return match[length += match.length]; } if (length >= 0 && length < match.length) { return match[length]; } return nil; } function slice_by_index_neg(string, index, length) { // negative index, walk from the end of the string, if (index < -string.length || length < -string.length) return nil; let j = string.length - 1, i = -1, result = '', result_l = 0, curr_cp, idx_end, max; if (length != null) { if (length < 0) max = length; else if (length === Infinity || (index + length >= 0)) max = -1; else max = index + length - 1; } for (; j >= 0; j--) { curr_cp = string.codePointAt(j); if (curr_cp >= 0xDC00 && curr_cp <= 0xDFFF) continue; // low surrogate, get the full code point next if (length != null && i <= max) { if (!idx_end) idx_end = (curr_cp > 0xDFFF) ? j + 2 : j + 1; result_l++; } if (i === index) { if (length === 0 || index === length) return ""; if (length === 1 || length == null) return String.fromCodePoint(curr_cp); break; } i--; } if (result_l > 0) { result = string.slice(j, idx_end); if (length < 0 && ((result_l + length) < 0)) return ""; return result; } return nil; } function slice_by_index_zero(string, length) { // special conditions if (length === 0 || string.length === 0) return (length != null) ? "" : nil; if (length === 1 || length == null) return first_char(string); if (length === Infinity) return string.toString(); // walk the string let i = 0, result = ''; for (const c of string) { result += c; i++; if (i === length) break; } if (length < 0) { // if length is a negative index from a range, we walked to the end, so shorten the result if ((i + length) > 0) return cut_from_end(result, -length); else return ""; } return result; } function slice_by_index_pos(string, index, length) { let i = 0, result_l = 0, result; for (const c of string) { if (i < index) { i++; } else if (i === index) { if (length === 1 || length == null) return c; if (length === 0) return ""; result = c; i++; result_l++; } else if (i > index) { if (result_l < length || length < 0) { result += c; i++; result_l++; } else if (length > 0 && result_l >= length) break; } } if (result) { if (length < 0) { // if length is a negative index from a range, we walked to the end, so shorten the result if ((result_l + length) > 0) return cut_from_end(result, -length); else return ""; } if (result_l > 0 && index <= i && length > 1) return result; } // special condition for ruby weirdness if (i === index && length != null) return ""; return nil; } function slice(string, index, length) { if (index.$$is_string) return slice_by_string(string, index, length); if (index.$$is_regexp) return slice_by_regexp(string, index, length); if (index.$$is_range) { if (length) #{raise TypeError, 'length not allowed if range is given'}; // This part sets index and length, basically converting string[2..3] range // to string[2, 1] index + length and letting the range get handled by the // index + length code below. // // For ranges, first index always is a index, possibly negative. // Length is either the length, if it can be determined by the indexes of the range, // or its a possibly negative index, because the exact string length is not known, // or Infinity, with Infinity indicating 'walk to end of string'. const range = index; const r_end = range.end === nil ? Infinity : $coerce_to(range.end, #{::Integer}, 'to_int'); index = range.begin === nil ? 0 : $coerce_to(range.begin, #{::Integer}, 'to_int'); if (((index > 0 && r_end > 0) || (index < 0 && r_end < 0)) && index > r_end) { length = 0; } else if (index === r_end) { length = range.excl ? 0 : 1; } else { const e = range.excl ? 0 : 1; if ((!range.excl && r_end === -1) || r_end === Infinity) length = Infinity; else if (index == 0 || (index > 0 && r_end < 0)) length = r_end === Infinity ? Infinity : (r_end + e); else if (index < 0 && r_end >= 0) length = 0; else if ((index < 0 && r_end < 0) || (index > 0 && r_end > 0)) { length = r_end === Infinity ? Infinity : (r_end - index + e); if (length < 0) length = 0; } } } else { index = $coerce_to(index, #{::Integer}, 'to_int'); if (length != null) length = $coerce_to(length, #{::Integer}, 'to_int'); if (length < 0) return nil; } if (index > MAX_STR_LEN) #{raise RangeError, 'index too large'}; if (length !== Infinity && length > MAX_STR_LEN) #{raise RangeError, 'length too large'}; if (index < 0) return slice_by_index_neg(string, index, length); if (index === 0) return slice_by_index_zero(string, length); return slice_by_index_pos(string, index, length); } function raise_if_not_stringish(obj) { if (obj === nil) #{raise TypeError, 'no implicit conversion of nil into String'}; if (typeof obj === "number") #{raise TypeError, 'no implicit conversion of Integer into String'}; if (obj === true || obj === false) #{raise TypeError, "no implicit conversion of #{`obj`} into String"}; } function case_options_have_ascii(options, allow_fold) { let ascii = false, fold = false; if (options.length > 0) { for(const option of options) { if (option == "ascii") ascii = true; else if (options == "fold") fold = true; else #{raise ArgumentError, "unknown option :#{`option`}"} } if (!allow_fold) { if (fold && ascii) #{raise ArgumentError, 'too many options'}; if (fold) #{raise ArgumentError, ':fold not allowed'}; } } return ascii; } } # Force strict mode to suppress autoboxing of `this` %x{ (function() { 'use strict'; #{ def __id__ %x{ if (typeof self === 'object') { return #{super} } if (string_id_map.has(self)) { return string_id_map.get(self); } var id = Opal.uid(); string_id_map.set(self, id); return id; } end def hash %x{ var hash = $opal32_init(), i, length = self.length; hash = $opal32_add(hash, 0x5); hash = $opal32_add(hash, length); for (i = 0; i < length; i++) { hash = $opal32_add(hash, self.charCodeAt(i)); } return hash; } end } })(); } def self.try_convert(what) ::Opal.coerce_to?(what, ::String, :to_str) end def self.new(*args) %x{ var str = args[0] || ""; var opts = args[args.length-1]; str = $coerce_to(str, #{::String}, 'to_str'); if (self.$$constructor === String) { str = $str(str); } else { str = new self.$$constructor(str); } if (opts && opts.$$is_hash) { if (opts.has('encoding')) str = str.$force_encoding(opts.get('encoding')); } if (!str.$initialize.$$pristine) #{`str`.initialize(*args)}; return str; } end # Our initialize method does nothing, the string value setup is being # done by String.new. Therefore not all kinds of subclassing will work. # As a rule of thumb, when subclassing String, either make sure to override # .new or make sure that the first argument given to a constructor is # a string we want our subclass-string to hold. def initialize(str = undefined, encoding: nil, capacity: nil) end def %(data) if ::Array === data format(self, *data) else format(self, data) end end def *(count) %x{ count = $coerce_to(count, #{::Integer}, 'to_int'); if (count < 0) { #{::Kernel.raise ::ArgumentError, 'negative argument'} } if (count === 0) { return ''; } var result = '', string = self.toString(); // All credit for the bit-twiddling magic code below goes to Mozilla // polyfill implementation of String.prototype.repeat() posted here: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat if (string.length * count >= MAX_STR_LEN) { #{::Kernel.raise ::RangeError, 'multiply count must not overflow maximum string size'} } for (;;) { if ((count & 1) === 1) { result += string; } count >>>= 1; if (count === 0) { break; } string += string; } return result; } end def +(other) other = `$coerce_to(#{other}, #{::String}, 'to_str')` %x{ if (other.length === 0 && self.$$class === Opal.String) return self; if (self.length === 0 && other.$$class === Opal.String) return other; var out = self + other; if (self.encoding === out.encoding && other.encoding === out.encoding) return out; if (self.encoding.name === "UTF-8" || other.encoding.name === "UTF-8") return out; return Opal.str(out, self.encoding); } end def +@ frozen? ? dup : self end def -@ %x{ if (typeof self === 'string' || self.$$frozen) return self; if (self.encoding.name == 'UTF-8' && self.internal_encoding.name == 'UTF-8') return self.toString(); return self.$dup().$freeze(); } end # << - not supported, mutates string def <=>(other) if other.respond_to? :to_str other = other.to_str.to_s `self > other ? 1 : (self < other ? -1 : 0)` else %x{ var cmp = #{other <=> self}; if (cmp === nil) { return nil; } else { return cmp > 0 ? -1 : (cmp < 0 ? 1 : 0); } } end end def ==(other) %x{ if (other.$$is_string) { return self.toString() === other.toString(); } if ($respond_to(other, '$to_str')) { return #{other == self}; } return false; } end alias === == def =~(other) %x{ if (other.$$is_string) { #{::Kernel.raise ::TypeError, 'type mismatch: String given'}; } return #{other =~ self}; } end def [](index, length = undefined) result = `slice(self, index, length)` if result %x{ if (self.encoding === Opal.Encoding?.UTF_8) return result; return $str(result, self.encoding); } end nil end # []= - not supported, mutates string # append_as_bytes - not supported, mutates string def ascii_only? # non-ASCII-compatible encoding must return false %x{ if (!self.encoding?.ascii) return false; return /^[\x00-\x7F]*$/.test(self); } end def b `$str(self, 'binary')` end def byteindex(search, offset = 0) %x{ let index, match, regex; if (offset == nil || offset == null) { offset = 0; } else { offset = $coerce_to(offset, #{::Integer}, 'to_int'); if (offset < 0) { offset += self.$bytesize(); if (offset < 0) return nil; } } raise_if_not_stringish(search); if (search.$$is_regexp) { let str, b_size; if (offset > 0) { // because we cannot do binary RegExp, we byteslice self from offset // then exec the regexp on the remaining string, getting the // char index, and then measure the bytesize until the char index b_size = self.$bytesize(); if (offset > b_size) return nil; str = self.$byteslice(offset, b_size - offset); } else str = self; regex = $global_regexp(search); match = regex.exec(str); if (match === null) { #{$~ = nil}; return nil; } #{$~ = ::MatchData.new(`regex`, `match`)}; index = match.index; if (index === 0) return offset; return offset + #{internal_encoding.bytesize(`str`, `index - 1`)}; } search = $coerce_to(search, #{::String}, 'to_str'); index = find_byte_index_of(self, search, search.$length(), offset, false); if (index === -1) return nil; return index; } end def byterindex(search, offset = undefined) %x{ let index, match, regex, _m; if (offset == undefined) { offset = self.$bytesize(); } else { offset = $coerce_to(offset, #{::Integer}, 'to_int'); if (offset < 0) { offset += self.$bytesize(); if (offset < 0) return nil; } } raise_if_not_stringish(search); if (search.$$is_regexp) { let br_idx, b_length = self.$bytesize(); if (offset < b_length) br_idx = self.$byteslice(0, offset + 1).length - 1; match = null; regex = $global_regexp(search); while (true) { _m = regex.exec(self); if (_m === null || _m.index > br_idx) break; match = _m; regex.lastIndex = match.index + 1; } if (match === null) { #{$~ = nil} return nil; } #{$~ = ::MatchData.new `regex`, `match`}; index = match.index; if (index === 0) return 0; return #{internal_encoding.bytesize(`self`, `index - 1`)}; } search = $coerce_to(search, #{::String}, 'to_str'); index = find_byte_index_of(self, search, search.$length(), offset, true); if (index === -1) return nil; return index; } end def bytes(&block) res = each_byte.to_a return res unless block_given? res.each(&block) self end def bytesize internal_encoding.bytesize(self, `self.length`) end def byteslice(index, length = undefined) %x{ if (index.$$is_range) { if (length) #{raise TypeError, 'length not allowed if range is given'}; // This part sets index and length, basically converting self[2..3] range // to self[2, 1] index + length and letting the range get handled by the // index + length code below. const range = index; const r_end = index.end === nil ? Infinity : $coerce_to(range.end, #{::Integer}, 'to_int'); index = range.begin === nil ? 0 : $coerce_to(range.begin, #{::Integer}, 'to_int'); if (((index > 0 && r_end > 0) || (index < 0 && r_end <0)) && index > r_end) { length = 0; } else if (index === r_end) { length = range.excl ? 0 : 1; } else { const e = range.excl ? 0 : 1; if ((!range.excl && r_end === -1) || r_end === Infinity) length = Infinity; else if (index == 0 || (index > 0 && r_end < 0)) length = r_end === Infinity ? Infinity : (r_end + e); else if (index < 0 && r_end >= 0) length = 0; else if ((index < 0 && r_end < 0) || (index > 0 && r_end > 0)) { length = r_end === Infinity ? Infinity : (r_end - index + e); if (length < 0) length = 0; } } } else { index = $coerce_to(index, #{::Integer}, 'to_int'); if (length != null) length = $coerce_to(length, #{::Integer}, 'to_int'); if (length < 0) return nil; if (length == null || length === nil) { if (self.length === 0) return nil; // no match possible length = 1; } } if (index > MAX_STR_LEN) #{raise RangeError, 'index too large'}; if (length !== Infinity && length > MAX_STR_LEN) #{raise RangeError, 'length too large'}; } result = internal_encoding.byteslice(self, index, length) if result %x{ if (self.encoding === Opal.Encoding?.UTF_8) return result; return $str(result, self.encoding); } end result end # bytesplice - not supported, mutates string def capitalize(*options) %x{ if (self.length === 0) return ''; let first = first_char(self); if (case_options_have_ascii(options) && first.codePointAt(0) > 127) return self; let first_upper = first.toUpperCase(); if (first_upper.length > first.length && first_upper.codePointAt(0) < 128) { first_upper = first_upper[0] + first_upper[1].toLowerCase(); } let capz = first_upper + self.substring(first.length).toLowerCase(); return $str(capz, self.encoding); } end # capitalize! - not supported, mutates string def casecmp(other) return nil unless other.respond_to?(:to_str) other = `$coerce_to(other, #{::String}, 'to_str')`.to_s downcase(:ascii) <=> other.downcase(:ascii) end def casecmp?(other) return nil unless other.respond_to?(:to_str) other = `$coerce_to(other, #{::String}, 'to_str')`.to_s c = downcase(:fold) <=> other.downcase(:fold) return true if c == 0 return nil if c.nil? false end def center(width, padstr = ' ') width = `$coerce_to(#{width}, #{::Integer}, 'to_int')` padstr = `$coerce_to(#{padstr}, #{::String}, 'to_str')`.to_s ::Kernel.raise ::ArgumentError, 'zero width padding' if padstr.empty? l = length return self if width <= l %x{ return $str(padding(padstr, Math.floor((width + l) / 2) - l) + self + padding(padstr, Math.ceil((width + l) / 2) - l), self.encoding); } end def chars(&block) return each_char(&block) if block_given? # cannot use the shortcut [...self] here, # because encoding must be set on each char each_char.to_a end def chomp(separator = $/) return self if `separator === nil || self.length === 0` separator = ::Opal.coerce_to!(separator, ::String, :to_str).to_s %x{ var result; if (separator === "\n") { result = self.replace(/\r?\n?$/, ''); } else if (separator.length === 0) { result = self.replace(/(\r?\n)+$/, ''); } else if (self.length >= separator.length && !starts_with_low_surrogate(separator) && !ends_with_high_surrogate(separator)) { // compare tail with separator if (self.substring(self.length - separator.length) === separator) { result = self.substring(0, self.length - separator.length); } } if (result != null) { return $str(result, self.encoding); } } self end # chomp! - not supported, mutates string def chop %x{ var length = self.length, result; if (length <= 1) { result = ""; } else if (self.charAt(length - 1) === "\n" && self.charAt(length - 2) === "\r") { result = self.substring(0, length - 2); } else { let cut = self.codePointAt(length - 2) > 0xFFFF ? 2 : 1; result = self.substring(0, length - cut); } return $str(result, self.encoding); } end # chop! - not supported, mutates string def chr %x{ let result = self.length > 0 ? first_char(self) : ''; return $str(result, self.encoding); } end # clear - not supported, mutates string def clone(freeze: nil) unless freeze.nil? || freeze == true || freeze == false raise ArgumentError, "unexpected value for freeze: #{freeze.class}" end copy = `$str(self)` copy.copy_singleton_methods(self) copy.initialize_clone(self, freeze: freeze) if freeze == true `if (!copy.$$frozen) copy.$$frozen = true;` elsif freeze.nil? `if (self.$$frozen) copy.$$frozen = true;` end copy end def codepoints(&block) # If a block is given, which is a deprecated form, works the same as each_codepoint. return each_codepoint(&block) if block_given? each_codepoint.to_a end # concat - not supported, mutates string def count(*sets) %x{ if (sets.length === 0) { #{::Kernel.raise ::ArgumentError, 'ArgumentError: wrong number of arguments (0 for 1+)'} } let char_class = char_class_from_char_sets(sets); if (char_class === null) return 0; let pattern_flags = $transform_regexp(char_class, 'gu'); return self.$length() - self.replace(new RegExp(pattern_flags[0], pattern_flags[1]), '').$length(); } end # crypt - not implemented, crypt(3) missing # dedup - not implemented def delete(*sets) %x{ if (sets.length === 0) { #{::Kernel.raise ::ArgumentError, 'ArgumentError: wrong number of arguments (0 for 1+)'} } let char_class = char_class_from_char_sets(sets); if (char_class === null) return self; let pattern_flags = $transform_regexp(char_class, 'gu'); return $str(self.replace(new RegExp(pattern_flags[0], pattern_flags[1]), ''), self.encoding); } end # delete! - not supported, mutates string def delete_prefix(prefix) %x{ if (!prefix.$$is_string) { prefix = $coerce_to(prefix, #{::String}, 'to_str'); } if (starts_with(self, prefix)) { return $str(self.slice(prefix.length), self.encoding); } return self; } end # delete_prefix! - not supported, mutates string def delete_suffix(suffix) %x{ if (!suffix.$$is_string) { suffix = $coerce_to(suffix, #{::String}, 'to_str'); } if (ends_with(self, suffix)) { return $str(self.slice(0, self.length - suffix.length), self.encoding); } return self; } end # delete_suffix! - not supported, mutates string def downcase(*options) %x{ let str = self; if (options.length > 0){ if (case_options_have_ascii(options, true)) { str = str.replace(/[A-Z]+/g, (match)=>{ return match.toLowerCase(); }); } else if (options.includes('fold')) { str = str.toUpperCase(); // ß -> SS str = str.toLowerCase(); // SS -> ss } } else { str = str.toLowerCase(); } return $str(str, self.encoding); } end # downcase! - not supported, mutates string def dump %x{ /* eslint-disable no-misleading-character-class */ let e = "[\\\\\"\x00-\x1F\x7F-\xFF\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f" + String.fromCharCode(0xd800) + '-' + String.fromCharCode(0xdfff) + "\ufeff\ufff0-\uffff]", escapable = new RegExp(e, 'g'), meta = { '\u0007': '\\a', '\u001b': '\\e', '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '\v': '\\v', '"' : '\\"',
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
true
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/process.rb
opal/corelib/process.rb
# backtick_javascript: true module ::Process @__clocks__ = [] def self.__register_clock__(name, func) const_set name, @__clocks__.size @__clocks__ << func end __register_clock__ :CLOCK_REALTIME, `function() { return Date.now() }` monotonic = false %x{ if (Opal.global.performance) { monotonic = function() { return performance.now() }; } else if (Opal.global.process && process.hrtime) { // let now be the base to get smaller numbers var hrtime_base = process.hrtime(); monotonic = function() { var hrtime = process.hrtime(hrtime_base); var us = (hrtime[1] / 1000) | 0; // cut below microsecs; return ((hrtime[0] * 1000) + (us / 1000)); }; } } __register_clock__(:CLOCK_MONOTONIC, monotonic) if monotonic def self.pid 0 end def self.times t = ::Time.now.to_f ::Benchmark::Tms.new(t, t, t, t, t) end def self.clock_gettime(clock_id, unit = :float_second) (clock = @__clocks__[clock_id]) || ::Kernel.raise(::Errno::EINVAL, "clock_gettime(#{clock_id}) #{@__clocks__[clock_id]}") %x{ var ms = clock(); switch (unit) { case 'float_second': return (ms / 1000); // number of seconds as a float (default) case 'float_millisecond': return (ms / 1); // number of milliseconds as a float case 'float_microsecond': return (ms * 1000); // number of microseconds as a float case 'second': return ((ms / 1000) | 0); // number of seconds as an integer case 'millisecond': return ((ms / 1) | 0); // number of milliseconds as an integer case 'microsecond': return ((ms * 1000) | 0); // number of microseconds as an integer case 'nanosecond': return ((ms * 1000000) | 0); // number of nanoseconds as an integer default: #{::Kernel.raise ::ArgumentError, "unexpected unit: #{unit}"} } } end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/complex.rb
opal/corelib/complex.rb
# backtick_javascript: true require 'corelib/numeric' require 'corelib/complex/base' class ::Complex < ::Numeric def self.rect(real, imag = 0) unless ::Numeric === real && real.real? && ::Numeric === imag && imag.real? ::Kernel.raise ::TypeError, 'not a real' end new(real, imag) end def self.polar(r, theta = 0) unless ::Numeric === r && r.real? && ::Numeric === theta && theta.real? ::Kernel.raise ::TypeError, 'not a real' end new(r * ::Math.cos(theta), r * ::Math.sin(theta)) end attr_reader :real, :imag def initialize(real, imag = 0) @real = real @imag = imag freeze end def coerce(other) if ::Complex === other [other, self] elsif ::Numeric === other && other.real? [::Complex.new(other, 0), self] else ::Kernel.raise ::TypeError, "#{other.class} can't be coerced into Complex" end end def ==(other) if ::Complex === other @real == other.real && @imag == other.imag elsif ::Numeric === other && other.real? @real == other && @imag == 0 else other == self end end def -@ ::Kernel.Complex(-@real, -@imag) end def +(other) if ::Complex === other ::Kernel.Complex(@real + other.real, @imag + other.imag) elsif ::Numeric === other && other.real? ::Kernel.Complex(@real + other, @imag) else __coerced__ :+, other end end def -(other) if ::Complex === other ::Kernel.Complex(@real - other.real, @imag - other.imag) elsif ::Numeric === other && other.real? ::Kernel.Complex(@real - other, @imag) else __coerced__ :-, other end end def *(other) if ::Complex === other ::Kernel.Complex(@real * other.real - @imag * other.imag, @real * other.imag + @imag * other.real, ) elsif ::Numeric === other && other.real? ::Kernel.Complex(@real * other, @imag * other) else __coerced__ :*, other end end def /(other) if ::Complex === other if (::Number === @real && @real.nan?) || (::Number === @imag && @imag.nan?) || (::Number === other.real && other.real.nan?) || (::Number === other.imag && other.imag.nan?) ::Complex.new(::Float::NAN, ::Float::NAN) else self * other.conj / other.abs2 end elsif ::Numeric === other && other.real? ::Kernel.Complex(@real.quo(other), @imag.quo(other)) else __coerced__ :/, other end end def **(other) if other == 0 return ::Complex.new(1, 0) end if ::Complex === other r, theta = polar ore = other.real oim = other.imag nr = ::Math.exp(ore * ::Math.log(r) - oim * theta) ntheta = theta * ore + oim * ::Math.log(r) ::Complex.polar(nr, ntheta) elsif ::Integer === other if other > 0 x = self z = x n = other - 1 while n != 0 div, mod = n.divmod(2) while mod == 0 x = ::Kernel.Complex(x.real * x.real - x.imag * x.imag, 2 * x.real * x.imag) n = div div, mod = n.divmod(2) end z *= x n -= 1 end z else (::Rational.new(1, 1) / self)**-other end elsif ::Float === other || ::Rational === other r, theta = polar ::Complex.polar(r**other, theta * other) else __coerced__ :**, other end end def abs ::Math.hypot(@real, @imag) end def abs2 @real * @real + @imag * @imag end def angle ::Math.atan2(@imag, @real) end def conj ::Kernel.Complex(@real, -@imag) end def denominator @real.denominator.lcm(@imag.denominator) end def eql?(other) Complex === other && @real.class == @imag.class && self == other end def fdiv(other) unless ::Numeric === other ::Kernel.raise ::TypeError, "#{other.class} can't be coerced into Complex" end self / other end def finite? @real.finite? && @imag.finite? end def hash [::Complex, @real, @imag].hash end def infinite? @real.infinite? || @imag.infinite? end def inspect "(#{self})" end def numerator d = denominator ::Kernel.Complex(@real.numerator * (d / @real.denominator), @imag.numerator * (d / @imag.denominator), ) end def polar [abs, arg] end def rationalize(eps = undefined) %x{ if (arguments.length > 1) { #{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} for 0..1)"}; } } if @imag != 0 ::Kernel.raise ::RangeError, "can't convert #{self} into Rational" end real.rationalize(eps) end def real? false end def rect [@real, @imag] end def to_f unless @imag == 0 ::Kernel.raise ::RangeError, "can't convert #{self} into Float" end @real.to_f end def to_i unless @imag == 0 ::Kernel.raise ::RangeError, "can't convert #{self} into Integer" end @real.to_i end def to_r unless @imag == 0 ::Kernel.raise ::RangeError, "can't convert #{self} into Rational" end @real.to_r end def to_s result = @real.inspect result += if (::Number === @imag && @imag.nan?) || @imag.positive? || @imag.zero? '+' else '-' end result += @imag.abs.inspect if ::Number === @imag && (@imag.nan? || @imag.infinite?) result += '*' end result + 'i' end I = new(0, 1) def self.from_string(str) %x{ var re = /[+-]?[\d_]+(\.[\d_]+)?(e\d+)?/, match = str.match(re), real, imag, denominator; function isFloat() { return re.test(str); } function cutFloat() { var match = str.match(re); var number = match[0]; str = str.slice(number.length); return number.replace(/_/g, ''); } // handles both floats and rationals function cutNumber() { if (isFloat()) { var numerator = parseFloat(cutFloat()); if (str[0] === '/') { // rational real part str = str.slice(1); if (isFloat()) { var denominator = parseFloat(cutFloat()); return #{::Kernel.Rational(`numerator`, `denominator`)}; } else { // reverting '/' str = '/' + str; return numerator; } } else { // float real part, no denominator return numerator; } } else { return null; } } real = cutNumber(); if (!real) { if (str[0] === 'i') { // i => Complex(0, 1) return #{::Kernel.Complex(0, 1)}; } if (str[0] === '-' && str[1] === 'i') { // -i => Complex(0, -1) return #{::Kernel.Complex(0, -1)}; } if (str[0] === '+' && str[1] === 'i') { // +i => Complex(0, 1) return #{::Kernel.Complex(0, 1)}; } // anything => Complex(0, 0) return #{::Kernel.Complex(0, 0)}; } imag = cutNumber(); if (!imag) { if (str[0] === 'i') { // 3i => Complex(0, 3) return #{::Kernel.Complex(0, `real`)}; } else { // 3 => Complex(3, 0) return #{::Kernel.Complex(`real`, 0)}; } } else { // 3+2i => Complex(3, 2) return #{::Kernel.Complex(`real`, `imag`)}; } } end class << self alias rectangular rect end alias arg angle alias conjugate conj alias divide / alias imaginary imag alias magnitude abs alias phase arg alias quo / alias rectangular rect undef negative? undef positive? undef step end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/trace_point.rb
opal/corelib/trace_point.rb
# backtick_javascript: true class ::TracePoint # partial implementation of TracePoint # supports :class and :end events def self.trace(event, &block) new(event, &block).enable end attr_reader :event def initialize(event, &block) unless event == :class || event == :end ::Kernel.raise 'Only the :class and :end events are supported' end @event = event @block = block @trace_object = nil @trace_evt = "trace_#{@event}" @tracers_for_evt = "tracers_for_#{@event}" end def enable(*args, &enable_block) previous_state = enabled? %x{ Opal[#{@tracers_for_evt}].push(self); Opal[#{@trace_evt}] = true; } if block_given? yield disable end previous_state end def enabled? `Opal[#{@trace_evt}] && Opal[#{@tracers_for_evt}].includes(self)` end def disable %x{ var idx = Opal[#{@tracers_for_evt}].indexOf(self) if (idx > -1) { Opal[#{@tracers_for_evt}].splice(idx, 1); if (Opal[#{@tracers_for_evt}].length === 0) { Opal[#{@trace_evt}] = false; } return true; } else { return false; } } end def self @trace_object end # Current path during callback def path # Use the Ruby-level caller to determine the current file path (first non-runtime frame) loc = ::Kernel.caller(2, 1) return nil unless loc loc.split(':in `').first end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/random.rb
opal/corelib/random.rb
# helpers: truthy # backtick_javascript: true # use_strict: true require 'corelib/random/formatter' class ::Random attr_reader :seed, :state def self._verify_count(count) %x{ if (!$truthy(count)) count = 16; if (typeof count !== "number") count = #{`count`.to_int}; if (count < 0) #{::Kernel.raise ::ArgumentError, 'negative string size (or size too big)'}; count = Math.floor(count); return count; } end def initialize(seed = ::Random.new_seed) seed = ::Opal.coerce_to!(seed, ::Integer, :to_int) @state = seed reseed(seed) end def reseed(seed) @seed = seed `self.$rng = Opal.$$rand.reseed(seed)` end def self.new_seed `Opal.$$rand.new_seed()` end def self.rand(limit = undefined) self::DEFAULT.rand(limit) end def self.srand(n = ::Random.new_seed) n = ::Opal.coerce_to!(n, ::Integer, :to_int) previous_seed = self::DEFAULT.seed self::DEFAULT.reseed(n) previous_seed end def self.urandom(size) ::SecureRandom.bytes(size) end def ==(other) return false unless ::Random === other seed == other.seed && state == other.state end def bytes(length) length = ::Random._verify_count(length) ::Array.new(length) { rand(255).chr }.join.encode('ASCII-8BIT') end def self.bytes(length) self::DEFAULT.bytes(length) end def rand(limit = undefined) random_number(limit) end # Not part of the Ruby interface (use #random_number for portability), but # used by Random::Formatter as a shortcut, as for Random interface the float # RNG is primary. def random_float %x{ self.state++; return Opal.$$rand.rand(self.$rng); } end def self.random_float self::DEFAULT.random_float end def self.generator=(generator) `Opal.$$rand = #{generator}` if const_defined? :DEFAULT self::DEFAULT.reseed else const_set :DEFAULT, new(new_seed) end end end require 'corelib/random/mersenne_twister'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/enumerable.rb
opal/corelib/enumerable.rb
# helpers: truthy, coerce_to, yield1, yieldX, deny_frozen_access # backtick_javascript: true # use_strict: true module ::Enumerable %x{ function comparableForPattern(value) { if (value.length === 0) { value = [nil]; } if (value.length > 1) { value = [value]; } return value; } } def all?(pattern = undefined, &block) if `pattern !== undefined` each do |*value| comparable = `comparableForPattern(value)` return false unless pattern.public_send(:===, *comparable) end elsif block_given? each do |*value| unless yield(*value) return false end end else each do |*value| unless ::Opal.destructure(value) return false end end end true end def any?(pattern = undefined, &block) if `pattern !== undefined` each do |*value| comparable = `comparableForPattern(value)` return true if pattern.public_send(:===, *comparable) end elsif block_given? each do |*value| if yield(*value) return true end end else each do |*value| if ::Opal.destructure(value) return true end end end false end def chunk(&block) return to_enum(:chunk) { enumerator_size } unless block_given? ::Enumerator.new do |yielder| %x{ var previous = nil, accumulate = []; function releaseAccumulate() { if (accumulate.length > 0) { #{yielder.yield(`previous`, `accumulate`)} } } self.$each.$$p = function(value) { var key = $yield1(block, value); if (key === nil) { releaseAccumulate(); accumulate = []; previous = nil; } else { if (previous === nil || previous === key) { accumulate.push(value); } else { releaseAccumulate(); accumulate = [value]; } previous = key; } } self.$each(); releaseAccumulate(); } end end def chunk_while(&block) ::Kernel.raise ::ArgumentError, 'no block given' unless block_given? slice_when { |before, after| !(yield before, after) } end def collect(&block) return enum_for(:collect) { enumerator_size } unless block_given? %x{ var result = []; self.$each.$$p = function() { var value = $yieldX(block, arguments); result.push(value); }; self.$each(); return result; } end def collect_concat(&block) return enum_for(:collect_concat) { enumerator_size } unless block_given? map(&block).flatten(1) end def compact to_a.compact end def count(object = undefined, &block) result = 0 %x{ if (object != null && block !== nil) { #{warn('warning: given block not used')} } } if `object != null` block = ::Kernel.proc do |*args| ::Opal.destructure(args) == object end elsif block.nil? block = ::Kernel.proc { true } end each do |*args| `result++` if `$yieldX(block, args)` end result end def cycle(n = nil, &block) unless block_given? return enum_for(:cycle, n) do if n.nil? respond_to?(:size) ? ::Float::INFINITY : nil else n = ::Opal.coerce_to!(n, ::Integer, :to_int) n > 0 ? enumerator_size * n : 0 end end end unless n.nil? n = ::Opal.coerce_to! n, ::Integer, :to_int return if `n <= 0` end %x{ var all = [], i, length, value; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); all.push(param); } self.$each(); if (all.length === 0) { return nil; } if (n === nil) { while (true) { for (i = 0, length = all.length; i < length; i++) { value = $yield1(block, all[i]); } } } else { while (n > 1) { for (i = 0, length = all.length; i < length; i++) { value = $yield1(block, all[i]); } n--; } } } end def detect(ifnone = undefined, &block) return enum_for :detect, ifnone unless block_given? each do |*args| value = ::Opal.destructure(args) if yield(value) return value end end %x{ if (ifnone !== undefined) { if (typeof(ifnone) === 'function') { return ifnone(); } else { return ifnone; } } } nil end def drop(number) number = `$coerce_to(number, #{::Integer}, 'to_int')` if `number < 0` ::Kernel.raise ::ArgumentError, 'attempt to drop negative size' end %x{ var result = [], current = 0; self.$each.$$p = function() { if (number <= current) { result.push(#{::Opal.destructure(`arguments`)}); } current++; }; self.$each() return result; } end def drop_while(&block) return enum_for :drop_while unless block_given? %x{ var result = [], dropping = true; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}; if (dropping) { var value = $yield1(block, param); if (!$truthy(value)) { dropping = false; result.push(param); } } else { result.push(param); } }; self.$each(); return result; } end def each_cons(n, &block) if `arguments.length != 1` ::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} for 1)" end n = ::Opal.try_convert n, ::Integer, :to_int if `n <= 0` ::Kernel.raise ::ArgumentError, 'invalid size' end unless block_given? return enum_for(:each_cons, n) do enum_size = enumerator_size if enum_size.nil? nil elsif enum_size == 0 || enum_size < n 0 else enum_size - n + 1 end end end %x{ var buffer = []; self.$each.$$p = function() { var element = #{::Opal.destructure(`arguments`)}; buffer.push(element); if (buffer.length > n) { buffer.shift(); } if (buffer.length == n) { $yield1(block, buffer.slice(0, n)); } } self.$each(); return self; } end def each_entry(*data, &block) unless block_given? return to_enum(:each_entry, *data) { enumerator_size } end %x{ self.$each.$$p = function() { var item = #{::Opal.destructure(`arguments`)}; $yield1(block, item); } self.$each.apply(self, data); return self; } end def each_slice(n, &block) n = `$coerce_to(#{n}, #{::Integer}, 'to_int')` if `n <= 0` ::Kernel.raise ::ArgumentError, 'invalid slice size' end return enum_for(:each_slice, n) { respond_to?(:size) ? (size / n).ceil : nil } unless block_given? %x{ var slice = [] self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}; slice.push(param); if (slice.length === n) { $yield1(block, slice); slice = []; } }; self.$each(); // our "last" group, if smaller than n then won't have been yielded if (slice.length > 0) { $yield1(block, slice); } } self end def each_with_index(*args, &block) return enum_for(:each_with_index, *args) { enumerator_size } unless block_given? %x{ var index = 0; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}; block(param, index); index++; }; self.$each.apply(self, args); } self end def each_with_object(object, &block) return enum_for(:each_with_object, object) { enumerator_size } unless block_given? %x{ self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}; block(param, object); }; self.$each(); } object end def entries(*args) %x{ var result = []; self.$each.$$p = function() { result.push(#{::Opal.destructure(`arguments`)}); }; self.$each.apply(self, args); return result; } end def filter_map(&block) return enum_for(:filter_map) { enumerator_size } unless block_given? map(&block).select(&:itself) end def find_all(&block) return enum_for(:find_all) { enumerator_size } unless block_given? %x{ var result = []; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); if ($truthy(value)) { result.push(param); } }; self.$each(); return result; } end def find_index(object = undefined, &block) return enum_for :find_index if `object === undefined && block === nil` %x{ if (object != null && block !== nil) { #{warn('warning: given block not used')} } } index = 0 if `object != null` each do |*value| if ::Opal.destructure(value) == object return index end `index += 1` end else each do |*value| if yield(*value) return index end `index += 1` end end nil end def first(number = undefined) if `number === undefined` each do |value| return value end nil else result = [] number = `$coerce_to(number, #{::Integer}, 'to_int')` if `number < 0` ::Kernel.raise ::ArgumentError, 'attempt to take negative size' end if `number == 0` return [] end current = 0 each do |*args| `result.push(#{::Opal.destructure(args)})` if `number <= ++current` return result end end result end end def grep(pattern, &block) result = [] each do |*value| cmp = `comparableForPattern(value)` next unless pattern.__send__(:===, *cmp) if block_given? value = [value] if value.length > 1 value = yield(*value) elsif value.length <= 1 value = value[0] end result.push(value) end result end def grep_v(pattern, &block) result = [] each do |*value| cmp = `comparableForPattern(value)` next if pattern.__send__(:===, *cmp) if block_given? value = [value] if value.length > 1 value = yield(*value) elsif value.length <= 1 value = value[0] end result.push(value) end result end def group_by(&block) return enum_for(:group_by) { enumerator_size } unless block_given? hash = {} %x{ var result; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); #{(hash[`value`] ||= []) << `param`}; } self.$each(); if (result !== undefined) { return result; } } hash end def include?(obj) each do |*args| if ::Opal.destructure(args) == obj return true end end false end def inject(object = undefined, sym = undefined, &block) %x{ var result = object; if (block !== nil && sym === undefined) { self.$each.$$p = function() { var value = #{::Opal.destructure(`arguments`)}; if (result === undefined) { result = value; return; } value = $yieldX(block, [result, value]); result = value; }; } else { if (sym === undefined) { if (!#{::Symbol === object}) { #{::Kernel.raise ::TypeError, "#{object.inspect} is not a Symbol"}; } sym = object; result = undefined; } self.$each.$$p = function() { var value = #{::Opal.destructure(`arguments`)}; if (result === undefined) { result = value; return; } result = #{`result`.__send__ sym, `value`}; }; } self.$each(); return result == undefined ? nil : result; } end def lazy ::Enumerator::Lazy.new(self, enumerator_size) do |enum, *args| enum.yield(*args) end end def enumerator_size respond_to?(:size) ? size : nil end def max(n = undefined, &block) %x{ if (n === undefined || n === nil) { var result, value; self.$each.$$p = function() { var item = #{::Opal.destructure(`arguments`)}; if (result === undefined) { result = item; return; } if (block !== nil) { value = $yieldX(block, [item, result]); } else { value = #{`item` <=> `result`}; } if (value === nil) { #{::Kernel.raise ::ArgumentError, 'comparison failed'}; } if (value > 0) { result = item; } } self.$each(); if (result === undefined) { return nil; } else { return result; } } n = $coerce_to(n, #{::Integer}, 'to_int'); } sort(&block).reverse.first(n) end def max_by(n = nil, &block) return enum_for(:max_by, n) { enumerator_size } unless block unless n.nil? return sort_by(&block).reverse.take n end %x{ var result, by; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); if (result === undefined) { result = param; by = value; return; } if (#{`value` <=> `by`} > 0) { result = param by = value; } }; self.$each(); return result === undefined ? nil : result; } end def min(n = nil, &block) unless n.nil? if block_given? return sort { |a, b| yield a, b }.take n else return sort.take n end end %x{ var result; if (block !== nil) { self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}; if (result === undefined) { result = param; return; } var value = block(param, result); if (value === nil) { #{::Kernel.raise ::ArgumentError, 'comparison failed'}; } if (value < 0) { result = param; } }; } else { self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}; if (result === undefined) { result = param; return; } if (#{::Opal.compare(`param`, `result`)} < 0) { result = param; } }; } self.$each(); return result === undefined ? nil : result; } end def min_by(n = nil, &block) return enum_for(:min_by, n) { enumerator_size } unless block unless n.nil? return sort_by(&block).take n end %x{ var result, by; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); if (result === undefined) { result = param; by = value; return; } if (#{`value` <=> `by`} < 0) { result = param by = value; } }; self.$each(); return result === undefined ? nil : result; } end def minmax(&block) block ||= ::Kernel.proc { |a, b| a <=> b } %x{ var min = nil, max = nil, first_time = true; self.$each.$$p = function() { var element = #{::Opal.destructure(`arguments`)}; if (first_time) { min = max = element; first_time = false; } else { var min_cmp = #{block.call(`min`, `element`)}; if (min_cmp === nil) { #{::Kernel.raise ::ArgumentError, 'comparison failed'} } else if (min_cmp > 0) { min = element; } var max_cmp = #{block.call(`max`, `element`)}; if (max_cmp === nil) { #{::Kernel.raise ::ArgumentError, 'comparison failed'} } else if (max_cmp < 0) { max = element; } } } self.$each(); return [min, max]; } end def minmax_by(&block) return enum_for(:minmax_by) { enumerator_size } unless block %x{ var min_result = nil, max_result = nil, min_by, max_by; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); if ((min_by === undefined) || #{`value` <=> `min_by`} < 0) { min_result = param; min_by = value; } if ((max_by === undefined) || #{`value` <=> `max_by`} > 0) { max_result = param; max_by = value; } }; self.$each(); return [min_result, max_result]; } end def none?(pattern = undefined, &block) if `pattern !== undefined` each do |*value| comparable = `comparableForPattern(value)` return false if pattern.public_send(:===, *comparable) end elsif block_given? each do |*value| if yield(*value) return false end end else each do |*value| item = ::Opal.destructure(value) return false if item end end true end def one?(pattern = undefined, &block) count = 0 if `pattern !== undefined` each do |*value| comparable = `comparableForPattern(value)` if pattern.public_send(:===, *comparable) count += 1 return false if count > 1 end end elsif block_given? each do |*value| next unless yield(*value) count += 1 return false if count > 1 end else each do |*value| next unless ::Opal.destructure(value) count += 1 return false if count > 1 end end count == 1 end def partition(&block) return enum_for(:partition) { enumerator_size } unless block_given? %x{ var truthy = [], falsy = [], result; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); if ($truthy(value)) { truthy.push(param); } else { falsy.push(param); } }; self.$each(); return [truthy, falsy]; } end def reject(&block) return enum_for(:reject) { enumerator_size } unless block_given? %x{ var result = []; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); if (!$truthy(value)) { result.push(param); } }; self.$each(); return result; } end def reverse_each(&block) return enum_for(:reverse_each) { enumerator_size } unless block_given? %x{ var result = []; self.$each.$$p = function() { result.push(arguments); }; self.$each(); for (var i = result.length - 1; i >= 0; i--) { $yieldX(block, result[i]); } return result; } end def slice_before(pattern = undefined, &block) if `pattern === undefined && block === nil` ::Kernel.raise ::ArgumentError, 'both pattern and block are given' end if `pattern !== undefined && block !== nil || arguments.length > 1` ::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} expected 1)" end ::Enumerator.new do |e| %x{ var slice = []; if (block !== nil) { if (pattern === undefined) { self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = $yield1(block, param); if ($truthy(value) && slice.length > 0) { #{e << `slice`}; slice = []; } slice.push(param); }; } else { self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = block(param, #{pattern.dup}); if ($truthy(value) && slice.length > 0) { #{e << `slice`}; slice = []; } slice.push(param); }; } } else { self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}, value = #{pattern === `param`}; if ($truthy(value) && slice.length > 0) { #{e << `slice`}; slice = []; } slice.push(param); }; } self.$each(); if (slice.length > 0) { #{e << `slice`}; } } end end def slice_after(pattern = undefined, &block) if `pattern === undefined && block === nil` ::Kernel.raise ::ArgumentError, 'both pattern and block are given' end if `pattern !== undefined && block !== nil || arguments.length > 1` ::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} expected 1)" end if `pattern !== undefined` block = ::Kernel.proc { |e| pattern === e } end ::Enumerator.new do |yielder| %x{ var accumulate; self.$each.$$p = function() { var element = #{::Opal.destructure(`arguments`)}, end_chunk = $yield1(block, element); if (accumulate == null) { accumulate = []; } if ($truthy(end_chunk)) { accumulate.push(element); #{yielder.yield(`accumulate`)}; accumulate = null; } else { accumulate.push(element) } } self.$each(); if (accumulate != null) { #{yielder.yield(`accumulate`)}; } } end end def slice_when(&block) ::Kernel.raise ::ArgumentError, 'wrong number of arguments (0 for 1)' unless block_given? ::Enumerator.new do |yielder| %x{ var slice = nil, last_after = nil; self.$each_cons.$$p = function() { var params = #{::Opal.destructure(`arguments`)}, before = params[0], after = params[1], match = $yieldX(block, [before, after]); last_after = after; if (slice === nil) { slice = []; } if ($truthy(match)) { slice.push(before); #{yielder.yield(`slice`)}; slice = []; } else { slice.push(before); } } self.$each_cons(2); if (slice !== nil) { slice.push(last_after); #{yielder.yield(`slice`)}; } } end end def sort(&block) ary = to_a block = ->(a, b) { a <=> b } unless block_given? ary.sort(&block) end def sort_by(&block) return enum_for(:sort_by) { enumerator_size } unless block_given? dup = map do arg = ::Opal.destructure(`arguments`) [yield(arg), arg] end dup.sort! { |a, b| `a[0]` <=> `b[0]` } dup.map! { |i| `i[1]` } end # This method implements the Kahan summation algorithm if it is possible to apply one. def sum(initial = 0) result = initial compensation = 0 each do |*args| item = if block_given? yield(*args) else ::Opal.destructure(args) end if ![::Float::INFINITY, -::Float::INFINITY].include?(item) && item.respond_to?(:-) y = item - compensation t = result + y compensation = (t - result) - y result = t else result += item end end result end def take(num) first(num) end def take_while(&block) return enum_for :take_while unless block result = [] each do |*args| value = ::Opal.destructure(args) unless yield(value) return result end `result.push(value)` end end def uniq(&block) hash = {} each do |*args| value = ::Opal.destructure(args) produced = if block_given? yield(value) else value end unless hash.key?(produced) hash[produced] = value end end hash.values end def tally(hash = undefined) `if (hash && hash !== nil) { $deny_frozen_access(hash); }` out = group_by(&:itself).transform_values(&:count) if hash out.each { |k, v| hash[k] = hash.fetch(k, 0) + v } hash else out end end def to_h(*args, &block) return map(&block).to_h(*args) if block_given? %x{ var hash = #{{}}; self.$each.$$p = function() { var param = #{::Opal.destructure(`arguments`)}; var ary = #{::Opal.coerce_to?(`param`, ::Array, :to_ary)}, key, val; if (!ary.$$is_array) { #{::Kernel.raise ::TypeError, "wrong element type #{`param`.class} (expected array)"} } if (ary.length !== 2) { #{::Kernel.raise ::ArgumentError, "element has wrong array length (expected 2, was #{`ary`.length})"} } key = ary[0]; val = ary[1]; Opal.hash_put(hash, key, val); }; self.$each.apply(self, args); return hash; } end def to_set(klass = ::Set, *args, &block) klass.new(self, *args, &block) end def zip(*others, &block) to_a.zip(*others) end alias find detect alias filter find_all alias flat_map collect_concat alias map collect alias member? include? alias reduce inject alias select find_all alias to_a entries end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/runtime.rb
opal/corelib/runtime.rb
require 'runtime/runtime'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/nil.rb
opal/corelib/nil.rb
# backtick_javascript: true # use_strict: true class ::NilClass `self.$$prototype.$$meta = #{self}` class << self def allocate ::Kernel.raise ::TypeError, "allocator undefined for #{name}" end undef :new end def ! true end def &(other) false end def |(other) `other !== false && other !== nil` end def ^(other) `other !== false && other !== nil` end def ==(other) `other === nil` end def dup nil end def clone(freeze: true) nil end def inspect 'nil' end def nil? true end def singleton_class ::NilClass end def to_a [] end def to_h `new Map()` end def to_i 0 end def to_s '' end def to_c ::Complex.new(0, 0) end def rationalize(*args) ::Kernel.raise ::ArgumentError if args.length > 1 ::Kernel.Rational(0, 1) end def to_r ::Kernel.Rational(0, 1) end def instance_variables [] end alias to_f to_i end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/regexp.rb
opal/corelib/regexp.rb
# helpers: coerce_to, prop, freeze, annotate_regexp, escape_metacharacters # backtick_javascript: true # use_strict: true class ::RegexpError < ::StandardError; end class ::Regexp < `RegExp` self::IGNORECASE = 1 self::EXTENDED = 2 self::MULTILINE = 4 # Not supported: self::FIXEDENCODING = 16 self::NOENCODING = 32 `Opal.prop(self.$$prototype, '$$is_regexp', true)` `Opal.prop(self.$$prototype, '$$source', null)` `Opal.prop(self.$$prototype, '$$options', null)` `Opal.prop(self.$$prototype, '$$g', null)` class << self def allocate allocated = super `#{allocated}.uninitialized = true` allocated end def escape(string) %x{ string = $coerce_to(string, #{::String}, 'to_str'); return Opal.escape_regexp(string); } end def last_match(n = nil) if n.nil? $~ elsif $~ $~[n] end end def union(*parts) %x{ function exclude_compatible(flags) { return (flags || 0) & ~#{MULTILINE} & ~#{EXTENDED}; } function compatible_flags(first, second) { return exclude_compatible(first) == exclude_compatible(second) } var is_first_part_array, quoted_validated, part, options, each_part_options; if (parts.length == 0) { return /(?!)/; } // return fast if there's only one element if (parts.length == 1 && parts[0].$$is_regexp) { return parts[0]; } // cover the 2 arrays passed as arguments case is_first_part_array = parts[0].$$is_array; if (parts.length > 1 && is_first_part_array) { #{::Kernel.raise ::TypeError, 'no implicit conversion of Array into String'} } // deal with splat issues (related to https://github.com/opal/opal/issues/858) if (is_first_part_array) { parts = parts[0]; } options = undefined; quoted_validated = []; for (var i=0; i < parts.length; i++) { part = parts[i]; if (part.$$is_string) { quoted_validated.push(#{escape(`part`)}); } else if (part.$$is_regexp) { each_part_options = #{`part`.options}; if (options != undefined && !compatible_flags(options, each_part_options)) { #{::Kernel.raise ::TypeError, 'All expressions must use the same options'} } options = each_part_options; quoted_validated.push('(?:'+#{`part`.source}+')'); } else { quoted_validated.push(#{escape(`part`.to_str)}); } } } # Take advantage of logic that can parse options from JS Regex new(`quoted_validated`.join('|'), `options`) end def new(regexp, options = undefined) %x{ if (regexp.$$is_regexp) { return $annotate_regexp(new RegExp(regexp), regexp.$$source, regexp.$$options); } regexp = #{::Opal.coerce_to!(regexp, ::String, :to_str)}; if (regexp.charAt(regexp.length - 1) === '\\' && regexp.charAt(regexp.length - 2) !== '\\') { #{::Kernel.raise ::RegexpError, "too short escape sequence: /#{regexp}/"} } if (options === undefined || #{!options}) { options = 'u'; } else if (options.$$is_number) { var temp = 'u'; if (#{IGNORECASE} & options) { temp += 'i'; } if (#{MULTILINE} & options) { temp += 'm'; } options = temp; } else if (!options.$$is_string) { options = 'iu'; } var result = Opal.transform_regexp(regexp, options); return Opal.annotate_regexp(new RegExp(result[0], result[1]), $escape_metacharacters(regexp), options); } end alias compile new alias quote escape end def ==(other) `other instanceof RegExp && self.$options() == other.$options() && self.$source() == other.$source()` end def ===(string) `#{match(::Opal.coerce_to?(string, ::String, :to_str))} !== nil` end def =~(string) match(string) && $~.begin(0) end def freeze # Specialized version of freeze, because the $$gm and $$g properties need to be set # especially for RegExp. return self if frozen? %x{ if (!self.hasOwnProperty('$$g')) { $prop(self, '$$g', null); } return $freeze(self); } end def inspect # Use a regexp to extract the regular expression and the optional mode modifiers from the string. # In the regular expression, escape any front slash (not already escaped) with a backslash. %x{ var regexp_pattern = self.$source(); var regexp_flags = self.$$options != null ? self.$$options : self.flags; regexp_flags = regexp_flags.replace('u', ''); var chars = regexp_pattern.split(''); var chars_length = chars.length; var char_escaped = false; var regexp_pattern_escaped = ''; for (var i = 0; i < chars_length; i++) { var current_char = chars[i]; if (!char_escaped && current_char == '/') { regexp_pattern_escaped += '\\'; } regexp_pattern_escaped += current_char; if (current_char == '\\') { // does not over escape char_escaped = !char_escaped; } else { char_escaped = false; } } return '/' + regexp_pattern_escaped + '/' + regexp_flags; } end def match(string, pos = undefined, &block) %x{ if (self.uninitialized) { #{::Kernel.raise ::TypeError, 'uninitialized Regexp'} } if (pos === undefined) { if (string === nil) return #{$~ = nil}; var m = self.exec($coerce_to(string, #{::String}, 'to_str')); if (m) { #{$~ = ::MatchData.new(`self`, `m`)}; return block === nil ? #{$~} : #{yield $~}; } else { return #{$~ = nil}; } } pos = $coerce_to(pos, #{::Integer}, 'to_int'); if (string === nil) { return #{$~ = nil}; } string = $coerce_to(string, #{::String}, 'to_str'); if (pos < 0) { pos += string.length; if (pos < 0) { return #{$~ = nil}; } } // global RegExp maintains state, so not using self/this var md, re = Opal.global_regexp(self); while (true) { md = re.exec(string); if (md === null) { return #{$~ = nil}; } if (md.index >= pos) { #{$~ = ::MatchData.new(`re`, `md`)}; return block === nil ? #{$~} : #{yield $~}; } re.lastIndex = md.index + 1; } } end def match?(string, pos = undefined) %x{ if (self.uninitialized) { #{::Kernel.raise ::TypeError, 'uninitialized Regexp'} } if (pos === undefined) { return string === nil ? false : self.test($coerce_to(string, #{::String}, 'to_str')); } pos = $coerce_to(pos, #{::Integer}, 'to_int'); if (string === nil) { return false; } string = $coerce_to(string, #{::String}, 'to_str'); if (pos < 0) { pos += string.length; if (pos < 0) { return false; } } // global RegExp maintains state, so not using self/this var md, re = Opal.global_regexp(self); md = re.exec(string); if (md === null || md.index < pos) { return false; } else { return true; } } end def names source.scan(/\(?<(\w+)>/, no_matchdata: true).map(&:first).uniq end def named_captures source.scan(/\(?<(\w+)>/, no_matchdata: true) # Scan for capture groups .map(&:first) # Get the first regexp match (\w+) .each_with_index # Add index to an iterator .group_by(&:first) # Group by the capture group names .transform_values do |i| # Convert hash values i.map { |j| j.last + 1 } # Drop the capture group names; increase indexes by 1 end end def ~ self =~ $_ end def source `self.$$source != null ? self.$$source : self.source` end def options # Flags would be nice to use with this, but still experimental - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags %x{ if (self.uninitialized) { #{::Kernel.raise ::TypeError, 'uninitialized Regexp'} } var result = 0; // should be supported in IE6 according to https://msdn.microsoft.com/en-us/library/7f5z26w4(v=vs.94).aspx if (self.$$options != null ? self.$$options.includes('m') : self.multiline) { result |= #{MULTILINE}; } if (self.$$options != null ? self.$$options.includes('i') : self.ignoreCase) { result |= #{IGNORECASE}; } if (self.$$options != null ? self.$$options.includes('x') : false) { result |= #{EXTENDED}; } return result; } end def casefold? `self.ignoreCase` end alias eql? == alias to_s source end class MatchData attr_reader :post_match, :pre_match, :regexp, :string def initialize(regexp, match_groups, no_matchdata: false) $~ = self unless no_matchdata @regexp = regexp @begin = `match_groups.index` @string = `match_groups.input` @pre_match = `match_groups.input.slice(0, match_groups.index)` @post_match = `match_groups.input.slice(match_groups.index + match_groups[0].length)` @matches = [] %x{ for (var i = 0, length = match_groups.length; i < length; i++) { var group = match_groups[i]; if (group == null) { #{@matches}.push(nil); } else { #{@matches}.push(group); } } } end def match(idx) if (match = self[idx]) match elsif idx.is_a?(Integer) && idx >= length ::Kernel.raise ::IndexError, "index #{idx} out of matches" end end def match_length(idx) match(idx)&.length end def [](*args) %x{ if (args[0].$$is_string) { if (#{!regexp.names.include?(args[0])}) { #{::Kernel.raise ::IndexError, "undefined group name reference: #{args[0]}"} } return #{named_captures[args[0]]} } else { return #{@matches[*args]} } } end def offset(n) %x{ if (n !== 0) { #{::Kernel.raise ::ArgumentError, 'MatchData#offset only supports 0th element'} } return [self.begin, self.begin + self.matches[n].length]; } end def ==(other) return false unless ::MatchData === other `self.string == other.string` && `self.regexp.toString() == other.regexp.toString()` && `self.pre_match == other.pre_match` && `self.post_match == other.post_match` && `self.begin == other.begin` end def begin(n) %x{ if (n !== 0) { #{::Kernel.raise ::ArgumentError, 'MatchData#begin only supports 0th element'} } return self.begin; } end def end(n) %x{ if (n !== 0) { #{::Kernel.raise ::ArgumentError, 'MatchData#end only supports 0th element'} } return self.begin + self.matches[n].length; } end def captures `#{@matches}.slice(1)` end def named_captures matches = captures regexp.named_captures.transform_values do |i| matches[i.last - 1] end end def names regexp.names end def inspect %x{ var str = "#<MatchData " + #{`#{@matches}[0]`.inspect}; if (#{regexp.names.empty?}) { for (var i = 1, length = #{@matches}.length; i < length; i++) { str += " " + i + ":" + #{`#{@matches}[i]`.inspect}; } } else { #{ named_captures.each do |k, v| %x{ str += " " + #{k} + ":" + #{v.inspect} } end } } return str + ">"; } end def length `#{@matches}.length` end def to_a @matches end def to_s `#{@matches}[0]` end def values_at(*args) %x{ var i, a, index, values = []; for (i = 0; i < args.length; i++) { if (args[i].$$is_range) { a = #{`args[i]`.to_a}; a.unshift(i, 1); Array.prototype.splice.apply(args, a); } index = #{::Opal.coerce_to!(`args[i]`, ::Integer, :to_int)}; if (index < 0) { index += #{@matches}.length; if (index < 0) { values.push(nil); continue; } } values.push(#{@matches}[index]); } return values; } end alias eql? == alias size length end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/rational.rb
opal/corelib/rational.rb
# backtick_javascript: true require 'corelib/numeric' require 'corelib/rational/base' class ::Rational < ::Numeric def self.reduce(num, den) num = num.to_i den = den.to_i if den == 0 ::Kernel.raise ::ZeroDivisionError, 'divided by 0' elsif den < 0 num = -num den = -den elsif den == 1 return new(num, den) end gcd = num.gcd(den) new(num / gcd, den / gcd) end def self.convert(num, den) if num.nil? || den.nil? ::Kernel.raise ::TypeError, 'cannot convert nil into Rational' end if ::Integer === num && ::Integer === den return reduce(num, den) end if ::Float === num || ::String === num || ::Complex === num num = num.to_r end if ::Float === den || ::String === den || ::Complex === den den = den.to_r end if den.equal?(1) && !(::Integer === num) ::Opal.coerce_to!(num, ::Rational, :to_r) elsif ::Numeric === num && ::Numeric === den num / den else reduce(num, den) end end def initialize(num, den) @num = num @den = den freeze end def numerator @num end def denominator @den end def coerce(other) case other when ::Rational [other, self] when ::Integer [other.to_r, self] when ::Float [other, to_f] end end def ==(other) case other when ::Rational @num == other.numerator && @den == other.denominator when ::Integer @num == other && @den == 1 when ::Float to_f == other else other == self end end def <=>(other) case other when ::Rational @num * other.denominator - @den * other.numerator <=> 0 when ::Integer @num - @den * other <=> 0 when ::Float to_f <=> other else __coerced__ :<=>, other end end def +(other) case other when ::Rational num = @num * other.denominator + @den * other.numerator den = @den * other.denominator ::Kernel.Rational(num, den) when ::Integer ::Kernel.Rational(@num + other * @den, @den) when ::Float to_f + other else __coerced__ :+, other end end def -(other) case other when ::Rational num = @num * other.denominator - @den * other.numerator den = @den * other.denominator ::Kernel.Rational(num, den) when ::Integer ::Kernel.Rational(@num - other * @den, @den) when ::Float to_f - other else __coerced__ :-, other end end def *(other) case other when ::Rational num = @num * other.numerator den = @den * other.denominator ::Kernel.Rational(num, den) when ::Integer ::Kernel.Rational(@num * other, @den) when ::Float to_f * other else __coerced__ :*, other end end def /(other) case other when ::Rational num = @num * other.denominator den = @den * other.numerator ::Kernel.Rational(num, den) when ::Integer if other == 0 to_f / 0.0 else ::Kernel.Rational(@num, @den * other) end when ::Float to_f / other else __coerced__ :/, other end end def **(other) case other when ::Integer if self == 0 && other < 0 ::Float::INFINITY elsif other > 0 ::Kernel.Rational(@num**other, @den**other) elsif other < 0 ::Kernel.Rational(@den**-other, @num**-other) else ::Kernel.Rational(1, 1) end when ::Float to_f**other when ::Rational if other == 0 ::Kernel.Rational(1, 1) elsif other.denominator == 1 if other < 0 ::Kernel.Rational(@den**other.numerator.abs, @num**other.numerator.abs) else ::Kernel.Rational(@num**other.numerator, @den**other.numerator) end elsif self == 0 && other < 0 ::Kernel.raise ::ZeroDivisionError, 'divided by 0' else to_f**other end else __coerced__ :**, other end end def abs ::Kernel.Rational(@num.abs, @den.abs) end def ceil(precision = 0) if precision == 0 (-(-@num / @den)).ceil else with_precision(:ceil, precision) end end def floor(precision = 0) if precision == 0 (-(-@num / @den)).floor else with_precision(:floor, precision) end end def hash [::Rational, @num, @den].hash end def inspect "(#{self})" end def rationalize(eps = undefined) %x{ if (arguments.length > 1) { #{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} for 0..1)"}; } if (eps == null) { return self; } var e = #{eps.abs}, a = #{self - `e`}, b = #{self + `e`}; var p0 = 0, p1 = 1, q0 = 1, q1 = 0, p2, q2; var c, k, t; while (true) { c = #{`a`.ceil}; if (#{`c` <= `b`}) { break; } k = c - 1; p2 = k * p1 + p0; q2 = k * q1 + q0; t = #{1 / (`b` - `k`)}; b = #{1 / (`a` - `k`)}; a = t; p0 = p1; q0 = q1; p1 = p2; q1 = q2; } return #{::Kernel.Rational(`c * p1 + p0`, `c * q1 + q0`)}; } end def round(precision = 0) return with_precision(:round, precision) unless precision == 0 return 0 if @num == 0 return @num if @den == 1 num = @num.abs * 2 + @den den = @den * 2 approx = (num / den).truncate if @num < 0 -approx else approx end end def to_f @num / @den end def to_i truncate end def to_r self end def to_s "#{@num}/#{@den}" end def truncate(precision = 0) if precision == 0 @num < 0 ? ceil : floor else with_precision(:truncate, precision) end end def with_precision(method, precision) ::Kernel.raise ::TypeError, 'not an Integer' unless ::Integer === precision p = 10**precision s = self * p if precision < 1 (s.send(method) / p).to_i else ::Kernel.Rational(s.send(method), p) end end def self.from_string(string) %x{ var str = string.trimLeft(), re = /^[+-]?[\d_]+(\.[\d_]+)?/, match = str.match(re), numerator, denominator; function isFloat() { return re.test(str); } function cutFloat() { var match = str.match(re); var number = match[0]; str = str.slice(number.length); return number.replace(/_/g, ''); } if (isFloat()) { numerator = parseFloat(cutFloat()); if (str[0] === '/') { // rational real part str = str.slice(1); if (isFloat()) { denominator = parseFloat(cutFloat()); return #{::Kernel.Rational(`numerator`, `denominator`)}; } else { return #{::Kernel.Rational(`numerator`, 1)}; } } else { return #{::Kernel.Rational(`numerator`, 1)}; } } else { return #{::Kernel.Rational(0, 1)}; } } end alias divide / alias quo / end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/unsupported.rb
opal/corelib/unsupported.rb
# backtick_javascript: true # use_strict: true class ::String `var ERROR = "String#%s not supported. Mutable String methods are currently not supported in Opal."` %i[ << []= append_as_bytes bytesplice capitalize! chomp! chop! clear concat delete! delete_prefix! delete_suffix! downcase! encode! gsub! insert lstrip! next! prepend replace reverse! rstrip! scrub! setbyte slice! squeeze! strip! sub! succ! swapcase! tr! tr_s! unicode_normalize! upcase! ].each do |method_name| define_method method_name do |*| ::Kernel.raise ::NotImplementedError, `ERROR.replace("%s", method_name)` end end end class ::Module def public(*methods) %x{ if (methods.length === 0) { self.$$module_function = false; return nil; } return (methods.length === 1) ? methods[0] : methods; } end def private_class_method(*methods) `return (methods.length === 1) ? methods[0] : methods` end def private_method_defined?(obj) false end def private_constant(*) end def deprecate_constant(*) self end alias nesting public alias private public alias protected public alias protected_method_defined? private_method_defined? alias public_class_method private_class_method alias public_instance_method instance_method alias public_instance_methods instance_methods alias public_method_defined? method_defined? end module ::Kernel def private_methods(*methods) [] end alias protected_methods private_methods alias private_instance_methods private_methods alias protected_instance_methods private_methods end module ::Kernel def eval(*) ::Kernel.raise ::NotImplementedError, "To use Kernel#eval, you must first require 'opal-parser'. "\ "See https://github.com/opal/opal/blob/#{RUBY_ENGINE_VERSION}/docs/opal_parser.md for details." end end def self.public(*methods) `return (methods.length === 1) ? methods[0] : methods` end def self.private(*methods) `return (methods.length === 1) ? methods[0] : methods` end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/module.rb
opal/corelib/module.rb
# helpers: truthy, coerce_to, const_set, Object, return_ivar, assign_ivar, ivar, deny_frozen_access, freeze, prop, jsid, each_ivar # backtick_javascript: true # use_strict: true class ::Module %x{ function ensure_symbol_or_string(name) { if (name.$$is_string) { return name; }; var converted_name = #{::Opal.try_convert(`name`, ::String, :to_str)}; if (converted_name.$$is_string) { return converted_name; } else if (converted_name === nil) { #{::Kernel.raise ::TypeError, "#{`name`} is not a symbol nor a string"} } else { #{::Kernel.raise ::TypeError, "can't convert #{`name`.class} to String (#{`name`.class}#to_str gives #{`converted_name`.class}"} } } } def self.allocate %x{ var module = Opal.allocate_module(nil, function(){}); // Link the prototype of Module subclasses if (self !== Opal.Module) Object.setPrototypeOf(module, self.$$prototype); return module; } end def initialize(&block) module_exec(self, &block) if block_given? end def ===(object) return false if `object == null` `Opal.is_a(object, self)` end def <(other) unless ::Module === other ::Kernel.raise ::TypeError, 'compared with non class/module' end # class cannot be a descendant of itself %x{ var working = self, ancestors, i, length; if (working === other) { return false; } for (i = 0, ancestors = Opal.ancestors(self), length = ancestors.length; i < length; i++) { if (ancestors[i] === other) { return true; } } for (i = 0, ancestors = Opal.ancestors(other), length = ancestors.length; i < length; i++) { if (ancestors[i] === self) { return false; } } return nil; } end def <=(other) equal?(other) || self < other end def >(other) unless ::Module === other ::Kernel.raise ::TypeError, 'compared with non class/module' end other < self end def >=(other) equal?(other) || self > other end def <=>(other) %x{ if (self === other) { return 0; } } unless ::Module === other return nil end lt = self < other return nil if lt.nil? lt ? -1 : 1 end def alias_method(newname, oldname) `$deny_frozen_access(self)` newname = `$coerce_to(newname, #{::String}, 'to_str')` oldname = `$coerce_to(oldname, #{::String}, 'to_str')` `Opal.alias(self, newname, oldname)` self end def alias_native(mid, jsid = mid) `$deny_frozen_access(self)` `Opal.alias_native(self, mid, jsid)` self end def ancestors `Opal.ancestors(self)` end def append_features(includer) `$deny_frozen_access(includer)` `Opal.append_features(self, includer)` self end def attr_accessor(*names) attr_reader(*names) attr_writer(*names) end def attr(*args) %x{ if (args.length == 2 && (args[1] === true || args[1] === false)) { #{warn 'optional boolean argument is obsoleted', uplevel: 1} args[1] ? #{attr_accessor(`args[0]`)} : #{attr_reader(`args[0]`)}; return nil; } } attr_reader(*args) end def attr_reader(*names) %x{ $deny_frozen_access(self); var proto = self.$$prototype; for (var i = names.length - 1; i >= 0; i--) { var name = names[i], id = $jsid(name), ivar = $ivar(name); var body = $return_ivar(ivar); // initialize the instance variable as nil Opal.prop(proto, ivar, nil); body.$$parameters = []; body.$$arity = 0; Opal.defn(self, id, body); } } nil end def attr_writer(*names) %x{ $deny_frozen_access(self); var proto = self.$$prototype; for (var i = names.length - 1; i >= 0; i--) { var name = names[i], id = $jsid(name + '='), ivar = $ivar(name); var body = $assign_ivar(ivar) body.$$parameters = [['req']]; body.$$arity = 1; // initialize the instance variable as nil Opal.prop(proto, ivar, nil); Opal.defn(self, id, body); } } nil end def autoload(const, path) %x{ $deny_frozen_access(self); if (!#{Opal.const_name?(const)}) { #{::Kernel.raise ::NameError, "autoload must be constant name: #{const}"} } if (path == "") { #{::Kernel.raise ::ArgumentError, 'empty file name'} } if (!self.$$const.hasOwnProperty(#{const})) { if (!self.$$autoload) { self.$$autoload = {}; } Opal.const_cache_version++; self.$$autoload[#{const}] = { path: #{path}, loaded: false, required: false, success: false, exception: false }; if (self.$const_added && !self.$const_added.$$pristine) { self.$const_added(#{const}); } } return nil; } end def autoload?(const) %x{ if (self.$$autoload && self.$$autoload[#{const}] && !self.$$autoload[#{const}].required && !self.$$autoload[#{const}].success) { return self.$$autoload[#{const}].path; } var ancestors = self.$ancestors(); for (var i = 0, length = ancestors.length; i < length; i++) { if (ancestors[i].$$autoload && ancestors[i].$$autoload[#{const}] && !ancestors[i].$$autoload[#{const}].required && !ancestors[i].$$autoload[#{const}].success) { return ancestors[i].$$autoload[#{const}].path; } } return nil; } end def class_variables `Object.keys(Opal.class_variables(self))` end def class_variable_get(name) name = ::Opal.class_variable_name!(name) `Opal.class_variable_get(self, name, false)` end def class_variable_set(name, value) `$deny_frozen_access(self)` name = ::Opal.class_variable_name!(name) `Opal.class_variable_set(self, name, value)` end def class_variable_defined?(name) name = ::Opal.class_variable_name!(name) `Opal.class_variables(self).hasOwnProperty(name)` end def const_added(name) end ::Opal.pristine self, :const_added def remove_class_variable(name) `$deny_frozen_access(self)` name = ::Opal.class_variable_name!(name) %x{ if (Opal.hasOwnProperty.call(self.$$cvars, name)) { var value = self.$$cvars[name]; delete self.$$cvars[name]; return value; } else { #{::Kernel.raise ::NameError, "cannot remove #{name} for #{self}"} } } end def constants(inherit = true) `Opal.constants(self, inherit)` end def self.constants(inherit = undefined) %x{ if (inherit == null) { var nesting = (self.$$nesting || []).concat($Object), constant, constants = {}, i, ii; for(i = 0, ii = nesting.length; i < ii; i++) { for (constant in nesting[i].$$const) { constants[constant] = true; } } return Object.keys(constants); } else { return Opal.constants(self, inherit) } } end def self.nesting `self.$$nesting || []` end # check for constant within current scope # if inherit is true or self is Object, will also check ancestors def const_defined?(name, inherit = true) name = Opal.const_name!(name) ::Kernel.raise ::NameError.new("wrong constant name #{name}", name) unless name =~ ::Opal::CONST_NAME_REGEXP %x{ var module, modules = [self], module_constants, i, ii; // Add up ancestors if inherit is true if (inherit) { modules = modules.concat(Opal.ancestors(self)); // Add Object's ancestors if it's a module – modules have no ancestors otherwise if (self.$$is_module) { modules = modules.concat([$Object]).concat(Opal.ancestors($Object)); } } for (i = 0, ii = modules.length; i < ii; i++) { module = modules[i]; if (module.$$const[#{name}] != null) { return true; } if ( module.$$autoload && module.$$autoload[#{name}] && !module.$$autoload[#{name}].required && !module.$$autoload[#{name}].success ) { return true; } } return false; } end def const_get(name, inherit = true) name = Opal.const_name!(name) %x{ if (name.indexOf('::') === 0 && name !== '::'){ name = name.slice(2); } } if `name.indexOf('::') != -1 && name != '::'` return name.split('::').inject(self) { |o, c| o.const_get(c) } end ::Kernel.raise ::NameError.new("wrong constant name #{name}", name) unless name =~ ::Opal::CONST_NAME_REGEXP %x{ if (inherit) { return Opal.$$([self], name); } else { return Opal.const_get_local(self, name); } } end def const_missing(name) full_const_name = self == ::Object ? name : "#{self.name}::#{name}" ::Kernel.raise ::NameError.new("uninitialized constant #{full_const_name}", name) end def const_set(name, value) `$deny_frozen_access(self)` name = ::Opal.const_name!(name) if name !~ ::Opal::CONST_NAME_REGEXP || name.start_with?('::') ::Kernel.raise ::NameError.new("wrong constant name #{name}", name) end `$const_set(self, name, value)` value end def public_constant(const_name) end def define_method(name, method = undefined, &block) %x{ $deny_frozen_access(self); if (method === undefined && block === nil) #{::Kernel.raise ::ArgumentError, 'tried to create a Proc object without a block'} name = ensure_symbol_or_string(name); } if `method !== undefined` block = case method when ::Proc method when ::Method `#{method.to_proc}.$$unbound` when ::UnboundMethod `Opal.wrap_method_body(method.$$method)` else ::Kernel.raise ::TypeError, "wrong argument type #{method.class} (expected Proc/Method/UnboundMethod)" end if `!method.$$is_proc` owner = method.owner if `owner.$$is_class` && !(self <= owner) # rubocop:disable Style/InverseMethods message = `owner.$$is_singleton` ? "can't bind singleton method to a different class" : "bind argument must be a subclass of #{owner}" ::Kernel.raise ::TypeError, message end end end %x{ if (typeof(Proxy) !== 'undefined') { var meta = Object.create(null) block.$$proxy_target = block block = new Proxy(block, { apply: function(target, self, args) { var old_name = target.$$jsid, old_lambda = target.$$is_lambda; target.$$jsid = name; target.$$is_lambda = true; try { return target.apply(self, args); } catch(e) { if (e === target.$$brk || e === target.$$ret) return e.$v; throw e; } finally { target.$$jsid = old_name; target.$$is_lambda = old_lambda; } } }) } block.$$jsid = name; block.$$s = null; block.$$def = block; block.$$define_meth = true; return Opal.defn(self, $jsid(name), block); } end def freeze # Specialized version of freeze, because the $$base_module property needs to be # accessible despite the frozen status return self if frozen? %x{ if (!self.hasOwnProperty('$$base_module')) { $prop(self, '$$base_module', null); } return $freeze(self); } end def remove_method(*names) %x{ for (var i = 0; i < names.length; i++) { var name = ensure_symbol_or_string(names[i]); $deny_frozen_access(self); Opal.rdef(self, "$" + name); } } self end def singleton_class? `!!self.$$is_singleton` end def include(*mods) %x{ for (var i = mods.length - 1; i >= 0; i--) { var mod = mods[i]; if (!mod.$$is_module) { #{::Kernel.raise ::TypeError, "wrong argument type #{`mod`.class} (expected Module)"}; } #{`mod`.append_features self}; #{`mod`.included self}; } } self end def included_modules `Opal.included_modules(self)` end def include?(mod) %x{ if (!mod.$$is_module) { #{::Kernel.raise ::TypeError, "wrong argument type #{`mod`.class} (expected Module)"}; } var i, ii, mod2, ancestors = Opal.ancestors(self); for (i = 0, ii = ancestors.length; i < ii; i++) { mod2 = ancestors[i]; if (mod2 === mod && mod2 !== self) { return true; } } return false; } end def instance_method(name) %x{ var meth = self.$$prototype[$jsid(name)]; if (!meth || meth.$$stub) { #{::Kernel.raise ::NameError.new("undefined method `#{name}' for class `#{self.name}'", name)}; } return #{::UnboundMethod.new(self, `meth.$$owner || #{self}`, `meth`, name)}; } end def instance_methods(include_super = true) %x{ if ($truthy(#{include_super})) { return Opal.instance_methods(self); } else { return Opal.own_instance_methods(self); } } end def included(mod) end def extended(mod) end def extend_object(object) `$deny_frozen_access(object)` nil end def method_added(*) end def method_removed(*) end def method_undefined(*) end def module_eval(*args, &block) if block.nil? && `!!Opal.compile` ::Kernel.raise ::ArgumentError, 'wrong number of arguments (0 for 1..3)' unless (1..3).cover? args.size string, file, _lineno = *args default_eval_options = { file: file || '(eval)', eval: true } compiling_options = __OPAL_COMPILER_CONFIG__.merge(default_eval_options) compiled = ::Opal.compile string, compiling_options block = ::Kernel.proc do %x{new Function("Opal,self", "return " + compiled)(Opal, self)} end elsif args.any? ::Kernel.raise ::ArgumentError, "wrong number of arguments (#{args.size} for 0)" \ "\n\n NOTE:If you want to enable passing a String argument please add \"require 'opal-parser'\" to your script\n" end %x{ var old = block.$$s, result; block.$$s = null; result = block.apply(self, [self]); block.$$s = old; return result; } end def module_exec(*args, &block) %x{ if (block === nil) { #{::Kernel.raise ::LocalJumpError, 'no block given'} } var block_self = block.$$s, result; block.$$s = null; result = block.apply(self, args); block.$$s = block_self; return result; } end def method_defined?(method) %x{ var body = self.$$prototype[$jsid(method)]; return (!!body) && !body.$$stub; } end def module_function(*methods) %x{ $deny_frozen_access(self); if (methods.length === 0) { self.$$module_function = true; return nil; } else { for (var i = 0, length = methods.length; i < length; i++) { var meth = methods[i], id = $jsid(meth), func = self.$$prototype[id]; Opal.defs(self, id, func); } return methods.length === 1 ? methods[0] : methods; } return self; } end def name %x{ if (self.$$full_name) { return self.$$full_name; } var result = [], base = self; while (base) { // Give up if any of the ancestors is unnamed if (base.$$name === nil || base.$$name == null) return nil; result.unshift(base.$$name); base = base.$$base_module; if (base === $Object) { break; } } if (result.length === 0) { return nil; } return self.$$full_name = result.join('::'); } end def prepend(*mods) %x{ if (mods.length === 0) { #{::Kernel.raise ::ArgumentError, 'wrong number of arguments (given 0, expected 1+)'} } for (var i = mods.length - 1; i >= 0; i--) { var mod = mods[i]; if (!mod.$$is_module) { #{::Kernel.raise ::TypeError, "wrong argument type #{`mod`.class} (expected Module)"}; } #{`mod`.prepend_features self}; #{`mod`.prepended self}; } } self end def prepend_features(prepender) %x{ $deny_frozen_access(prepender); if (!self.$$is_module) { #{::Kernel.raise ::TypeError, "wrong argument type #{self.class} (expected Module)"}; } Opal.prepend_features(self, prepender) } self end def prepended(mod) end def remove_const(name) `$deny_frozen_access(self)` `Opal.const_remove(self, name)` end def to_s `Opal.Module.$name.call(self)` || "#<#{`self.$$is_module ? 'Module' : 'Class'`}:0x#{__id__.to_s(16)}>" end def undef_method(*names) %x{ for (var i = 0; i < names.length; i++) { var name = ensure_symbol_or_string(names[i]); $deny_frozen_access(self); Opal.udef(self, "$" + name); } } self end def instance_variables consts = constants %x{ var result = []; $each_ivar(self, function(name) { if (name !== 'constructor' && !#{consts.include?(`name`)}) { result.push('@' + name); } }); return result; } end def initialize_copy(other) %x{ function copyInstanceMethods(from, to) { var i, method_names = Opal.own_instance_methods(from); for (i = 0; i < method_names.length; i++) { var name = method_names[i], jsid = $jsid(name), body = from.$$prototype[jsid], wrapped = Opal.wrap_method_body(body); wrapped.$$jsid = name; Opal.defn(to, jsid, wrapped); } } function copyIncludedModules(from, to) { var modules = from.$$own_included_modules; for (var i = modules.length - 1; i >= 0; i--) { Opal.append_features(modules[i], to); } } function copyPrependedModules(from, to) { var modules = from.$$own_prepended_modules; for (var i = modules.length - 1; i >= 0; i--) { Opal.prepend_features(modules[i], to); } } copyInstanceMethods(other, self); copyIncludedModules(other, self); copyPrependedModules(other, self); self.$$cloned_from = other.$$cloned_from.concat(other); } copy_class_variables(other) copy_constants(other) end def initialize_dup(other) super # Unlike other classes, Module's singleton methods are copied on Object#dup. copy_singleton_methods(other) end def copy_class_variables(other) %x{ for (var name in other.$$cvars) { self.$$cvars[name] = other.$$cvars[name]; } } end def copy_constants(other) %x{ var name, other_constants = other.$$const; for (name in other_constants) { $const_set(self, name, other_constants[name]); } } end def refine(klass, &block) refinement_module, m, klass_id = self, nil, nil %x{ klass_id = Opal.id(klass); if (typeof self.$$refine_modules === "undefined") { self.$$refine_modules = Object.create(null); } if (typeof self.$$refine_modules[klass_id] === "undefined") { m = self.$$refine_modules[klass_id] = #{::Refinement.new}; } else { m = self.$$refine_modules[klass_id]; } m.refinement_module = refinement_module m.refined_class = klass } m.class_exec(&block) m end def refinements %x{ var refine_modules = self.$$refine_modules, hash = #{{}};; if (typeof refine_modules === "undefined") return hash; for (var id in refine_modules) { hash['$[]='](refine_modules[id].refined_class, refine_modules[id]); } return hash; } end # Compiler overrides this method def using(mod) ::Kernel.raise 'Module#using is not permitted in methods' end alias class_eval module_eval alias class_exec module_exec alias inspect to_s end class ::Refinement < ::Module attr_reader :refined_class def inspect if @refinement_module "#<refinement:#{@refined_class.inspect}@#{@refinement_module.inspect}>" else super end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/basic_object.rb
opal/corelib/basic_object.rb
# use_strict: true # backtick_javascript: true class ::BasicObject def initialize(*) end def ==(other) `self === other` end def eql?(other) self == other end alias equal? == def __id__ %x{ if (self.$$id != null) { return self.$$id; } Opal.prop(self, '$$id', Opal.uid()); return self.$$id; } end def __send__(symbol, *args, &block) %x{ if (!symbol.$$is_string) { #{raise ::TypeError, "#{inspect} is not a symbol nor a string"} } var func = self[Opal.jsid(symbol)]; if (func) { if (block !== nil) { func.$$p = block; } return func.apply(self, args); } if (block !== nil) { self.$method_missing.$$p = block; } return self.$method_missing.apply(self, [symbol].concat(args)); } end def ! false end ::Opal.pristine :! def !=(other) !(self == other) end def instance_eval(*args, &block) if block.nil? && `!!Opal.compile` ::Kernel.raise ::ArgumentError, 'wrong number of arguments (0 for 1..3)' unless (1..3).cover? args.size string, file, _lineno = *args default_eval_options = { file: file || '(eval)', eval: true } compiling_options = __OPAL_COMPILER_CONFIG__.merge(default_eval_options) compiled = ::Opal.compile string, compiling_options block = ::Kernel.proc do %x{new Function("Opal,self", "return " + compiled)(Opal, self)} end elsif block.nil? && args.length >= 1 && args.first[0] == '@' # get instance variable return instance_variable_get(args.first) elsif args.any? ::Kernel.raise ::ArgumentError, "wrong number of arguments (#{args.size} for 0)" end %x{ var old = block.$$s, result; block.$$s = null; // Need to pass $$eval so that method definitions know if this is // being done on a class/module. Cannot be compiler driven since // send(:instance_eval) needs to work. if (self.$$is_a_module) { self.$$eval = true; try { result = block.call(self, self); } finally { self.$$eval = false; } } else { result = block.call(self, self); } block.$$s = old; return result; } end def instance_exec(*args, &block) ::Kernel.raise ::ArgumentError, 'no block given' unless block %x{ var block_self = block.$$s, result; block.$$s = null; if (self.$$is_a_module) { self.$$eval = true; try { result = block.apply(self, args); } finally { self.$$eval = false; } } else { result = block.apply(self, args); } block.$$s = block_self; return result; } end def singleton_method_added(*) end def singleton_method_removed(*) end def singleton_method_undefined(*) end def method_missing(symbol, *args, &block) inspect_result = ::Opal.inspect(self) ::Kernel.raise ::NoMethodError.new( "undefined method `#{symbol}' for #{inspect_result}", symbol, args ), nil, ::Kernel.caller(1) end ::Opal.pristine(self, :method_missing) def respond_to_missing?(method_name, include_all = false) false end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/marshal.rb
opal/corelib/marshal.rb
require 'corelib/marshal/read_buffer' require 'corelib/marshal/write_buffer' module ::Marshal MAJOR_VERSION = 4 MINOR_VERSION = 8 class << self def dump(object) self::WriteBuffer.new(object).write end def load(marshaled) self::ReadBuffer.new(marshaled).read end alias restore load end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/hash.rb
opal/corelib/hash.rb
# helpers: yield1, hash_clone, hash_delete, hash_each, hash_get, hash_put, deny_frozen_access, freeze, opal32_init, opal32_add # backtick_javascript: true # use_strict: true require 'corelib/enumerable' # --- # Internal properties: # # - $$keys [Map<key-array>] optional Map of key arrays, used when objects are used as keys # - $$proc [Proc,null,nil] the default proc used for missing keys # - key-array [JS::Map] an element of a array that holds objects used as keys, `{ key_hash => [objects...] }` class ::Hash < `Map` include ::Enumerable # Mark all hash instances as valid hashes (used to check keyword args, etc) `self.$$prototype.$$is_hash = true` def self.[](*argv) %x{ var hash, argc = argv.length, arg, i; if (argc === 1) { hash = #{::Opal.coerce_to?(argv[0], ::Hash, :to_hash)}; if (hash !== nil) { return #{allocate.merge!(`hash`)}; } argv = #{::Opal.coerce_to?(argv[0], ::Array, :to_ary)}; if (argv === nil) { #{::Kernel.raise ::ArgumentError, 'odd number of arguments for Hash'}; } argc = argv.length; hash = #{allocate}; for (i = 0; i < argc; i++) { arg = argv[i]; if (!arg.$$is_array) #{::Kernel.raise ::ArgumentError, "invalid element #{`arg`.inspect} for Hash"}; if (arg.length === 1) { hash.$store(arg[0], nil); } else if (arg.length === 2) { hash.$store(arg[0], arg[1]); } else { #{::Kernel.raise ::ArgumentError, "invalid number of elements (#{`arg.length`} for #{`arg`.inspect}), must be 1..2"}; } } return hash; } if (argc % 2 !== 0) { #{::Kernel.raise ::ArgumentError, 'odd number of arguments for Hash'} } hash = #{allocate}; for (i = 0; i < argc; i += 2) { hash.$store(argv[i], argv[i + 1]); } return hash; } end def self.allocate %x{ var hash = new self.$$constructor(); hash.$$none = nil; hash.$$proc = nil; return hash; } end def self.try_convert(obj) ::Opal.coerce_to?(obj, ::Hash, :to_hash) end def initialize(defaults = undefined, &block) %x{ $deny_frozen_access(self); if (defaults !== undefined && block !== nil) { #{::Kernel.raise ::ArgumentError, 'wrong number of arguments (1 for 0)'} } self.$$none = (defaults === undefined ? nil : defaults); self.$$proc = block; return self; } end def ==(other) %x{ if (self === other) { return true; } if (!other.$$is_hash) { return false; } if (self.size !== other.size) { return false; } var entry, other_value; for (entry of self) { other_value = $hash_get(other, entry[0]); if (other_value === undefined || !entry[1]['$eql?'](other_value)) { return false; } } return true; } end def >=(other) other = ::Opal.coerce_to!(other, ::Hash, :to_hash) %x{ if (self.size < other.size) { return false; } } result = true other.each do |other_key, other_val| # rubocop:disable Style/HashEachMethods val = fetch(other_key, `null`) %x{ if (val == null || val !== other_val) { result = false; return; } } end result end def >(other) other = ::Opal.coerce_to!(other, ::Hash, :to_hash) %x{ if (self.size <= other.size) { return false; } } self >= other end def <(other) other = ::Opal.coerce_to!(other, ::Hash, :to_hash) other > self end def <=(other) other = ::Opal.coerce_to!(other, ::Hash, :to_hash) other >= self end def [](key) %x{ var value = $hash_get(self, key); if (value !== undefined) { return value; } return self.$default(key); } end def []=(key, value) %x{ $deny_frozen_access(self); $hash_put(self, key, value); return value; } end def assoc(object) %x{ var entry; for (entry of self) { if (#{`entry[0]` == object}) { return [entry[0], entry[1]]; } } return nil; } end def clear %x{ $deny_frozen_access(self); self.clear(); if (self.$$keys) self.$$keys.clear(); return self; } end def clone %x{ var hash = self.$class().$new(); $hash_clone(self, hash); return self["$frozen?"]() ? hash.$freeze() : hash; } end def compact %x{ var hash = new Map(); self.forEach((value, key, s) => { if (value !== nil && value != null) $hash_put(hash, key, value); }); return hash; } end def compact! %x{ $deny_frozen_access(self); var result = nil; return $hash_each(self, result, function(key, value) { if (value === nil || value == null) { $hash_delete(self, key); result = self; } return [false, result]; }); } end def compare_by_identity %x{ $deny_frozen_access(self); if (!self.$$by_identity) { self.$$by_identity = true; if (self.size !== 0) Opal.hash_rehash(self); } return self; } end def compare_by_identity? `self.$$by_identity === true` end def default(key = undefined) %x{ if (key !== undefined && self.$$proc !== nil && self.$$proc !== undefined) { return self.$$proc.$call(self, key); } if (self.$$none === undefined) { return nil; } return self.$$none; } end def default=(object) %x{ $deny_frozen_access(self); self.$$proc = nil; self.$$none = object; return object; } end def default_proc %x{ if (self.$$proc !== undefined) { return self.$$proc; } return nil; } end def default_proc=(default_proc) %x{ $deny_frozen_access(self); var proc = default_proc; if (proc !== nil) { proc = #{::Opal.coerce_to!(`proc`, ::Proc, :to_proc)}; if (#{`proc`.lambda?} && Math.abs(#{`proc`.arity}) !== 2) { #{::Kernel.raise ::TypeError, 'default_proc takes two arguments'}; } } self.$$none = nil; self.$$proc = proc; return default_proc; } end def delete(key, &block) %x{ $deny_frozen_access(self); var value = $hash_delete(self, key); if (value !== undefined) { return value; } if (block !== nil) { return #{yield key}; } return nil; } end def delete_if(&block) return enum_for(:delete_if) { size } unless block %x{ $deny_frozen_access(self); return $hash_each(self, self, function(key, value) { var obj = block(key, value); if (obj !== false && obj !== nil) { $hash_delete(self, key); } return [false, self]; }); } end def dig(key, *keys) item = self[key] %x{ if (item === nil || keys.length === 0) { return item; } } unless item.respond_to?(:dig) ::Kernel.raise ::TypeError, "#{item.class} does not have #dig method" end item.dig(*keys) end def dup `$hash_clone(self, self.$class().$new())` end def each(&block) return enum_for(:each) { size } unless block %x{ return $hash_each(self, self, function(key, value) { $yield1(block, [key, value]); return [false, self]; }); } end def each_key(&block) return enum_for(:each_key) { size } unless block %x{ return $hash_each(self, self, function(key, value) { block(key); return [false, self]; }); } end def each_value(&block) return enum_for(:each_value) { size } unless block %x{ return $hash_each(self, self, function(key, value) { block(value); return [false, self]; }); } end def empty? `self.size === 0` end def except(*keys) dup.except!(*keys) end def except!(*keys) keys.each { |key| delete(key) } self end def fetch(key, defaults = undefined, &block) %x{ var value = $hash_get(self, key); if (value !== undefined) { return value; } if (block !== nil) { return block(key); } if (defaults !== undefined) { return defaults; } } ::Kernel.raise ::KeyError.new("key not found: #{key.inspect}", key: key, receiver: self) end def fetch_values(*keys, &block) keys.map { |key| fetch(key, &block) } end def flatten(level = 1) level = ::Opal.coerce_to!(level, ::Integer, :to_int) %x{ var result = []; return $hash_each(self, result, function(key, value) { result.push(key); if (value.$$is_array) { if (level === 1) { result.push(value); return [false, result]; } result = result.concat(#{`value`.flatten(`level - 2`)}); return [false, result]; } result.push(value); return [false, result]; }); } end def freeze return self if frozen? `$freeze(self)` end def has_key?(key) `$hash_get(self, key) !== undefined` end def has_value?(value) %x{ var val, values = self.values(); for (val of values) { if (#{`val` == value}) { return true; } } return false; } end `var $hash_ids` def hash %x{ var top = ($hash_ids === undefined), hash_id = self.$object_id(), result = $opal32_init(), key, item, i, values, entry, size = self.size, ary = new Int32Array(size); result = $opal32_add(result, 0x4); result = $opal32_add(result, size); if (top) { $hash_ids = new Map(); } else if ($hash_ids.has(hash_id)) { return $opal32_add(result, 0x01010101); } try { if (!top) { values = $hash_ids.values(); for (item of values) { if (#{eql?(`item`)}) { return $opal32_add(result, 0x01010101); } } } $hash_ids.set(hash_id, self); i = 0; for (entry of self) { ary[i] = [0x70414952, entry[0], entry[1]].$hash(); i++; } ary = ary.sort(); for (i = 0; i < ary.length; i++) { result = $opal32_add(result, ary[i]); } return result; } finally { if (top) { $hash_ids = undefined; } } } end def index(object) %x{ var entry; for (entry of self) { if (#{`entry[1]` == object}) { return entry[0]; } } return nil; } end def indexes(*args) %x{ var result = []; for (var i = 0, length = args.length, key, value; i < length; i++) { key = args[i]; value = $hash_get(self, key); if (value === undefined) { result.push(#{default}); continue; } result.push(value); } return result; } end `var inspect_ids` def inspect %x{ var top = (inspect_ids === undefined), hash_id = self.$object_id(), result = []; } begin %x{ if (top) { inspect_ids = {}; } if (inspect_ids.hasOwnProperty(hash_id)) { return '{...}'; } inspect_ids[hash_id] = true; $hash_each(self, false, function(key, value) { value = #{Opal.inspect(`value`)} key = #{Opal.inspect(`key`)} result.push(key + '=>' + value); return [false, false]; }) return '{' + result.join(', ') + '}'; } nil ensure `if (top) inspect_ids = undefined` end end def invert %x{ var hash = new Map(); return $hash_each(self, hash, function(key, value) { $hash_put(hash, value, key); return [false, hash]; }); } end def keep_if(&block) return enum_for(:keep_if) { size } unless block %x{ $deny_frozen_access(self); return $hash_each(self, self, function(key, value) { var obj = block(key, value); if (obj === false || obj === nil) { $hash_delete(self, key); } return [false, self]; }); } end def keys `Array.from(self.keys())` end def length `self.size` end def merge(*others, &block) dup.merge!(*others, &block) end def merge!(*others, &block) %x{ $deny_frozen_access(self); var i, j, other; for (i = 0; i < others.length; ++i) { other = #{::Opal.coerce_to!(`others[i]`, ::Hash, :to_hash)}; if (block === nil) { $hash_each(other, false, function(key, value) { $hash_put(self, key, value); return [false, false]; }); } else { $hash_each(other, false, function(key, value) { var val = $hash_get(self, key); if (val === undefined) { $hash_put(self, key, value); return [false, false]; } $hash_put(self, key, block(key, val, value)); return [false, false]; }); } } return self; } end def rassoc(object) %x{ var entry; for (entry of self) { if (#{`entry[1]` == object}) { return [entry[0], entry[1]]; } } return nil; } end def rehash %x{ $deny_frozen_access(self); return Opal.hash_rehash(self); } end def reject(&block) return enum_for(:reject) { size } unless block %x{ var hash = new Map(); self.forEach((value, key, s) => { var obj = block(key, value); if (obj === false || obj === nil) { $hash_put(hash, key, value); } }); return hash; } end def reject!(&block) return enum_for(:reject!) { size } unless block %x{ $deny_frozen_access(self); var result = nil; return $hash_each(self, result, function(key, value) { var obj = block(key, value); if (obj !== false && obj !== nil) { $hash_delete(self, key); result = self; } return [false, result]; }); } end def replace(other) `$deny_frozen_access(self);` other = ::Opal.coerce_to!(other, ::Hash, :to_hash) %x{ self.$clear(); $hash_each(other, false, function(key, value) { $hash_put(self, key, value); return [false, false]; }); } if other.default_proc self.default_proc = other.default_proc else self.default = other.default end self end def select(&block) return enum_for(:select) { size } unless block %x{ var hash = new Map(); self.forEach((value, key, s) => { var obj = block(key, value); if (obj !== false && obj !== nil) { $hash_put(hash, key, value); } }); return hash; } end def select!(&block) return enum_for(:select!) { size } unless block %x{ $deny_frozen_access(self); var result = nil; return $hash_each(self, result, function(key, value) { var obj = block(key, value); if (obj === false || obj === nil) { $hash_delete(self, key); result = self; } return [false, result]; }); } end def shift %x{ $deny_frozen_access(self); return $hash_each(self, nil, function(key, value) { return [true, [key, $hash_delete(self, key)]]; }); } end def slice(*keys) %x{ var result = new Map(); for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i], value = $hash_get(self, key); if (value !== undefined) { $hash_put(result, key, value); } } return result; } end def to_a `Array.from(self)` end def to_h(&block) return map(&block).to_h if block_given? %x{ if (self.$$class === Opal.Hash) { return self; } var hash = new Map(); $hash_clone(self, hash); return hash; } end def to_hash self end def to_proc proc do |key = undefined| %x{ if (key == null) { #{::Kernel.raise ::ArgumentError, 'no key given'} } } self[key] end end def transform_keys(keys_hash = nil, &block) return enum_for(:transform_keys) { size } if !block && !keys_hash %x{ var result = new Map(); self.forEach((value, key, s) => { var new_key; if (keys_hash !== nil) new_key = $hash_get(keys_hash, key); if (new_key === undefined && block && block !== nil) new_key = block(key); if (new_key === undefined) new_key = key // key not modified $hash_put(result, new_key, value); }); return result; } end def transform_keys!(keys_hash = nil, &block) return enum_for(:transform_keys!) { size } if !block && !keys_hash %x{ $deny_frozen_access(self); var modified_keys = new Map(); return $hash_each(self, self, function(key, value) { var new_key; if (keys_hash !== nil) new_key = $hash_get(keys_hash, key); if (new_key === undefined && block && block !== nil) new_key = block(key); if (new_key === undefined) return [false, self]; // key not modified if (!$hash_get(modified_keys, key)) $hash_delete(self, key); $hash_put(self, new_key, value); $hash_put(modified_keys, new_key, true) return [false, self]; }); } end def transform_values(&block) return enum_for(:transform_values) { size } unless block %x{ var result = new Map(); self.forEach((value, key, s) => $hash_put(result, key, block(value))); return result; } end def transform_values!(&block) return enum_for(:transform_values!) { size } unless block %x{ $deny_frozen_access(self); return $hash_each(self, self, function(key, value) { $hash_put(self, key, block(value)); return [false, self]; }); } end def values `Array.from(self.values())` end alias each_pair each alias eql? == alias filter select alias filter! select! alias include? has_key? alias indices indexes alias key index alias key? has_key? alias member? has_key? alias size length alias store []= alias to_s inspect alias update merge! alias value? has_value? alias values_at indexes end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/error.rb
opal/corelib/error.rb
# backtick_javascript: true # use_strict: true class ::Exception < `Error` `Opal.prop(self.$$prototype, '$$is_exception', true)` `var stack_trace_limit` `Error.stackTraceLimit = 100` def self.new(*args) %x{ var message = (args.length > 0) ? args[0] : nil; var error = new self.$$constructor(message); error.name = self.$$name; error.message = message; error.cause = #{$!}; Opal.send(error, error.$initialize, args); // Error.captureStackTrace() will use .name and .toString to build the // first line of the stack trace so it must be called after the error // has been initialized. // https://nodejs.org/dist/latest-v6.x/docs/api/errors.html if (Opal.config.enable_stack_trace && Error.captureStackTrace) { // Passing Kernel.raise will cut the stack trace from that point above Error.captureStackTrace(error, stack_trace_limit); } return error; } end `stack_trace_limit = self.$new` def self.exception(*args) new(*args) end def initialize(*args) # using self.message aka @message to retain compatibility with native exception's message property `self.message = (args.length > 0) ? args[0] : nil` end # Those instance variables are not enumerable. def copy_instance_variables(other) super %x{ self.message = other.message; self.cause = other.cause; self.stack = other.stack; } end %x{ // Convert backtrace from any format to Ruby format function correct_backtrace(backtrace) { var new_bt = [], m; for (var i = 0; i < backtrace.length; i++) { var loc = backtrace[i]; if (!loc || !loc.$$is_string) { /* Do nothing */ } /* Chromium format */ else if ((m = loc.match(/^ at (.*?) \((.*?)\)$/))) { new_bt.push(m[2] + ":in `" + m[1] + "'"); } else if ((m = loc.match(/^ at (.*?)$/))) { new_bt.push(m[1] + ":in `undefined'"); } /* Node format */ else if ((m = loc.match(/^ from (.*?)$/))) { new_bt.push(m[1]); } /* Mozilla/Apple format */ else if ((m = loc.match(/^(.*?)@(.*?)$/))) { new_bt.push(m[2] + ':in `' + m[1] + "'"); } } return new_bt; } } def backtrace %x{ if (self.backtrace) { // nil is a valid backtrace return self.backtrace; } var backtrace = self.stack; if (typeof(backtrace) !== 'undefined' && backtrace.$$is_string) { return self.backtrace = correct_backtrace(backtrace.split("\n")); } else if (backtrace) { return self.backtrace = correct_backtrace(backtrace); } return []; } end def backtrace_locations %x{ if (self.backtrace_locations) return self.backtrace_locations; self.backtrace_locations = #{backtrace&.map do |loc| ::Thread::Backtrace::Location.new(loc) end} return self.backtrace_locations; } end def cause `self.cause || nil` end def exception(str = nil) %x{ if (str === nil || self === str) { return self; } var cloned = #{clone}; cloned.message = str; if (self.backtrace) cloned.backtrace = Array.from(self.backtrace); cloned.stack = self.stack; cloned.cause = self.cause; return cloned; } end # not using alias message to_s because you need to be able to override to_s and have message use overridden method, won't work with alias def message to_s end def full_message(kwargs = nil) unless defined? Hash # We are dealing with an unfully loaded Opal library, so we should # do with as little as we can. return "#{@message}\n#{`self.stack`}" end kwargs ||= {} kwargs[:highlight] = $stderr&.tty? unless kwargs.include?(:highlight) kwargs[:order] = :top unless kwargs.include?(:order) highlight, order = kwargs[:highlight], kwargs[:order] highlight = false if highlight.nil? unless `highlight === true || highlight === false` ::Kernel.raise ::ArgumentError, "expected true or false as highlight: #{highlight}" end unless `order == "top" || order == "bottom"` ::Kernel.raise ::ArgumentError, "expected :top or :bottom as order: #{order}" end if highlight bold_underline = "\e[1;4m" bold = "\e[1m" reset = "\e[m" else bold_underline = bold = reset = '' end bt = `Array.from(#{backtrace})` bt = caller if `bt == null || bt == nil || bt == ''` first = bt.shift msg = "#{first}: " msg += "#{bold}#{to_s} (#{bold_underline}#{self.class.name}#{reset}#{bold})#{reset}\n" msg += `bt.map((loc) => "\tfrom "+loc+"\n").join("")` msg += cause.full_message(highlight: highlight) if cause if order == :bottom msg = msg.split("\n").reverse.join("\n") msg = "#{bold}Traceback#{reset} (most recent call last):\n" + msg end msg end def inspect as_str = to_s as_str.empty? ? self.class.to_s : "#<#{self.class.to_s}: #{to_s}>" end def set_backtrace(backtrace) %x{ var valid = true, i, ii; if (backtrace === nil) { self.backtrace = nil; self.stack = ''; } else if (backtrace.$$is_string) { self.backtrace = [backtrace]; self.stack = ' from ' + backtrace; } else { if (backtrace.$$is_array) { for (i = 0, ii = backtrace.length; i < ii; i++) { if (!backtrace[i].$$is_string) { valid = false; break; } } } else { valid = false; } if (valid === false) { #{::Kernel.raise ::TypeError, 'backtrace must be Array of String'} } self.backtrace = backtrace; self.stack = backtrace.map(i => ' from ' + i).join("\n"); } return backtrace; } end def to_s # using self.message aka @message to retain compatibility with native exception's message property (@message && @message.to_s) || self.class.to_s end end # keep the indentation, it makes the exception hierarchy clear class ::ScriptError < ::Exception; end class ::SyntaxError < ::ScriptError; end class ::LoadError < ::ScriptError; end class ::NotImplementedError < ::ScriptError; end class ::SystemExit < ::Exception; end class ::NoMemoryError < ::Exception; end class ::SignalException < ::Exception; end class ::Interrupt < ::SignalException; end class ::SecurityError < ::Exception; end class ::SystemStackError < ::Exception; end class ::StandardError < ::Exception; end class ::EncodingError < ::StandardError; end class ::ZeroDivisionError < ::StandardError; end class ::NameError < ::StandardError; end class ::NoMethodError < ::NameError; end class ::RuntimeError < ::StandardError; end class ::FrozenError < ::RuntimeError; end class ::LocalJumpError < ::StandardError; end class ::TypeError < ::StandardError; end class ::ArgumentError < ::StandardError; end class ::UncaughtThrowError < ::ArgumentError; end class ::IndexError < ::StandardError; end class ::StopIteration < ::IndexError; end class ::ClosedQueueError < ::StopIteration; end class ::KeyError < ::IndexError; end class ::RangeError < ::StandardError; end class ::FloatDomainError < ::RangeError; end class ::IOError < ::StandardError; end class ::EOFError < ::IOError; end class ::SystemCallError < ::StandardError; end class ::RegexpError < ::StandardError; end class ::ThreadError < ::StandardError; end class ::FiberError < ::StandardError; end ::Object.autoload :Errno, 'corelib/error/errno' class ::FrozenError < ::RuntimeError attr_reader :receiver def initialize(message, receiver: nil) super message @receiver = receiver end end class ::UncaughtThrowError < ::ArgumentError attr_reader :tag, :value def initialize(tag, value = nil) @tag = tag @value = value super("uncaught throw #{@tag.inspect}") end end class ::NameError attr_reader :name def initialize(message, name = nil) super message @name = name end end class ::NoMethodError attr_reader :args def initialize(message, name = nil, args = []) super message, name @args = args end end class ::StopIteration attr_reader :result end class ::KeyError def initialize(message, receiver: nil, key: nil) super(message) @receiver = receiver @key = key end def receiver @receiver || ::Kernel.raise(::ArgumentError, 'no receiver is available') end def key @key || ::Kernel.raise(::ArgumentError, 'no key is available') end end class ::LocalJumpError attr_reader :exit_value, :reason def initialize(message, exit_value = nil, reason = :noreason) super message @exit_value = exit_value @reason = reason end end module ::Opal module Raw class Error end end end module ::JS def self.const_missing(const) if const == :Error warn '[Opal] JS::Error class has been renamed to Opal::Raw::Error and will change semantics in Opal 2.1. ' \ 'To ensure forward compatibility, please update your rescue clauses.' ::JS::Raw::Error else super end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/pattern_matching.rb
opal/corelib/pattern_matching.rb
require 'corelib/pattern_matching/base' # A "userland" implementation of pattern matching for Opal class ::PatternMatching def self.call(from, pattern) pm = new(from, pattern) pm.match || (return nil) pm.returns end def initialize(from, pattern) @from, @pattern = from, pattern @returns = [] end attr_reader :returns def match(from = @from, pattern = @pattern) if pattern == :var @returns << from true else # Pattern is otherwise an Array type, *args = *pattern case type when :save # from => @returns << from match(from, args[0]) when :lit # 3, 4, :a, (1..), ... (but also ^a) args[0] === from when :any # a | b args.any? { |arg| match(from, arg) } when :all # Array(1) which works as Array & [1] (& doesn't exist though...) args.all? { |arg| match(from, arg) } when :array # [...] fixed_size, array_size, array_match = *args return false unless from.respond_to? :deconstruct a = from.deconstruct return false if fixed_size && a.length != array_size return false if a.length < array_size skip_elems = 0 skip_rests = 0 array_match.each_with_index.all? do |elem, i| type, *args = elem case type when :rest skip_elems = a.size - array_size skip_rests = 1 match(a[i...i + skip_elems], args[0]) if args[0] # :save? true else match(a[i + skip_elems - skip_rests], elem) end end when :find # [*, a, b, *] find_match, = *args first, *find_match, last = *find_match pattern_length = find_match.length return false unless from.respond_to? :deconstruct a = from.deconstruct a_length = a.length return false if a_length < pattern_length # We will save the backup of returns, to be restored # on each iteration to try again. returns_backup = @returns.dup # Extract the capture info from first and last. # Both are of a form [:rest], or [:rest, :var]. # So our new variables will be either :var, or nil. first, last = first[1], last[1] # Let's try to match each possibility... # [A, B, c, d], [a, B, C, d], [a, b, C, D] iterations = a_length - pattern_length + 1 iterations.times.any? do |skip| first_part = a[0, skip] content = a[skip, pattern_length] last_part = a[skip + pattern_length..-1] match(first_part, first) if first success = content.each_with_index.all? do |e, i| match(e, find_match[i]) end match(last_part, last) if last # Match failed. Let's not return anything. @returns = returns_backup.dup unless success success end when :hash # {...} any_size, hash_match = *args hash_match = hash_match.to_h return false unless from.respond_to? :deconstruct_keys if any_size && any_size != true # a => {a:, **other} a = from.deconstruct_keys(nil) # ^^^^^^^ else a = from.deconstruct_keys(hash_match.keys) end hash_match.all? do |k, v| return false unless a.key? k match(a[k], v) end || (return false) if any_size && any_size != true match(a.except(*hash_match.keys), args[0]) elsif !any_size return false unless a.except(*hash_match.keys).empty? end true end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/numeric.rb
opal/corelib/numeric.rb
# backtick_javascript: true # use_strict: true require 'corelib/comparable' class ::Numeric include ::Comparable def coerce(other) if other.instance_of? self.class return [other, self] end [::Kernel.Float(other), ::Kernel.Float(self)] end def __coerced__(method, other) if other.respond_to?(:coerce) a, b = other.coerce(self) a.__send__ method, b else case method when :+, :-, :*, :/, :%, :&, :|, :^, :** ::Kernel.raise ::TypeError, "#{other.class} can't be coerced into Numeric" when :>, :>=, :<, :<=, :<=> ::Kernel.raise ::ArgumentError, "comparison of #{self.class} with #{other.class} failed" end end end def <=>(other) if equal? other return 0 end nil end def +@ self end def -@ 0 - self end def %(other) self - other * div(other) end def abs self < 0 ? -self : self end def abs2 self * self end def angle self < 0 ? ::Math::PI : 0 end def ceil(ndigits = 0) to_f.ceil(ndigits) end def conj self end def denominator to_r.denominator end def div(other) ::Kernel.raise ::ZeroDivisionError, 'divided by o' if other == 0 (self / other).floor end def divmod(other) [div(other), self % other] end def fdiv(other) to_f / other end def floor(ndigits = 0) to_f.floor(ndigits) end def i ::Kernel.Complex(0, self) end def imag 0 end def integer? false end def nonzero? zero? ? nil : self end def numerator to_r.numerator end def polar [abs, arg] end def quo(other) ::Opal.coerce_to!(self, ::Rational, :to_r) / other end def real self end def real? true end def rect [self, 0] end def round(digits = undefined) to_f.round(digits) end def step(limit = undefined, step = undefined, to: undefined, by: undefined, &block) %x{ if (limit !== undefined && to !== undefined) { #{::Kernel.raise ::ArgumentError, 'to is given twice'} } if (step !== undefined && by !== undefined) { #{::Kernel.raise ::ArgumentError, 'step is given twice'} } if (to !== undefined) { limit = to; } if (by !== undefined) { step = by; } if (limit === undefined) { limit = nil; } function validateParameters() { if (step === nil) { #{::Kernel.raise ::TypeError, 'step must be numeric'} } if (step != null && #{step == 0}) { #{::Kernel.raise ::ArgumentError, "step can't be 0"} } if (step === nil || step == null) { step = 1; } var sign = #{step <=> 0}; if (sign === nil) { #{::Kernel.raise ::ArgumentError, "0 can't be coerced into #{step.class}"} } if (limit === nil || limit == null) { limit = sign > 0 ? #{::Float::INFINITY} : #{-::Float::INFINITY}; } #{::Opal.compare(self, limit)} } function stepFloatSize() { if ((step > 0 && self > limit) || (step < 0 && self < limit)) { return 0; } else if (step === Infinity || step === -Infinity) { return 1; } else { var abs = Math.abs, floor = Math.floor, err = (abs(self) + abs(limit) + abs(limit - self)) / abs(step) * #{::Float::EPSILON}; if (err === Infinity || err === -Infinity) { return 0; } else { if (err > 0.5) { err = 0.5; } return floor((limit - self) / step + err) + 1 } } } function stepSize() { validateParameters(); if (step === 0) { return Infinity; } if (step % 1 !== 0) { return stepFloatSize(); } else if ((step > 0 && self > limit) || (step < 0 && self < limit)) { return 0; } else { var ceil = Math.ceil, abs = Math.abs, lhs = abs(self - limit) + 1, rhs = abs(step); return ceil(lhs / rhs); } } } unless block_given? if (!limit || limit.is_a?(::Numeric)) && (!step || step.is_a?(::Numeric)) return ::Enumerator::ArithmeticSequence.new( [limit, step, ('to: ' if to), ('by: ' if by)], self ) else return enum_for(:step, limit, step, &`stepSize`) end end %x{ validateParameters(); var isDesc = #{step.negative?}, isInf = #{step == 0} || (limit === Infinity && !isDesc) || (limit === -Infinity && isDesc); if (self.$$is_number && step.$$is_number && limit.$$is_number) { if (self % 1 === 0 && (isInf || limit % 1 === 0) && step % 1 === 0) { var value = self; if (isInf) { for (;; value += step) { block(value); } } else if (isDesc) { for (; value >= limit; value += step) { block(value); } } else { for (; value <= limit; value += step) { block(value); } } return self; } else { var begin = #{to_f}.valueOf(); step = #{step.to_f}.valueOf(); limit = #{limit.to_f}.valueOf(); var n = stepFloatSize(); if (!isFinite(step)) { if (n !== 0) block(begin); } else if (step === 0) { while (true) { block(begin); } } else { for (var i = 0; i < n; i++) { var d = i * step + self; if (step >= 0 ? limit < d : limit > d) { d = limit; } block(d); } } return self; } } } counter = self while `isDesc ? #{counter >= limit} : #{counter <= limit}` yield counter counter += step end end def to_c ::Kernel.Complex(self, 0) end def to_int to_i end def truncate(ndigits = 0) to_f.truncate(ndigits) end def zero? self == 0 end def positive? self > 0 end def negative? self < 0 end def dup self end def clone(freeze: true) self end def finite? true end def infinite? nil end alias arg angle alias conjugate conj alias imaginary imag alias magnitude abs alias modulo % alias phase arg alias rectangular rect end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding.rb
opal/corelib/string/encoding.rb
# backtick_javascript: true # helpers: str class ::Encoding class << self def register(name, options = {}, &block) names = [name] + (options[:aliases] || []) ascii = options[:ascii] || false dummy = options[:dummy] || false if options[:inherits] encoding = options[:inherits].clone encoding.initialize(name, names, ascii, dummy) else encoding = new(name, names, ascii, dummy) end encoding.instance_exec(&block) if block_given? register = `Opal.encodings` names.each do |encoding_name| const_set encoding_name.tr('-', '_'), encoding register.JS[encoding_name] = encoding end end def find(name) return default_external if name == :default_external `return Opal.find_encoding(name)` end attr_accessor :default_external, :default_internal end attr_reader :name, :names def initialize(name, names, ascii, dummy) @name = name @names = names @ascii = ascii @dummy = dummy end def ascii_compatible? @ascii end def dummy? @dummy end def binary? false end def to_s @name end def inspect "#<Encoding:#{@name}#{' (dummy)' if @dummy}>" end # methods to implement per encoding def bytesize(str, index) ::Kernel.raise ::NotImplementedError end def byteslice(str, index, length) ::Kernel.raise ::NotImplementedError end def decode(io_buffer) ::Kernel.raise ::NotImplementedError end def decode!(io_buffer) ::Kernel.raise ::NotImplementedError end def each_byte(str, &block) ::Kernel.raise ::NotImplementedError end # Fills io_buffer with bytes of str and yields the number # of valid bytes in io_buffer to the block. # Repeats until end of str while reusing io_buffer. # In other words: io_buffer is used as a sliding window over str. def each_byte_buffer(str, io_buffer, &block) ::Kernel.raise ::NotImplementedError end def scrub(str, replacement, &block) ::Kernel.raise ::NotImplementedError end def valid_encoding?(str) ::Kernel.raise ::NotImplementedError end class ::EncodingError < ::StandardError; end class ::CompatibilityError < ::EncodingError; end class UndefinedConversionError < ::EncodingError; end end %x{ const SFCP = String.fromCodePoint; const SFCC = String.fromCharCode; function scrubbing_decoder(enc, label) { if (!enc.scrubbing_decoder) enc.scrubbing_decoder = new TextDecoder(label, { fatal: false }); return enc.scrubbing_decoder; } function validating_decoder(enc, label) { if (!enc.validating_decoder) enc.validating_decoder = new TextDecoder(label, { fatal: true }); return enc.validating_decoder; } } ::Encoding.register 'UTF-8', aliases: ['CP65001'], ascii: true do def bytesize(str, index) %x{ let code_point, size = 0; for (const c of str) { code_point = c.codePointAt(0); if (code_point < 0x80) size++; // char is one byte long in UTF-8 else if (code_point < 0x800) size += 2; // char is two bytes long // else if (code_point < 0xD800) size += 3; // char is three bytes long // else if (code_point < 0xE000) size += 3; // for lone surrogates the 0xBD 0xBF 0xEF, 3 bytes, get inserted else if (code_point < 0x10000) size += 3; // char is three bytes long else if (code_point <= 0x110000) size += 4; // char is four bytes long if (index-- <= 0) break; } return size; } end def byteslice(str, index, length) # Must handle negative index and length, with length being negative indicating a negative range end. # This slices at UTF-16 character boundaries, as required by specs. # However, some specs require slicing UTF-16 characters into its bytes, which won't work. %x{ let result = "", code_point, idx, max; if (index < 0) { // negative index, walk from the end of the string, let i = str.length - 1, bad_cp = -1; // -1 = no, string ok, 0 or larger = the code point idx = -1; if (length < 0) max = length; // a negative index else if (length === 0) max = index; else if ((index + length) >= 0) max = -1; // from end of string else max = index + length - 1; for (; i >= 0; i--) { code_point = str.codePointAt(i); if (code_point >= 0xD800 && code_point <= 0xDFFF) { // low surrogate, get the full code_point next continue; } if (length >= 0 || length === -1 || (length < 0 && idx <= length)) { if (code_point < 0x80) { if (idx >= index && idx <= max) result = SFCP(code_point) + result; idx--; // always landing on character boundary, no need to check } else if (code_point < 0x800) { // 2 byte surrogates if (idx >= index && idx <= max) result = SFCP(code_point) + result; idx -= 2; // check for broken character boundary, raise if so // } else if (code_point < 0xD800) { // // 3 byte surrogates // if (idx >= index && idx <= max) result = SFCP(code_point) + result; // idx -= 3; } else if (code_point < 0x10000) { // 3 byte surrogates if (idx >= index && idx <= max) result = SFCP(code_point) + result; idx -= 3; } else if (code_point < 0x110000) { // 4 byte surrogates if (idx >= index && idx <= max) result = SFCP(code_point) + result; idx -= 3; } } if (idx < index) break; } if (idx > index || result.length === 0) return nil; } else { // 0 or positive index, walk from beginning idx = 0; if (length < 0) max = Infinity; // to end of string else if (length === 0) max = index + 1; else max = index + length; for (const c of str) { code_point = c.codePointAt(0); if (code_point < 0x80) { if (idx >= index && idx <= max) result += SFCP(code_point); idx++; } else if (code_point < 0x800) { // 2 byte surrogates if (idx >= index && idx <= max) result += SFCP(code_point); idx += 2; } else if (code_point < 0xD800) { // 3 byte surrogates if (idx >= index && idx <= max) result += SFCP(code_point); idx += 3; } else if (code_point < 0xE000) { if (idx >= index && idx <= max) result += SFCP(0xEF); idx++; if (idx >= index && idx <= max) result += SFCP(0xBF); idx++; if (idx >= index && idx <= max) result += SFCP(0xBD); idx++; } else if (code_point < 0x10000) { // 3 byte surrogates if (idx >= index && idx <= max) result += SFCP(code_point); idx += 3; } else if (code_point < 0x110000) { // 4 byte surrogates if (idx >= index && idx <= max) result += SFCP(code_point); idx += 4; } if (idx >= max) break; } if (result.length === 0) { if (idx === index) result = ""; else return nil; } if (length < 0) { // if length is a negative index from a range, we walked to the end, // so shorten the result accordingly // result has the bytes already spread out as chars so we can simply slice if ((idx + length) > 0) result = result.slice(0, result.length + length); else result = ""; } } if (length === 0) result = ""; return result; } end def decode(io_buffer) %x{ let result = scrubbing_decoder(self, 'utf-8').decode(io_buffer.data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let result = validating_decoder(self, 'utf-8').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ let code_point; for (const c of str) { code_point = c.codePointAt(0); if (code_point < 0x80) { #{yield `code_point`}; } else if (code_point < 0x800) { #{yield `code_point >> 0x6 | 0xC0`}; #{yield `code_point & 0x3F | 0x80`}; } else if (code_point < 0xD800) { #{yield `code_point >> 0xC | 0xE0`}; #{yield `code_point >> 0x6 & 0x3F | 0x80`}; #{yield `code_point & 0x3F | 0x80`}; } else if (code_point < 0xE000) { #{yield `0xEF`}; #{yield `0xBF`}; #{yield `0xBD`}; } else if (code_point < 0x10000) { #{yield `code_point >> 0xC | 0xE0`}; #{yield `code_point >> 0x6 & 0x3F | 0x80`}; #{yield `code_point & 0x3F | 0x80`}; } else if (code_point < 0x110000) { #{yield `code_point >> 0x12 | 0xF0`}; #{yield `code_point >> 0xC & 0x3F | 0x80`}; #{yield `code_point >> 0x6 & 0x3F | 0x80`}; #{yield `code_point & 0x3F | 0x80`}; } } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let code_point, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for (const c of str) { code_point = c.codePointAt(0); if (code_point < 0x80) { set_byte(code_point); } else if (code_point < 0x800) { set_byte(code_point >> 0x6 | 0xC0); set_byte(code_point & 0x3F | 0x80); } else if (code_point < 0xD800) { set_byte(code_point >> 0xC | 0xE0); set_byte(code_point >> 0x6 & 0x3F | 0x80); set_byte(code_point & 0x3F | 0x80); } else if (code_point < 0xE000) { set_byte(0xEF); set_byte(0xBF); set_byte(0xBD); } else if (code_point < 0x10000) { set_byte(code_point >> 0xC | 0xE0); set_byte(code_point >> 0x6 & 0x3F | 0x80); set_byte(code_point & 0x3F | 0x80); } else if (code_point < 0x110000) { set_byte(code_point >> 0x12 | 0xF0); set_byte(code_point >> 0xC & 0x3F | 0x80); set_byte(code_point >> 0x6 & 0x3F | 0x80); set_byte(code_point & 0x3F | 0x80); } } if (pos > 0) { #{yield pos} } } str end def scrub(str, replacement, &block) %x{ let result = scrubbing_decoder(self, 'utf-8').decode(new Uint8Array(str.$bytes())); if (block !== nil) { // dont know the bytes anymore ... ¯\_(ツ)_/¯ result = result.replace(/�/g, (byte)=>{ return #{yield `byte`}; }); } else if (replacement && replacement !== nil) { // this may replace valid � that have existed in the string before, // but there currently is no way to specify a other replacement character for TextDecoder result = result.replace(/�/g, replacement); } return $str(result, self); } end def valid_encoding?(str) %x{ try { validating_decoder(self, 'utf-8').decode(new Uint8Array(str.$bytes())); } catch { return false; } return true; } end end ::Encoding.register 'UTF-16LE', aliases: ['UTF-16'] do def bytesize(str, index) %x{ if (index < str.length) return (index + 1) * 2; return str.length * 2; } end def byteslice(str, index, length) # Must handle negative index and length, with length being negative indicating a negative range end. %x{ let result = "", char_code, idx, max, i; if (index < 0) { // negative index, walk from the end of the string, idx = -1; if (length < 0) max = length; // a negative index else if (length === 0) max = index; else if ((index + length) >= 0) max = -1; // from end of string else max = index + length - 1; for (i = str.length; i > 0; i--) { char_code = str.charCodeAt(i); if (length >= 0 || length === -1 || (length < 0 && idx <= length)) { if (idx >= index && idx <= max) result = SFCC(char_code) + result; } idx -= 2; if (idx < index) break; } if (idx > index || result.length === 0) return nil; } else { // 0 or positive index, walk from beginning idx = 0; if (length < 0) max = Infinity; else if (length === 0) max = index + 1; else max = index + length; for (i = 0, length = str.length; i < length; i++) { char_code = str.charCodeAt(i); if (idx >= index && idx <= max) result += SFCC(char_code); idx += 2; if (idx >= max) break; } if (result.length === 0) { if (idx === index) result = ""; else return nil; } if (length < 0) { // if length is a negative index from a range, we walked to the end, so shorten the result if ((idx + length) > 0) result = result.slice(0, result.length + length); else result = ""; } } if (length === 0) result = ""; return result; } end def decode(io_buffer) %x{ let result = scrubbing_decoder(self, 'utf-16le').decode(io_buffer.data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let result = validating_decoder(self, 'utf-16le').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ for (let i = 0, length = str.length; i < length; i++) { let char_code = str.charCodeAt(i); #{yield `char_code & 0xff`}; #{yield `char_code >> 8`}; } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let char_code, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for (let i = 0, length = str.length; i < length; i++) { char_code = str.charCodeAt(i); set_byte(char_code & 0xff); set_byte(char_code >> 8); } if (pos > 0) { #{yield pos} } } str end def scrub(str, replacement, &block) %x{ let result = scrubbing_decoder(self, 'utf-16le').decode(new Uint8Array(str.$bytes())); if (block !== nil) { // dont know the bytes anymore ... ¯\_(ツ)_/¯ result = result.replace(/�/g, (byte)=>{ return #{yield `byte`}; }); } else if (replacement && replacement !== nil) { // this may replace valid � that have existed in the string before, // but there currently is no way to specify a other replacement character for TextDecoder result = result.replace(/�/g, replacement); } return $str(result, self); } end def valid_encoding?(str) %x{ try { validating_decoder(self, 'utf-16').decode(new Uint8Array(str.$bytes())); } catch { return false; } return true; } end end ::Encoding.register 'UTF-16BE', inherits: ::Encoding::UTF_16LE do def decode(io_buffer) %x{ let result = scrubbing_decoder(self, 'utf-16be').decode(io_buffer.data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let result = validating_decoder(self, 'utf-16be').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ for (var i = 0, length = str.length; i < length; i++) { var char_code = str.charCodeAt(i); #{yield `char_code >> 8`}; #{yield `char_code & 0xff`}; } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let char_code, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for (let i = 0, length = str.length; i < length; i++) { char_code = str.charCodeAt(i); set_byte(char_code >> 8); set_byte(char_code & 0xff); } if (pos > 0) { #{yield pos} } } str end def scrub(str, replacement, &block) %x{ let result = scrubbing_decoder(self, 'utf-16be').decode(new Uint8Array(str.$bytes())); if (block !== nil) { // dont know the bytes anymore ... ¯\_(ツ)_/¯ result = result.replace(/�/g, (byte)=>{ return #{yield `byte`}; }); } else if (replacement && replacement !== nil) { // this may replace valid � that have existed in the string before, // but there currently is no way to specify a other replacement character for TextDecoder result = result.replace(/�/g, replacement); } return $str(result, self); } end def valid_encoding?(str) %x{ try { validating_decoder(self, 'utf-16be').decode(new Uint8Array(str.$bytes())); } catch { return false; } return true; } end end ::Encoding.register 'UTF-32LE' do def bytesize(str, index) %x{ if (index < str.length) return (index + 1) * 4; return str.length * 4; } end def byteslice(str, index, length) # Must handle negative index and length, with length being negative indicating a negative range end. %x{ let result = "", char_code, idx, max, i; if (index < 0) { // negative index, walk from the end of the string, idx = -1; if (length < 0) max = length; // a negative index else if (length === 0) max = index; else if ((index + length) >= 0) max = -1; // from end of string else max = index + length - 1; for (i = str.length; i > 0; i--) { char_code = str.charCodeAt(i); if (length > 0 || length === -1 || (length < 0 && idx <= length)) { if (idx >= index && idx <= max) result = SFCC(char_code) + result; } idx -= 4; if (idx < index) break; } if (idx > index || result.length === 0) return nil; } else { // 0 or positive index, walk from beginning idx = 0; if (length < 0) max = Infinity; else if (length === 0) max = index + 1; else max = index + length; for (let i = 0, length = str.length; i < length; i++) { char_code = str.charCodeAt(i); if (idx >= index && idx <= max) result += SFCC(char_code); idx += 4; if (idx >= max) break; } if (result.length === 0) { if (idx === index) result = ""; else return nil; } if (length < 0) { // if length is a negative index from a range, we walked to the end, so shorten the result if ((idx + length) > 0) result = result.slice(0, result.length + length); else result = ""; } } if (length === 0) result = ""; return result; } end def decode(io_buffer) %x{ let i = 0, o = 0, io_dv = io_buffer.data_view, io_dv_bl = io_dv.byteLength, data_view = new DataView(new ArrayBuffer(Math.ceil(io_dv_bl / 2))); while (i < io_dv_bl) { data_view.setUint8(o++, io_dv.getUint8(i++)); if (i < io_dv_bl) data_view.setUint8(o++, io_dv.getUint8(i++)); i += 2; } let result = scrubbing_decoder(self, 'utf-16').decode(data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let i = 0, o = 0, io_dv = io_buffer.data_view, io_dv_bl = io_dv.byteLength, data_view = new DataView(new ArrayBuffer(Math.ceil(io_dv_bl / 2))); while (i < io_dv_bl) { data_view.setUint8(o++, io_dv.getUint8(i++)); if (i < io_dv_bl) data_view.setUint8(o++, io_dv.getUint8(i++)); i += 2; } let result = validating_decoder(self, 'utf-16').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ for (var i = 0, length = str.length; i < length; i++) { var char_code = str.charCodeAt(i); #{yield `char_code & 0xff`}; #{yield `char_code >> 8`}; #{yield 0}; #{yield 0}; } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let char_code, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for (let i = 0, length = str.length; i < length; i++) { char_code = str.charCodeAt(i); set_byte(char_code & 0xff); set_byte(char_code >> 8); set_byte(0); set_byte(0); } if (pos > 0) { #{yield pos} } } str end def scrub(str, replacement) str end def valid_encoding?(str) true end end ::Encoding.register 'UTF-32BE', inherits: ::Encoding::UTF_32LE do def decode(io_buffer) %x{ let i = 0, o = 0, io_dv = io_buffer.data_view, io_dv_bl = io_dv.byteLength, data_view = new DataView(new ArrayBuffer(Math.floor(io_dv_bl / 2))); while (i < io_dv_bl) { i += 2; if (i < io_dv_bl) data_view.setUint8(o++, io_dv.getUint8(i++)); if (i < io_dv_bl) data_view.setUint8(o++, io_dv.getUint8(i++)); } let result = scrubbing_decoder(self, 'utf-16').decode(data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let i = 0, o = 0, io_dv = io_buffer.data_view, io_dv_bl = io_dv.byteLength, data_view = new DataView(new ArrayBuffer(Math.floor(io_dv_bl / 2))); while (i < io_dv_bl) { i += 2; if (i < io_dv_bl) data_view.setUint8(o++, io_dv.getUint8(i++)); if (i < io_dv_bl) data_view.setUint8(o++, io_dv.getUint8(i++)); } let result = validating_decoder(self, 'utf-16').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ for (var i = 0, length = str.length; i < length; i++) { var char_code = str.charCodeAt(i); #{yield 0}; #{yield 0}; #{yield `char_code >> 8`}; #{yield `char_code & 0xff`}; } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let char_code, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for (let i = 0, length = str.length; i < length; i++) { char_code = str.charCodeAt(i); set_byte(0); set_byte(0); set_byte(char_code >> 8); set_byte(char_code & 0xff); } if (pos > 0) { #{yield pos} } } str end end ::Encoding.register 'ASCII-8BIT', aliases: ['BINARY'], ascii: true do def binary? true end def bytesize(str, index) %x{ if (index < str.size) return index + 1; return str.length; } end def byteslice(str, index, length) # Must handle negative index and length, with length being negative indicating a negative range end. %x{ let result = "", char_code, i; if (index < 0) index = str.length + index; if (index < 0) return nil; if (length < 0) length = (str.length + length) - index; if (length < 0) return nil; // must produce the same result as each_byte, so we cannot simply use slice() for (i = 0; i < length && (index + i) <= str.length; i++) { char_code = str.charCodeAt(index + i); result = SFCC(char_code & 0xff) + result; } if (result.length === 0) return nil; return result; } end def decode(io_buffer) %x{ let result = scrubbing_decoder(self, 'ascii').decode(io_buffer.data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let result = validating_decoder(self, 'ascii').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ for (let i = 0, length = str.length; i < length; i++) { #{yield `str.charCodeAt(i) & 0xff`}; } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for (let i = 0, length = str.length; i < length; i++) { set_byte(str.charCodeAt(i) & 0xff); } if (pos > 0) { #{yield pos} } } str end def scrub(str, replacement, &block) %x{ let result = scrubbing_decoder(self, 'ascii').decode(new Uint8Array(str.$bytes())); if (block !== nil) { // dont know all the bytes anymore ... ¯\_(ツ)_/¯ result = result.replace(/[�\x80-\xff]/g, (byte)=>{ return #{yield `byte`}; }); } else if (replacement && replacement !== nil) { // this may replace valid � that have existed in the string before, // but there currently is no way to specify a other replacement character for TextDecoder result = result.replace(/[�\x80-\xff]/g, replacement); } else { result = result.replace(/[�\x80-\xff]/g, '?'); } return $str(result, self); } end def valid_encoding?(str) %x{ try { validating_decoder(self, 'ascii').decode(new Uint8Array(str.$bytes())); } catch { return false; } return true; } end end ::Encoding.register 'ISO-8859-1', aliases: ['ISO8859-1'], ascii: true, inherits: ::Encoding::ASCII_8BIT ::Encoding.register 'US-ASCII', aliases: ['ASCII'], ascii: true, inherits: ::Encoding::ASCII_8BIT ::Encoding.default_external = __ENCODING__ ::Encoding.default_internal = __ENCODING__ `Opal.prop(String.prototype, 'encoding', #{::Encoding::UTF_8})` `Opal.prop(String.prototype, 'internal_encoding', #{::Encoding::UTF_8})`
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/unpack.rb
opal/corelib/string/unpack.rb
# backtick_javascript: true require 'base64' require 'corelib/pack_unpack/format_string_parser' class ::String %x{ // Format Parser var eachDirectiveAndCount = Opal.PackUnpack.eachDirectiveAndCount; function flattenArray(callback) { return function(data) { var array = callback(data); return #{`array`.flatten}; } } function mapChunksToWords(callback) { return function(data) { var chunks = callback(data); return chunks.map(function(chunk) { return chunk.reverse().reduce(function(result, singleByte) { return result * 256 + singleByte; }, 0); }); } } function chunkBy(chunkSize, callback) { return function(data) { var array = callback(data), chunks = [], chunksCount = (array.length / chunkSize); for (var i = 0; i < chunksCount; i++) { var chunk = array.splice(0, chunkSize); if (chunk.length === chunkSize) { chunks.push(chunk); } } return chunks; } } function toNByteSigned(bytesCount, callback) { return function(data) { var unsignedBits = callback(data), bitsCount = bytesCount * 8, limit = Math.pow(2, bitsCount); return unsignedBits.map(function(n) { if (n >= limit / 2) { n -= limit; } return n; }); } } function bytesToAsciiChars(callback) { return function(data) { var bytes = callback(data); return bytes.map(function(singleByte) { return String.fromCharCode(singleByte); }); } } function joinChars(callback) { return function(data) { var chars = callback(data); return chars.join(''); } } var hostLittleEndian = (function() { var uint32 = new Uint32Array([0x11223344]); return new Uint8Array(uint32.buffer)[0] === 0x44; })(); function bytesToFloat(bytes, little, size) { var view = new DataView(new ArrayBuffer(size)); for (var i = 0; i < size; i++) { view.setUint8(i, bytes[i]); } return size === 4 ? view.getFloat32(0, little) : view.getFloat64(0, little); } function mapChunksToFloat(size, little, callback) { return function(data) { var chunks = chunkBy(size, callback)(data); return chunks.map(function(chunk) { return bytesToFloat(chunk, little, size); }); } } function wrapIntoArray(callback) { return function(data) { var object = callback(data); return [object]; } } function filterTrailingChars(chars) { var charCodesToFilter = chars.map(function(s) { return s.charCodeAt(0); }); return function(callback) { return function(data) { var charCodes = callback(data); while (charCodesToFilter.indexOf(charCodes[charCodes.length - 1]) !== -1) { charCodes = charCodes.slice(0, charCodes.length - 1); } return charCodes; } } } var filterTrailingZerosAndSpaces = filterTrailingChars(["\u0000", " "]); function invertChunks(callback) { return function(data) { var chunks = callback(data); return chunks.map(function(chunk) { return chunk.reverse(); }); } } function uudecode(callback) { return function(data) { var bytes = callback(data); var stop = false; var i = 0, length = 0; var result = []; do { if (i < bytes.length) { var n = bytes[i] - 32 & 0x3F; ++i; if (bytes[i] === 10) { continue; } if (n > 45) { return ''; } length += n; while (n > 0) { var c1 = bytes[i]; var c2 = bytes[i + 1]; var c3 = bytes[i + 2]; var c4 = bytes[i + 3]; var b1 = (c1 - 32 & 0x3F) << 2 | (c2 - 32 & 0x3F) >> 4; var b2 = (c2 - 32 & 0x3F) << 4 | (c3 - 32 & 0x3F) >> 2; var b3 = (c3 - 32 & 0x3F) << 6 | c4 - 32 & 0x3F; result.push(b1 & 0xFF); result.push(b2 & 0xFF); result.push(b3 & 0xFF); i += 4; n -= 3; } ++i; } else { break; } } while (true); return result.slice(0, length); } } function toBits(callback) { return function(data) { var bytes = callback(data); var bits = bytes.map(function(singleByte) { return singleByte.toString(2); }); return bits; } } function decodeBERCompressedIntegers(callback) { return function(data) { var bytes = callback(data), result = [], buffer = ''; for (var i = 0; i < bytes.length; i++) { var singleByte = bytes[i], bits = singleByte.toString(2); bits = Array(8 - bits.length + 1).join('0').concat(bits); var firstBit = bits[0]; bits = bits.slice(1, bits.length); buffer = buffer.concat(bits); if (firstBit === '0') { var decoded = parseInt(buffer, 2); result.push(decoded); buffer = '' } } return result; } } function base64Decode(callback) { return function(data) { return #{Base64.decode64(`callback(data)`)}; } } // quoted-printable decode function qpdecode(callback) { return function(data) { var string = callback(data); return string .replace(/[\t\x20]$/gm, '') .replace(/=(?:\r\n?|\n|$)/g, '') .replace(/=([a-fA-F0-9]{2})/g, function($0, $1) { var codePoint = parseInt($1, 16); return String.fromCharCode(codePoint); }); } } function identityFunction(value) { return value; } var handlers = { // Integer 'C': identityFunction, 'S': mapChunksToWords(chunkBy(2, identityFunction)), 'L': mapChunksToWords(chunkBy(4, identityFunction)), 'Q': mapChunksToWords(chunkBy(8, identityFunction)), 'J': null, 'S>': mapChunksToWords(invertChunks(chunkBy(2, identityFunction))), 'L>': mapChunksToWords(invertChunks(chunkBy(4, identityFunction))), 'Q>': mapChunksToWords(invertChunks(chunkBy(8, identityFunction))), 'c': toNByteSigned(1, identityFunction), 's': toNByteSigned(2, mapChunksToWords(chunkBy(2, identityFunction))), 'l': toNByteSigned(4, mapChunksToWords(chunkBy(4, identityFunction))), 'q': toNByteSigned(8, mapChunksToWords(chunkBy(8, identityFunction))), 'j': null, 's>': toNByteSigned(2, mapChunksToWords(invertChunks(chunkBy(2, identityFunction)))), 'l>': toNByteSigned(4, mapChunksToWords(invertChunks(chunkBy(4, identityFunction)))), 'q>': toNByteSigned(8, mapChunksToWords(invertChunks(chunkBy(8, identityFunction)))), 'n': null, // aliased later 'N': null, // aliased later 'v': null, // aliased later 'V': null, // aliased later 'U': identityFunction, 'w': decodeBERCompressedIntegers(identityFunction), 'x': function(data) { return []; }, // Float 'D': mapChunksToFloat(8, hostLittleEndian, identityFunction), 'd': mapChunksToFloat(8, hostLittleEndian, identityFunction), 'F': mapChunksToFloat(4, hostLittleEndian, identityFunction), 'f': mapChunksToFloat(4, hostLittleEndian, identityFunction), 'E': mapChunksToFloat(8, true, identityFunction), 'e': mapChunksToFloat(4, true, identityFunction), 'G': mapChunksToFloat(8, false, identityFunction), 'g': mapChunksToFloat(4, false, identityFunction), // String 'A': wrapIntoArray(joinChars(bytesToAsciiChars(filterTrailingZerosAndSpaces(identityFunction)))), 'a': wrapIntoArray(joinChars(bytesToAsciiChars(identityFunction))), 'Z': joinChars(bytesToAsciiChars(identityFunction)), 'B': joinChars(identityFunction), 'b': joinChars(identityFunction), 'H': joinChars(identityFunction), 'h': joinChars(identityFunction), 'u': joinChars(bytesToAsciiChars(uudecode(identityFunction))), 'M': qpdecode(joinChars(bytesToAsciiChars(identityFunction))), 'm': base64Decode(joinChars(bytesToAsciiChars(identityFunction))), 'P': null, 'p': null }; function readBytes(n) { return function(bytes) { var chunk = bytes.slice(0, n); bytes = bytes.slice(n, bytes.length); return { chunk: chunk, rest: bytes }; } } function readUnicodeCharChunk(bytes) { var currentByteIndex = 0; var bytesLength = bytes.length; function readByte() { var result = bytes[currentByteIndex++]; bytesLength = bytes.length - currentByteIndex; return result; } var c = readByte(), extraLength; if (c >> 7 == 0) { // 0xxx xxxx return { chunk: [c], rest: bytes.slice(currentByteIndex) }; } if (c >> 6 == 0x02) { #{::Kernel.raise ::ArgumentError, 'malformed UTF-8 character'} } if (c >> 5 == 0x06) { // 110x xxxx (two bytes) extraLength = 1; } else if (c >> 4 == 0x0e) { // 1110 xxxx (three bytes) extraLength = 2; } else if (c >> 3 == 0x1e) { // 1111 0xxx (four bytes) extraLength = 3; } else if (c >> 2 == 0x3e) { // 1111 10xx (five bytes) extraLength = 4; } else if (c >> 1 == 0x7e) { // 1111 110x (six bytes) extraLength = 5; } else { #{::Kernel.raise 'malformed UTF-8 character'} } if (extraLength > bytesLength) { #{ expected = `extraLength + 1` given = `bytesLength + 1` ::Kernel.raise ::ArgumentError, "malformed UTF-8 character (expected #{expected} bytes, given #{given} bytes)" } } // Remove the UTF-8 prefix from the char var mask = (1 << (8 - extraLength - 1)) - 1, result = c & mask; for (var i = 0; i < extraLength; i++) { c = readByte(); if (c >> 6 != 0x02) { #{::Kernel.raise 'Invalid multibyte sequence'} } result = (result << 6) | (c & 0x3f); } if (result <= 0xffff) { return { chunk: [result], rest: bytes.slice(currentByteIndex) }; } else { result -= 0x10000; var high = ((result >> 10) & 0x3ff) + 0xd800, low = (result & 0x3ff) + 0xdc00; return { chunk: [high, low], rest: bytes.slice(currentByteIndex) }; } } function readUuencodingChunk(buffer) { var length = buffer.indexOf(32); // 32 = space if (length === -1) { return { chunk: buffer, rest: [] }; } else { return { chunk: buffer.slice(0, length), rest: buffer.slice(length, buffer.length) }; } } function readNBitsLSBFirst(buffer, count) { var result = ''; while (count > 0 && buffer.length > 0) { var singleByte = buffer[0], bitsToTake = Math.min(count, 8), bytesToTake = Math.ceil(bitsToTake / 8); buffer = buffer.slice(1, buffer.length); if (singleByte != null) { var bits = singleByte.toString(2); bits = Array(8 - bits.length + 1).join('0').concat(bits).split('').reverse().join(''); for (var j = 0; j < bitsToTake; j++) { result += bits[j] || '0'; count--; } } } return { chunk: [result], rest: buffer }; } function readNBitsMSBFirst(buffer, count) { var result = ''; while (count > 0 && buffer.length > 0) { var singleByte = buffer[0], bitsToTake = Math.min(count, 8), bytesToTake = Math.ceil(bitsToTake / 8); buffer = buffer.slice(1, buffer.length); if (singleByte != null) { var bits = singleByte.toString(2); bits = Array(8 - bits.length + 1).join('0').concat(bits); for (var j = 0; j < bitsToTake; j++) { result += bits[j] || '0'; count--; } } } return { chunk: [result], rest: buffer }; } function readWhileFirstBitIsOne(buffer) { var result = []; for (var i = 0; i < buffer.length; i++) { var singleByte = buffer[i]; result.push(singleByte); if ((singleByte & 128) === 0) { break; } } return { chunk: result, rest: buffer.slice(result.length, buffer.length) }; } function readTillNullCharacter(buffer, count) { var result = []; for (var i = 0; i < count && i < buffer.length; i++) { var singleByte = buffer[i]; if (singleByte === 0) { break; } else { result.push(singleByte); } } if (count === Infinity) { count = result.length; } if (buffer[count] === 0) { count++; } buffer = buffer.slice(count, buffer.length); return { chunk: result, rest: buffer }; } function readHexCharsHighNibbleFirst(buffer, count) { var result = []; while (count > 0 && buffer.length > 0) { var singleByte = buffer[0], hex = singleByte.toString(16); buffer = buffer.slice(1, buffer.length); hex = Array(2 - hex.length + 1).join('0').concat(hex); if (count === 1) { result.push(hex[0]); count--; } else { result.push(hex[0], hex[1]); count -= 2; } } return { chunk: result, rest: buffer }; } function readHexCharsLowNibbleFirst(buffer, count) { var result = []; while (count > 0 && buffer.length > 0) { var singleByte = buffer[0], hex = singleByte.toString(16); buffer = buffer.slice(1, buffer.length); hex = Array(2 - hex.length + 1).join('0').concat(hex); if (count === 1) { result.push(hex[1]); count--; } else { result.push(hex[1], hex[0]); count -= 2; } } return { chunk: result, rest: buffer }; } function readNTimesAndMerge(callback) { return function(buffer, count) { var chunk = [], chunkData; if (count === Infinity) { while (buffer.length > 0) { chunkData = callback(buffer); buffer = chunkData.rest; chunk = chunk.concat(chunkData.chunk); } } else { for (var i = 0; i < count; i++) { chunkData = callback(buffer); buffer = chunkData.rest; chunk = chunk.concat(chunkData.chunk); } } return { chunk: chunk, rest: buffer }; } } function readAll(buffer, count) { return { chunk: buffer, rest: [] }; } var readChunk = { // Integer 'C': readNTimesAndMerge(readBytes(1)), 'S': readNTimesAndMerge(readBytes(2)), 'L': readNTimesAndMerge(readBytes(4)), 'Q': readNTimesAndMerge(readBytes(8)), 'J': null, 'S>': readNTimesAndMerge(readBytes(2)), 'L>': readNTimesAndMerge(readBytes(4)), 'Q>': readNTimesAndMerge(readBytes(8)), 'c': readNTimesAndMerge(readBytes(1)), 's': readNTimesAndMerge(readBytes(2)), 'l': readNTimesAndMerge(readBytes(4)), 'q': readNTimesAndMerge(readBytes(8)), 'j': null, 's>': readNTimesAndMerge(readBytes(2)), 'l>': readNTimesAndMerge(readBytes(4)), 'q>': readNTimesAndMerge(readBytes(8)), 'n': null, // aliased later 'N': null, // aliased later 'v': null, // aliased later 'V': null, // aliased later 'U': readNTimesAndMerge(readUnicodeCharChunk), 'w': readNTimesAndMerge(readWhileFirstBitIsOne), 'x': function(buffer, count) { if (count === Infinity) count = 1; return { chunk: [], rest: buffer.slice(count) }; }, // Float 'D': readNTimesAndMerge(readBytes(8)), 'd': readNTimesAndMerge(readBytes(8)), 'F': readNTimesAndMerge(readBytes(4)), 'f': readNTimesAndMerge(readBytes(4)), 'E': readNTimesAndMerge(readBytes(8)), 'e': readNTimesAndMerge(readBytes(4)), 'G': readNTimesAndMerge(readBytes(8)), 'g': readNTimesAndMerge(readBytes(4)), // String 'A': readNTimesAndMerge(readBytes(1)), 'a': readNTimesAndMerge(readBytes(1)), 'Z': readTillNullCharacter, 'B': readNBitsMSBFirst, 'b': readNBitsLSBFirst, 'H': readHexCharsHighNibbleFirst, 'h': readHexCharsLowNibbleFirst, 'u': readNTimesAndMerge(readUuencodingChunk), 'M': readAll, 'm': readAll, 'P': null, 'p': null } var autocompletion = { // Integer 'C': true, 'S': true, 'L': true, 'Q': true, 'J': null, 'S>': true, 'L>': true, 'Q>': true, 'c': true, 's': true, 'l': true, 'q': true, 'j': null, 's>': true, 'l>': true, 'q>': true, 'n': null, // aliased later 'N': null, // aliased later 'v': null, // aliased later 'V': null, // aliased later 'U': false, 'w': false, 'x': false, // Float 'D': true, 'd': true, 'F': true, 'f': true, 'E': true, 'e': true, 'G': true, 'g': true, // String 'A': false, 'a': false, 'Z': false, 'B': false, 'b': false, 'H': false, 'h': false, 'u': false, 'M': false, 'm': false, 'P': null, 'p': null } var optimized = { 'C*': handlers['C'], 'c*': handlers['c'], 'A*': handlers['A'], 'a*': handlers['a'], 'M*': wrapIntoArray(handlers['M']), 'm*': wrapIntoArray(handlers['m']), 'S*': handlers['S'], 's*': handlers['s'], 'L*': handlers['L'], 'l*': handlers['l'], 'Q*': handlers['Q'], 'q*': handlers['q'], 'S>*': handlers['S>'], 's>*': handlers['s>'], 'L>*': handlers['L>'], 'l>*': handlers['l>'], 'Q>*': handlers['Q>'], 'q>*': handlers['q>'], 'F*': handlers['F'], 'f*': handlers['f'], 'D*': handlers['D'], 'd*': handlers['d'], 'E*': handlers['E'], 'e*': handlers['e'], 'G*': handlers['G'], 'g*': handlers['g'] } function alias(existingDirective, newDirective) { readChunk[newDirective] = readChunk[existingDirective]; handlers[newDirective] = handlers[existingDirective]; autocompletion[newDirective] = autocompletion[existingDirective]; } alias('S>', 'n'); alias('L>', 'N'); alias('S', 'v'); alias('L', 'V'); alias('D', 'd'); alias('F', 'f'); } def unpack(format, offset: 0) ::Kernel.raise ::ArgumentError, "offset can't be negative" if offset < 0 format = ::Opal.coerce_to!(format, ::String, :to_str) .gsub(/#.*/, '') .gsub(/\s/, '') .delete("\000") %x{ var output = []; // A very optimized handler for U*. if (format == "U*" && self.internal_encoding.name === "UTF-8" && typeof self.codePointAt === "function") { var cp, j = 0; output = new Array(self.length); for (var i = offset; i < self.length; i++) { cp = output[j++] = self.codePointAt(i); if (cp > 0xffff) i++; } return output.slice(0, j); } var buffer = self.$bytes(); #{::Kernel.raise ::ArgumentError, 'offset outside of string' if offset > `buffer`.length} buffer = buffer.slice(offset); // optimization var optimizedHandler = optimized[format]; if (optimizedHandler) { return optimizedHandler(buffer); } function autocomplete(array, size) { while (array.length < size) { array.push(nil); } return array; } function processChunk(directive, count) { var chunk, chunkReader = readChunk[directive]; if (chunkReader == null) { #{::Kernel.raise "Unsupported unpack directive #{`directive`.inspect} (no chunk reader defined)"} } var chunkData = chunkReader(buffer, count); chunk = chunkData.chunk; buffer = chunkData.rest; var handler = handlers[directive]; if (handler == null) { #{::Kernel.raise "Unsupported unpack directive #{`directive`.inspect} (no handler defined)"} } return handler(chunk); } eachDirectiveAndCount(format, function(directive, count) { var part = processChunk(directive, count); if (count !== Infinity) { var shouldAutocomplete = autocompletion[directive]; if (shouldAutocomplete == null) { #{::Kernel.raise "Unsupported unpack directive #{`directive`.inspect} (no autocompletion rule defined)"} } if (shouldAutocomplete) { autocomplete(part, count); } } output = output.concat(part); }); return output; } end def unpack1(format, offset: 0) format = ::Opal.coerce_to!(format, ::String, :to_str).gsub(/\s/, '').delete("\000") unpack(format[0], offset: offset)[0] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding/sjis.rb
opal/corelib/string/encoding/sjis.rb
# backtick_javascript: true # helpers: str # inspired by # Jconv # Copyright (c) 2013-2014 narirou # MIT Licensed # https://github.com/narirou/jconv # modified for Opal: # https://github.com/janbiedermann/jconv/tree/for_opal # only converts UCS2/UTF16 string to JIS/SJIS/EUCJP byte buffer # performance: # https://github.com/janbiedermann/jconv/blob/for_opal/test/chart/speedLog.txt require 'corelib/string/encoding' require 'corelib/string/encoding/tables/sjis_inverted' %x{ const SJISInverted = Opal.Encoding.SJISInverted; let unknownSjis = SJISInverted[ '・'.charCodeAt( 0 ) ]; function scrubbing_decoder(enc, label) { if (!enc.scrubbing_decoder) enc.scrubbing_decoder = new TextDecoder(label, { fatal: false }); return enc.scrubbing_decoder; } function validating_decoder(enc, label) { if (!enc.validating_decoder) enc.validating_decoder = new TextDecoder(label, { fatal: true }); return enc.validating_decoder; } } ::Encoding.register 'Shift_JIS', aliases: %w[SHIFT_JIS SJIS] do def bytesize(str, index) %x{ let unicode, size = 0; for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { size++; } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { size++; } // KANJI else { let code = SJISInverted[ unicode ] || unknownSjis; size += 2; } if (index-- <= 0) break; } return size; } end def byteslice(str, index, length) # Must handle negative index and length, with length being negative indicating a negative range end. %x{ if (index < 0) index = str.length + index; if (index < 0) return nil; if (length < 0) length = (str.length + length) - index; if (length < 0) return nil; let bytes_ary = str.$bytes(); bytes_ary = bytes_ary.slice(index, index + length); let result = scrubbing_decoder(self, 'sjis').decode(new Uint8Array(bytes_ary)); if (result.length === 0) return nil; return $str(result, self); } end def decode(io_buffer) %x{ let result = scrubbing_decoder(self, 'sjis').decode(io_buffer.data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let result = validating_decoder(self, 'sjis').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ let unicode; for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { #{yield `unicode`}; } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { #{yield `unicode - 0xFEC0`}; } // KANJI else { let code = SJISInverted[ unicode ] || unknownSjis; #{yield `code >> 8`}; #{yield `code & 0xFF`}; } } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let unicode, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { set_byte(unicode); } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { set_byte(unicode - 0xFEC0); } // KANJI else { let code = SJISInverted[ unicode ] || unknownSjis; set_byte(code >> 8); set_byte(code & 0xFF); } } } end def scrub(str, replacement, &block) %x{ let result = scrubbing_decoder(self, 'sjis').decode(new Uint8Array(str.$bytes())); if (block !== nil) { // dont know the bytes anymore ... ¯\_(ツ)_/¯ result = result.replace(/�/g, (byte)=>{ return #{yield `byte`}; }); } else if (replacement && replacement !== nil) { // this may replace valid � that have existed in the string before, // but there currently is no way to specify a other replacement character for TextDecoder result = result.replace(/�/g, replacement); } return $str(result, self); } end def valid_encoding?(str) %x{ try { validating_decoder(self, 'sjis').decode(new Uint8Array(str.$bytes())); } catch { return false; } return true; } end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding/dummy.rb
opal/corelib/string/encoding/dummy.rb
# backtick_javascript: true require 'corelib/string/encoding' # these encodings are required for some ruby specs, make them dummy for now # their existence is often enough, like specs checking if a method returns # a new string in the same encoding it was orginally encoded in ::Encoding.register 'IBM437', inherits: ::Encoding::UTF_16LE, dummy: true ::Encoding.register 'IBM720', inherits: ::Encoding::UTF_16LE, dummy: true ::Encoding.register 'IBM866', inherits: ::Encoding::UTF_16LE, dummy: true ::Encoding.register 'ISO-8859-15', inherits: ::Encoding::UTF_16LE, dummy: true ::Encoding.register 'ISO-8859-5', inherits: ::Encoding::UTF_16LE, dummy: true ::Encoding.register 'Windows-1251', aliases: ['WINDOWS-1251'], inherits: ::Encoding::UTF_16LE, dummy: true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding/jis.rb
opal/corelib/string/encoding/jis.rb
# backtick_javascript: true # helpers: str # inspired by # Jconv # Copyright (c) 2013-2014 narirou # MIT Licensed # https://github.com/narirou/jconv # modified for Opal: # https://github.com/janbiedermann/jconv/tree/for_opal # only converts UCS2/UTF16 string to JIS/SJIS/EUCJP byte buffer # performance: # https://github.com/janbiedermann/jconv/blob/for_opal/test/chart/speedLog.txt require 'corelib/string/encoding' require 'corelib/string/encoding/tables/jis_inverted' require 'corelib/string/encoding/tables/jis_ext_inverted' %x{ const JISInverted = Opal.Encoding.JISInverted; const JISEXTInverted = Opal.Encoding.JISEXTInverted; let unknownJis = JISInverted[ '・'.charCodeAt( 0 ) ]; function scrubbing_decoder(enc, label) { if (!enc.scrubbing_decoder) enc.scrubbing_decoder = new TextDecoder(label, { fatal: false }); return enc.scrubbing_decoder; } function validating_decoder(enc, label) { if (!enc.validating_decoder) enc.validating_decoder = new TextDecoder(label, { fatal: true }); return enc.validating_decoder; } } ::Encoding.register 'ISO-2022-JP', aliases: ['JIS'] do def bytesize(str, index) %x{ let sequence = 0, size = 0, unicode; for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { if( sequence !== 0 ) { sequence = 0; size += 3; } size++; } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { if( sequence !== 1 ) { sequence = 1; size += 3; } size++; } else { var code = JISInverted[ unicode ]; if( code ) { // KANJI if( sequence !== 2 ) { sequence = 2; size += 3; } size += 2; } else { var ext = JISEXTInverted[ unicode ]; if( ext ) { // EXTENSION if( sequence !== 3 ) { sequence = 3; size += 4; } size += 2; } else { // UNKNOWN if( sequence !== 2 ) { sequence = 2; size += 3; } size += 2; } } } if (index-- <= 0) break; } // Add ASCII ESC if( sequence !== 0 ) { sequence = 0; size += 3; } return size; } end def byteslice(str, index, length) # Must handle negative index and length, with length being negative indicating a negative range end. %x{ if (index < 0) index = str.length + index; if (index < 0) return nil; if (length < 0) length = (str.length + length) - index; if (length < 0) return nil; let bytes_ary = str.$bytes(); bytes_ary = bytes_ary.slice(index, index + length); let result = scrubbing_decoder(self, 'iso-2022-jp').decode(new Uint8Array(bytes_ary)); if (result.length === 0) return nil; return $str(result, self); } end def decode(io_buffer) %x{ let result = scrubbing_decoder(self, 'iso-2022-jp').decode(io_buffer.data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let result = validating_decoder(self, 'iso-2022-jp').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ let sequence = 0, unicode; for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { if( sequence !== 0 ) { sequence = 0; #{yield `0x1B`}; #{yield `0x28`}; #{yield `0x42`}; } #{yield `unicode`}; } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { if( sequence !== 1 ) { sequence = 1; #{yield `0x1B`}; #{yield `0x28`}; #{yield `0x49`}; } #{yield `unicode - 0xFF40`}; } else { var code = JISInverted[ unicode ]; if( code ) { // KANJI if( sequence !== 2 ) { sequence = 2; #{yield `0x1B`}; #{yield `0x24`}; #{yield `0x42`}; } #{yield `code >> 8`}; #{yield `code & 0xFF`}; } else { var ext = JISEXTInverted[ unicode ]; if( ext ) { // EXTENSION if( sequence !== 3 ) { sequence = 3; #{yield `0x1B`}; #{yield `0x24`}; #{yield `0x28`}; #{yield `0x44`}; } #{yield `ext >> 8`}; #{yield `ext & 0xFF`}; } else { // UNKNOWN if( sequence !== 2 ) { sequence = 2; #{yield `0x1B`}; #{yield `0x24`}; #{yield `0x42`}; } #{yield `unknownJis >> 8`}; #{yield `unknownJis & 0xFF`}; } } } } // Add ASCII ESC if( sequence !== 0 ) { sequence = 0; #{yield `0x1B`}; #{yield `0x28`}; #{yield `0x42`}; } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let sequence = 0, unicode, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { if( sequence !== 0 ) { sequence = 0; set_byte(0x1B); set_byte(0x28); set_byte(0x42); } set_byte(unicode); } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { if( sequence !== 1 ) { sequence = 1; set_byte(0x1B); set_byte(0x28); set_byte(0x49); } set_byte(unicode - 0xFF40); } else { var code = JISInverted[ unicode ]; if( code ) { // KANJI if( sequence !== 2 ) { sequence = 2; set_byte(0x1B); set_byte(0x24); set_byte(0x42); } set_byte(code >> 8); set_byte(code & 0xFF); } else { var ext = JISEXTInverted[ unicode ]; if( ext ) { // EXTENSION if( sequence !== 3 ) { sequence = 3; set_byte(0x1B); set_byte(0x24); set_byte(0x28); set_byte(0x44); } set_byte(ext >> 8); set_byte(ext & 0xFF); } else { // UNKNOWN if( sequence !== 2 ) { sequence = 2; set_byte(0x1B); set_byte(0x24); set_byte(0x42); } set_byte(unknownJis >> 8); set_byte(unknownJis & 0xFF); } } } } // Add ASCII ESC if( sequence !== 0 ) { sequence = 0; set_byte(0x1B); set_byte(0x28); set_byte(0x42); } } end def scrub(str, replacement, &block) %x{ let result = scrubbing_decoder(self, 'iso-2022-jp').decode(new Uint8Array(str.$bytes())); if (block !== nil) { // dont know the bytes anymore ... ¯\_(ツ)_/¯ result = result.replace(/�/g, (byte)=>{ return #{yield `byte`}; }); } else if (replacement && replacement !== nil) { // this may replace valid � that have existed in the string before, // but there currently is no way to specify a other replacement character for TextDecoder result = result.replace(/�/g, replacement); } return $str(result, self); } end def valid_encoding?(str) %x{ try { validating_decoder(self, 'iso-2022-jp').decode(new Uint8Array(str.$bytes())); } catch { return false; } return true; } end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding/eucjp.rb
opal/corelib/string/encoding/eucjp.rb
# backtick_javascript: true # helpers: str # inspired by # Jconv # Copyright (c) 2013-2014 narirou # MIT Licensed # https://github.com/narirou/jconv # modified for Opal: # https://github.com/janbiedermann/jconv/tree/for_opal # only converts UCS2/UTF16 string to JIS/SJIS/EUCJP byte buffer # performance: # https://github.com/janbiedermann/jconv/blob/for_opal/test/chart/speedLog.txt require 'corelib/string/encoding' require 'corelib/string/encoding/tables/jis_inverted' require 'corelib/string/encoding/tables/jis_ext_inverted' %x{ const JISInverted = Opal.Encoding.JISInverted; const JISEXTInverted = Opal.Encoding.JISEXTInverted; let unknownJis = JISInverted[ '・'.charCodeAt( 0 ) ]; function scrubbing_decoder(enc, label) { if (!enc.scrubbing_decoder) enc.scrubbing_decoder = new TextDecoder(label, { fatal: false }); return enc.scrubbing_decoder; } function validating_decoder(enc, label) { if (!enc.validating_decoder) enc.validating_decoder = new TextDecoder(label, { fatal: true }); return enc.validating_decoder; } } ::Encoding.register 'EUC-JP' do def bytesize(str, index) %x{ let unicode, size = 0; for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { size++; } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { size += 2; } else { // KANJI var jis = JISInverted[ unicode ]; if( jis ) { size += 2; } else { // EXTENSION var ext = JISEXTInverted[ unicode ]; if( ext ) { size += 3; } // UNKNOWN else { size += 2; } } } if (index-- <= 0) break; } return size; } end def byteslice(str, index, length) # Must handle negative index and length, with length being negative indicating a negative range end. %x{ if (index < 0) index = str.length + index; if (index < 0) return nil; if (length < 0) length = (str.length + length) - index; if (length < 0) return nil; let bytes_ary = str.$bytes(); bytes_ary = bytes_ary.slice(index, index + length); let result = scrubbing_decoder(self, 'euc-jp').decode(new Uint8Array(bytes_ary)); if (result.length === 0) return nil; return $str(result, self); } end def decode(io_buffer) %x{ let result = scrubbing_decoder(self, 'euc-jp').decode(io_buffer.data_view); return $str(result, self); } end def decode!(io_buffer) %x{ let result = validating_decoder(self, 'euc-jp').decode(io_buffer.data_view); return $str(result, self); } end def each_byte(str) %x{ let unicode; for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { #{yield `unicode`}; } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { #{yield `0x8E`}; #{yield `unicode - 0xFFC0`}; } else { // KANJI var jis = JISInverted[ unicode ]; if( jis ) { #{yield `( jis >> 8 ) - 0x80`}; #{yield `( jis & 0xFF ) - 0x80`}; } else { // EXTENSION var ext = JISEXTInverted[ unicode ]; if( ext ) { #{yield `0x8F`}; #{yield `( ext >> 8 ) - 0x80`}; #{yield `( ext & 0xFF ) - 0x80`}; } // UNKNOWN else { #{yield `( unknownJis >> 8 ) - 0x80`}; #{yield `( unknownJis & 0xFF ) - 0x80`}; } } } } } end def each_byte_buffer(str, io_buffer) b_size = io_buffer.size pos = 0 %x{ let unicode, dv = io_buffer.data_view; function set_byte(byte) { if (pos === b_size) { #{yield pos} pos = 0; } dv.setUint8(pos++, byte); } for( const c of str ) { unicode = c.codePointAt(0); // ASCII if( unicode < 0x80 ) { set_byte(unicode); } // HALFWIDTH_KATAKANA else if( 0xFF61 <= unicode && unicode <= 0xFF9F ) { set_byte(0x8E); set_byte(unicode - 0xFFC0); } else { // KANJI var jis = JISInverted[ unicode ]; if( jis ) { set_byte(( jis >> 8 ) - 0x80); set_byte(( jis & 0xFF ) - 0x80); } else { // EXTENSION var ext = JISEXTInverted[ unicode ]; if( ext ) { set_byte(0x8F); set_byte(( ext >> 8 ) - 0x80); set_byte(( ext & 0xFF ) - 0x80); } // UNKNOWN else { set_byte(( unknownJis >> 8 ) - 0x80); set_byte(( unknownJis & 0xFF ) - 0x80); } } } } } end def scrub(str, replacement, &block) %x{ let result = scrubbing_decoder(self, 'euc-jp').decode(new Uint8Array(str.$bytes())); if (block !== nil) { // dont know the bytes anymore ... ¯\_(ツ)_/¯ result = result.replace(/�/g, (byte)=>{ return #{yield `byte`}; }); } else if (replacement && replacement !== nil) { // this may replace valid � that have existed in the string before, // but there currently is no way to specify a other replacement character for TextDecoder result = result.replace(/�/g, replacement); } return $str(result, self); } end def valid_encoding?(str) %x{ try { validating_decoder(self, 'euc-jp').decode(new Uint8Array(str.$bytes())); } catch { return false; } return true; } end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding/tables/jis_inverted.rb
opal/corelib/string/encoding/tables/jis_inverted.rb
# backtick_javascript: true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
true
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding/tables/jis_ext_inverted.rb
opal/corelib/string/encoding/tables/jis_ext_inverted.rb
# backtick_javascript: true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
true
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/string/encoding/tables/sjis_inverted.rb
opal/corelib/string/encoding/tables/sjis_inverted.rb
# backtick_javascript: true
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
true
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/process/base.rb
opal/corelib/process/base.rb
class ::Signal def self.trap(*) end end class ::GC def self.start end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/process/status.rb
opal/corelib/process/status.rb
module ::Process class Status def initialize(status, pid) @status, @pid = status, pid end def exitstatus @status end attr_reader :pid def success? @status == 0 end def inspect "#<Process::Status: pid #{@pid} exit #{@status}>" end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/error/errno.rb
opal/corelib/error/errno.rb
# backtick_javascript: true # use_strict: true module ::Errno errors = [ [:EINVAL, 'Invalid argument', 22], [:EEXIST, 'File exists', 17], [:EISDIR, 'Is a directory', 21], [:EMFILE, 'Too many open files', 24], [:ESPIPE, 'Illegal seek', 29], [:EACCES, 'Permission denied', 13], [:EPERM, 'Operation not permitted', 1], [:ENOENT, 'No such file or directory', 2], [:ENAMETOOLONG, 'File name too long', 36] ] klass = nil %x{ var i; for (i = 0; i < errors.length; i++) { (function() { // Create a closure var class_name = errors[i][0]; var default_message = errors[i][1]; var errno = errors[i][2]; klass = Opal.klass(self, Opal.SystemCallError, class_name); klass.errno = errno; #{ class << klass def new(name = nil) message = `default_message` message += " - #{name}" if name super(message) end end } })(); } } end class ::SystemCallError < ::StandardError def errno self.class.errno end class << self attr_reader :errno end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/math/polyfills.rb
opal/corelib/math/polyfills.rb
# backtick_javascript: true # Polyfills for browsers in the age of IE11 unless defined?(`Math.acosh`) %x{ Math.acosh = function(x) { return Math.log(x + Math.sqrt(x * x - 1)); } } end unless defined?(`Math.asinh`) %x{ Math.asinh = function(x) { return Math.log(x + Math.sqrt(x * x + 1)) } } end unless defined?(`Math.atanh`) %x{ Math.atanh = function(x) { return 0.5 * Math.log((1 + x) / (1 - x)); } } end unless defined?(`Math.cbrt`) %x{ Math.cbrt = function(x) { if (x == 0) { return 0; } if (x < 0) { return -Math.cbrt(-x); } var r = x, ex = 0; while (r < 0.125) { r *= 8; ex--; } while (r > 1.0) { r *= 0.125; ex++; } r = (-0.46946116 * r + 1.072302) * r + 0.3812513; while (ex < 0) { r *= 0.5; ex++; } while (ex > 0) { r *= 2; ex--; } r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r); r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r); r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r); r = (2.0 / 3.0) * r + (1.0 / 3.0) * x / (r * r); return r; } } end unless defined?(`Math.cosh`) %x{ Math.cosh = function(x) { return (Math.exp(x) + Math.exp(-x)) / 2; } } end unless defined?(`Math.hypot`) %x{ Math.hypot = function(x, y) { return Math.sqrt(x * x + y * y) } } end unless defined?(`Math.log2`) %x{ Math.log2 = function(x) { return Math.log(x) / Math.LN2; } } end unless defined?(`Math.log10`) %x{ Math.log10 = function(x) { return Math.log(x) / Math.LN10; } } end unless defined?(`Math.sinh`) %x{ Math.sinh = function(x) { return (Math.exp(x) - Math.exp(-x)) / 2; } } end unless defined?(`Math.tanh`) %x{ Math.tanh = function(x) { if (x == Infinity) { return 1; } else if (x == -Infinity) { return -1; } else { return (Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x)); } } } end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/kernel/format.rb
opal/corelib/kernel/format.rb
# helpers: coerce_to # backtick_javascript: true module ::Kernel def format(format_string, *args) if args.length == 1 && args[0].respond_to?(:to_ary) ary = ::Opal.coerce_to?(args[0], ::Array, :to_ary) args = ary.to_a unless ary.nil? end %x{ var result = '', //used for slicing: begin_slice = 0, end_slice, //used for iterating over the format string: i, len = format_string.length, //used for processing field values: arg, str, //used for processing %g and %G fields: exponent, //used for keeping track of width and precision: width, precision, //used for holding temporary values: tmp_num, //used for processing %{} and %<> fileds: hash_parameter_key, closing_brace_char, //used for processing %b, %B, %o, %x, and %X fields: base_number, base_prefix, base_neg_zero_regex, base_neg_zero_digit, //used for processing arguments: next_arg, seq_arg_num = 1, pos_arg_num = 0, //used for keeping track of flags: flags, FNONE = 0, FSHARP = 1, FMINUS = 2, FPLUS = 4, FZERO = 8, FSPACE = 16, FWIDTH = 32, FPREC = 64, FPREC0 = 128; function CHECK_FOR_FLAGS() { if (flags&FWIDTH) { #{::Kernel.raise ::ArgumentError, 'flag after width'} } if (flags&FPREC0) { #{::Kernel.raise ::ArgumentError, 'flag after precision'} } } function CHECK_FOR_WIDTH() { if (flags&FWIDTH) { #{::Kernel.raise ::ArgumentError, 'width given twice'} } if (flags&FPREC0) { #{::Kernel.raise ::ArgumentError, 'width after precision'} } } function GET_NTH_ARG(num) { if (num >= args.length) { #{::Kernel.raise ::ArgumentError, 'too few arguments'} } return args[num]; } function GET_NEXT_ARG() { switch (pos_arg_num) { case -1: #{::Kernel.raise ::ArgumentError, "unnumbered(#{`seq_arg_num`}) mixed with numbered"} // raise case -2: #{::Kernel.raise ::ArgumentError, "unnumbered(#{`seq_arg_num`}) mixed with named"} // raise } pos_arg_num = seq_arg_num++; return GET_NTH_ARG(pos_arg_num - 1); } function GET_POS_ARG(num) { if (pos_arg_num > 0) { #{::Kernel.raise ::ArgumentError, "numbered(#{`num`}) after unnumbered(#{`pos_arg_num`})"} } if (pos_arg_num === -2) { #{::Kernel.raise ::ArgumentError, "numbered(#{`num`}) after named"} } if (num < 1) { #{::Kernel.raise ::ArgumentError, "invalid index - #{`num`}$"} } pos_arg_num = -1; return GET_NTH_ARG(num - 1); } function GET_ARG() { return (next_arg === undefined ? GET_NEXT_ARG() : next_arg); } function READ_NUM(label) { var num, str = ''; for (;; i++) { if (i === len) { #{::Kernel.raise ::ArgumentError, 'malformed format string - %*[0-9]'} } if (format_string.charCodeAt(i) < 48 || format_string.charCodeAt(i) > 57) { i--; num = parseInt(str, 10) || 0; if (num > 2147483647) { #{::Kernel.raise ::ArgumentError, "#{`label`} too big"} } return num; } str += format_string.charAt(i); } } function READ_NUM_AFTER_ASTER(label) { var arg, num = READ_NUM(label); if (format_string.charAt(i + 1) === '$') { i++; arg = GET_POS_ARG(num); } else { arg = GET_NEXT_ARG(); } return #{`arg`.to_int}; } for (i = format_string.indexOf('%'); i !== -1; i = format_string.indexOf('%', i)) { str = undefined; flags = FNONE; width = -1; precision = -1; next_arg = undefined; end_slice = i; i++; switch (format_string.charAt(i)) { case '%': begin_slice = i; // no-break case '': case '\n': case '\0': i++; continue; } format_sequence: for (; i < len; i++) { switch (format_string.charAt(i)) { case ' ': CHECK_FOR_FLAGS(); flags |= FSPACE; continue format_sequence; case '#': CHECK_FOR_FLAGS(); flags |= FSHARP; continue format_sequence; case '+': CHECK_FOR_FLAGS(); flags |= FPLUS; continue format_sequence; case '-': CHECK_FOR_FLAGS(); flags |= FMINUS; continue format_sequence; case '0': CHECK_FOR_FLAGS(); flags |= FZERO; continue format_sequence; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tmp_num = READ_NUM('width'); if (format_string.charAt(i + 1) === '$') { if (i + 2 === len) { str = '%'; i++; break format_sequence; } if (next_arg !== undefined) { #{::Kernel.raise ::ArgumentError, "value given twice - %#{`tmp_num`}$"} } next_arg = GET_POS_ARG(tmp_num); i++; } else { CHECK_FOR_WIDTH(); flags |= FWIDTH; width = tmp_num; } continue format_sequence; case '<': case '\{': closing_brace_char = (format_string.charAt(i) === '<' ? '>' : '\}'); hash_parameter_key = ''; i++; for (;; i++) { if (i === len) { #{::Kernel.raise ::ArgumentError, 'malformed name - unmatched parenthesis'} } if (format_string.charAt(i) === closing_brace_char) { if (pos_arg_num > 0) { #{::Kernel.raise ::ArgumentError, "named #{`hash_parameter_key`} after unnumbered(#{`pos_arg_num`})"} } if (pos_arg_num === -1) { #{::Kernel.raise ::ArgumentError, "named #{`hash_parameter_key`} after numbered"} } pos_arg_num = -2; if (args[0] === undefined || !args[0].$$is_hash) { #{::Kernel.raise ::ArgumentError, 'one hash required'} } next_arg = #{`args[0]`.fetch(`hash_parameter_key`)}; if (closing_brace_char === '>') { continue format_sequence; } else { str = next_arg.toString(); if (precision !== -1) { str = str.slice(0, precision); } if (flags&FMINUS) { while (str.length < width) { str = str + ' '; } } else { while (str.length < width) { str = ' ' + str; } } break format_sequence; } } hash_parameter_key += format_string.charAt(i); } // raise case '*': i++; CHECK_FOR_WIDTH(); flags |= FWIDTH; width = READ_NUM_AFTER_ASTER('width'); if (width < 0) { flags |= FMINUS; width = -width; } continue format_sequence; case '.': if (flags&FPREC0) { #{::Kernel.raise ::ArgumentError, 'precision given twice'} } flags |= FPREC|FPREC0; precision = 0; i++; if (format_string.charAt(i) === '*') { i++; precision = READ_NUM_AFTER_ASTER('precision'); if (precision < 0) { flags &= ~FPREC; } continue format_sequence; } precision = READ_NUM('precision'); continue format_sequence; case 'd': case 'i': case 'u': arg = #{::Kernel.Integer(`GET_ARG()`)}; if (arg >= 0) { str = arg.toString(); while (str.length < precision) { str = '0' + str; } if (flags&FMINUS) { if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } while (str.length < width) { str = str + ' '; } } else { if (flags&FZERO && precision === -1) { while (str.length < width - ((flags&FPLUS || flags&FSPACE) ? 1 : 0)) { str = '0' + str; } if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } } else { if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } while (str.length < width) { str = ' ' + str; } } } } else { str = (-arg).toString(); while (str.length < precision) { str = '0' + str; } if (flags&FMINUS) { str = '-' + str; while (str.length < width) { str = str + ' '; } } else { if (flags&FZERO && precision === -1) { while (str.length < width - 1) { str = '0' + str; } str = '-' + str; } else { str = '-' + str; while (str.length < width) { str = ' ' + str; } } } } break format_sequence; case 'b': case 'B': case 'o': case 'x': case 'X': switch (format_string.charAt(i)) { case 'b': case 'B': base_number = 2; base_prefix = '0b'; base_neg_zero_regex = /^1+/; base_neg_zero_digit = '1'; break; case 'o': base_number = 8; base_prefix = '0'; base_neg_zero_regex = /^3?7+/; base_neg_zero_digit = '7'; break; case 'x': case 'X': base_number = 16; base_prefix = '0x'; base_neg_zero_regex = /^f+/; base_neg_zero_digit = 'f'; break; } arg = #{::Kernel.Integer(`GET_ARG()`)}; if (arg >= 0) { str = arg.toString(base_number); while (str.length < precision) { str = '0' + str; } if (flags&FMINUS) { if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } if (flags&FSHARP && arg !== 0) { str = base_prefix + str; } while (str.length < width) { str = str + ' '; } } else { if (flags&FZERO && precision === -1) { while (str.length < width - ((flags&FPLUS || flags&FSPACE) ? 1 : 0) - ((flags&FSHARP && arg !== 0) ? base_prefix.length : 0)) { str = '0' + str; } if (flags&FSHARP && arg !== 0) { str = base_prefix + str; } if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } } else { if (flags&FSHARP && arg !== 0) { str = base_prefix + str; } if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } while (str.length < width) { str = ' ' + str; } } } } else { if (flags&FPLUS || flags&FSPACE) { str = (-arg).toString(base_number); while (str.length < precision) { str = '0' + str; } if (flags&FMINUS) { if (flags&FSHARP) { str = base_prefix + str; } str = '-' + str; while (str.length < width) { str = str + ' '; } } else { if (flags&FZERO && precision === -1) { while (str.length < width - 1 - (flags&FSHARP ? 2 : 0)) { str = '0' + str; } if (flags&FSHARP) { str = base_prefix + str; } str = '-' + str; } else { if (flags&FSHARP) { str = base_prefix + str; } str = '-' + str; while (str.length < width) { str = ' ' + str; } } } } else { str = (arg >>> 0).toString(base_number).replace(base_neg_zero_regex, base_neg_zero_digit); while (str.length < precision - 2) { str = base_neg_zero_digit + str; } if (flags&FMINUS) { str = '..' + str; if (flags&FSHARP) { str = base_prefix + str; } while (str.length < width) { str = str + ' '; } } else { if (flags&FZERO && precision === -1) { while (str.length < width - 2 - (flags&FSHARP ? base_prefix.length : 0)) { str = base_neg_zero_digit + str; } str = '..' + str; if (flags&FSHARP) { str = base_prefix + str; } } else { str = '..' + str; if (flags&FSHARP) { str = base_prefix + str; } while (str.length < width) { str = ' ' + str; } } } } } if (format_string.charAt(i) === format_string.charAt(i).toUpperCase()) { str = str.toUpperCase(); } break format_sequence; case 'f': case 'e': case 'E': case 'g': case 'G': arg = #{::Kernel.Float(`GET_ARG()`)}; if (arg >= 0 || isNaN(arg)) { if (arg === Infinity) { str = 'Inf'; } else { switch (format_string.charAt(i)) { case 'f': str = arg.toFixed(precision === -1 ? 6 : precision); break; case 'e': case 'E': str = arg.toExponential(precision === -1 ? 6 : precision); break; case 'g': case 'G': str = arg.toExponential(); exponent = parseInt(str.split('e')[1], 10); if (!(exponent < -4 || exponent >= (precision === -1 ? 6 : precision))) { str = arg.toPrecision(precision === -1 ? (flags&FSHARP ? 6 : undefined) : precision); } break; } } if (flags&FMINUS) { if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } while (str.length < width) { str = str + ' '; } } else { if (flags&FZERO && arg !== Infinity && !isNaN(arg)) { while (str.length < width - ((flags&FPLUS || flags&FSPACE) ? 1 : 0)) { str = '0' + str; } if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } } else { if (flags&FPLUS || flags&FSPACE) { str = (flags&FPLUS ? '+' : ' ') + str; } while (str.length < width) { str = ' ' + str; } } } } else { if (arg === -Infinity) { str = 'Inf'; } else { switch (format_string.charAt(i)) { case 'f': str = (-arg).toFixed(precision === -1 ? 6 : precision); break; case 'e': case 'E': str = (-arg).toExponential(precision === -1 ? 6 : precision); break; case 'g': case 'G': str = (-arg).toExponential(); exponent = parseInt(str.split('e')[1], 10); if (!(exponent < -4 || exponent >= (precision === -1 ? 6 : precision))) { str = (-arg).toPrecision(precision === -1 ? (flags&FSHARP ? 6 : undefined) : precision); } break; } } if (flags&FMINUS) { str = '-' + str; while (str.length < width) { str = str + ' '; } } else { if (flags&FZERO && arg !== -Infinity) { while (str.length < width - 1) { str = '0' + str; } str = '-' + str; } else { str = '-' + str; while (str.length < width) { str = ' ' + str; } } } } if (format_string.charAt(i) === format_string.charAt(i).toUpperCase() && arg !== Infinity && arg !== -Infinity && !isNaN(arg)) { str = str.toUpperCase(); } str = str.replace(/([eE][-+]?)([0-9])$/, '$10$2'); break format_sequence; case 'a': case 'A': // Not implemented because there are no specs for this field type. #{::Kernel.raise ::NotImplementedError, '`A` and `a` format field types are not implemented in Opal yet'} // raise case 'c': arg = GET_ARG(); if (#{`arg`.respond_to?(:to_ary)}) { arg = #{`arg`.to_ary}[0]; } if (#{`arg`.respond_to?(:to_str)}) { str = #{`arg`.to_str}; } else { str = String.fromCharCode($coerce_to(arg, #{::Integer}, 'to_int')); } if (str.length !== 1) { #{::Kernel.raise ::ArgumentError, '%c requires a character'} } if (flags&FMINUS) { while (str.length < width) { str = str + ' '; } } else { while (str.length < width) { str = ' ' + str; } } break format_sequence; case 'p': str = #{`GET_ARG()`.inspect}; if (precision !== -1) { str = str.slice(0, precision); } if (flags&FMINUS) { while (str.length < width) { str = str + ' '; } } else { while (str.length < width) { str = ' ' + str; } } break format_sequence; case 's': str = #{`GET_ARG()`.to_s}; if (precision !== -1) { str = str.slice(0, precision); } if (flags&FMINUS) { while (str.length < width) { str = str + ' '; } } else { while (str.length < width) { str = ' ' + str; } } break format_sequence; default: #{::Kernel.raise ::ArgumentError, "malformed format string - %#{`format_string.charAt(i)`}"} } } if (str === undefined) { #{::Kernel.raise ::ArgumentError, 'malformed format string - %'} } result += format_string.slice(begin_slice, end_slice) + str; begin_slice = i + 1; } if (#{$DEBUG} && pos_arg_num >= 0 && seq_arg_num < args.length) { #{::Kernel.raise ::ArgumentError, 'too many arguments for format string'} } return result + format_string.slice(begin_slice); } end alias sprintf format end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/enumerator/chain.rb
opal/corelib/enumerator/chain.rb
# helpers: deny_frozen_access # backtick_javascript: true # use_strict: true class ::Enumerator class self::Chain < self def initialize(*enums) `$deny_frozen_access(self)` @enums = enums @iterated = [] @object = self end def each(*args, &block) return to_enum(:each, *args) { size } unless block_given? @enums.each do |enum| @iterated << enum enum.each(*args, &block) end self end def size(*args) accum = 0 @enums.each do |enum| size = enum.size(*args) return size if [nil, ::Float::INFINITY].include? size accum += size end accum end def rewind @iterated.reverse_each do |enum| enum.rewind if enum.respond_to? :rewind end @iterated = [] self end def inspect "#<Enumerator::Chain: #{@enums.inspect}>" end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/enumerator/lazy.rb
opal/corelib/enumerator/lazy.rb
# helpers: truthy, coerce_to, yield1, yieldX, deny_frozen_access # backtick_javascript: true # use_strict: true class ::Enumerator class self::Lazy < self class self::StopLazyError < ::Exception; end def self.for(object, *) lazy = super `lazy.enumerator = object` lazy end def initialize(object, size = nil, &block) `$deny_frozen_access(self)` unless block_given? ::Kernel.raise ::ArgumentError, 'tried to call lazy new without a block' end @enumerator = object super size do |yielder, *each_args| object.each(*each_args) do |*args| %x{ args.unshift(#{yielder}); $yieldX(block, args); } end rescue StopLazyError nil end end def lazy self end def collect(&block) unless block ::Kernel.raise ::ArgumentError, 'tried to call lazy map without a block' end Lazy.new(self, enumerator_size) do |enum, *args| %x{ var value = $yieldX(block, args); #{enum.yield `value`}; } end end def collect_concat(&block) unless block ::Kernel.raise ::ArgumentError, 'tried to call lazy map without a block' end Lazy.new(self, nil) do |enum, *args| %x{ var value = $yieldX(block, args); if (#{`value`.respond_to? :force} && #{`value`.respond_to? :each}) { #{`value`.each { |v| enum.yield v }} } else { var array = #{::Opal.try_convert `value`, ::Array, :to_ary}; if (array === nil) { #{enum.yield `value`}; } else { #{`value`.each { |v| enum.yield v }}; } } } end end def drop(n) n = `$coerce_to(#{n}, #{::Integer}, 'to_int')` if n < 0 ::Kernel.raise ::ArgumentError, 'attempt to drop negative size' end current_size = enumerator_size set_size = if ::Integer === current_size n < current_size ? n : current_size else current_size end dropped = 0 Lazy.new(self, set_size) do |enum, *args| if dropped < n dropped += 1 else enum.yield(*args) end end end def drop_while(&block) unless block ::Kernel.raise ::ArgumentError, 'tried to call lazy drop_while without a block' end succeeding = true Lazy.new(self, nil) do |enum, *args| if succeeding %x{ var value = $yieldX(block, args); if (!$truthy(value)) { succeeding = false; #{enum.yield(*args)}; } } else enum.yield(*args) end end end def enum_for(method = :each, *args, &block) self.class.for(self, method, *args, &block) end def find_all(&block) unless block ::Kernel.raise ::ArgumentError, 'tried to call lazy select without a block' end Lazy.new(self, nil) do |enum, *args| %x{ var value = $yieldX(block, args); if ($truthy(value)) { #{enum.yield(*args)}; } } end end def grep(pattern, &block) if block Lazy.new(self, nil) do |enum, *args| %x{ var param = #{::Opal.destructure(args)}, value = #{pattern === `param`}; if ($truthy(value)) { value = $yield1(block, param); #{enum.yield `$yield1(block, param)`}; } } end else Lazy.new(self, nil) do |enum, *args| %x{ var param = #{::Opal.destructure(args)}, value = #{pattern === `param`}; if ($truthy(value)) { #{enum.yield `param`}; } } end end end def reject(&block) unless block ::Kernel.raise ::ArgumentError, 'tried to call lazy reject without a block' end Lazy.new(self, nil) do |enum, *args| %x{ var value = $yieldX(block, args); if (!$truthy(value)) { #{enum.yield(*args)}; } } end end def take(n) n = `$coerce_to(#{n}, #{::Integer}, 'to_int')` if n < 0 ::Kernel.raise ::ArgumentError, 'attempt to take negative size' end current_size = enumerator_size set_size = if ::Integer === current_size n < current_size ? n : current_size else current_size end taken = 0 Lazy.new(self, set_size) do |enum, *args| if taken < n enum.yield(*args) taken += 1 else ::Kernel.raise StopLazyError end end end def take_while(&block) unless block ::Kernel.raise ::ArgumentError, 'tried to call lazy take_while without a block' end Lazy.new(self, nil) do |enum, *args| %x{ var value = $yieldX(block, args); if ($truthy(value)) { #{enum.yield(*args)}; } else { #{::Kernel.raise StopLazyError}; } } end end def inspect "#<#{self.class}: #{@enumerator.inspect}>" end alias force to_a alias filter find_all alias flat_map collect_concat alias map collect alias select find_all alias to_enum enum_for end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/enumerator/generator.rb
opal/corelib/enumerator/generator.rb
# helpers: deny_frozen_access # backtick_javascript: true # use_strict: true class Enumerator class Generator include ::Enumerable def initialize(&block) `$deny_frozen_access(self)` ::Kernel.raise ::LocalJumpError, 'no block given' unless block @block = block end def each(*args, &block) yielder = Yielder.new(&block) %x{ try { args.unshift(#{yielder}); Opal.yieldX(#{@block}, args); } catch (e) { if (e && e.$thrower_type == "breaker") { return e.$v; } else { throw e; } } } self end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/enumerator/arithmetic_sequence.rb
opal/corelib/enumerator/arithmetic_sequence.rb
# backtick_javascript: true # use_strict: true class ::Enumerator class self::ArithmeticSequence < self `Opal.prop(self.$$prototype, '$$is_arithmetic_seq', true)` `var inf = Infinity` # @private def initialize(range, step = undefined, creation_method = :step) @creation_method = creation_method if range.is_a? ::Array @step_arg1, @step_arg2, @topfx, @bypfx = *range @receiver_num = step @step = 1 @range = if @step_arg2 @step = @step_arg2 (@receiver_num..@step_arg1) elsif @step_arg1 (@receiver_num..@step_arg1) else (@receiver_num..nil) end else @skipped_arg = true unless step @range, @step = range, step || 1 end @object = self ::Kernel.raise ArgumentError, "step can't be 0" if @step == 0 unless @step.respond_to? :to_int ::Kernel.raise ArgumentError, "no implicit conversion of #{@step.class} " \ 'into Integer' end end attr_reader :step def begin @range.begin end def end @range.end end def exclude_end? @range.exclude_end? end # @private def _lesser_than_end?(val) end_ = self.end || `inf` if step > 0 exclude_end? ? val < end_ : val <= end_ else exclude_end? ? val > end_ : val >= end_ end end # @private def _greater_than_begin?(val) begin_ = self.begin || -`inf` if step > 0 val > begin_ else val < begin_ end end def first(count = undefined) iter = self.begin || -`inf` return _lesser_than_end?(iter) ? iter : nil unless count out = [] while _lesser_than_end?(iter) && count > 0 out << iter iter += step count -= 1 end out end def each(&block) return self unless block_given? case self.begin when nil ::Kernel.raise TypeError, "nil can't be coerced into Integer" end iter = self.begin || -`inf` while _lesser_than_end?(iter) yield iter iter += step end self end def last(count = undefined) case self.end when `inf`, -`inf` ::Kernel.raise ::FloatDomainError, self.end when nil ::Kernel.raise ::RangeError, 'cannot get the last element of endless arithmetic sequence' end iter = self.end - ((self.end - self.begin) % step) iter -= step unless _lesser_than_end?(iter) return _greater_than_begin?(iter) ? iter : nil unless count out = [] while _greater_than_begin?(iter) && count > 0 out << iter iter -= step count -= 1 end out.reverse end def size step_sign = step > 0 ? 1 : -1 if !_lesser_than_end?(self.begin) 0 elsif [-`inf`, `inf`].include?(step) 1 elsif [-`inf` * step_sign, nil].include?(self.begin) || [`inf` * step_sign, nil].include?(self.end) `inf` else iter = self.end - ((self.end - self.begin) % step) iter -= step unless _lesser_than_end?(iter) ((iter - self.begin) / step).abs.to_i + 1 end end def ==(other) self.class == other.class && self.begin == other.begin && self.end == other.end && step == other.step && exclude_end? == other.exclude_end? end def hash [ArithmeticSequence, self.begin, self.end, step, exclude_end?].hash end def inspect if @receiver_num args = if @step_arg2 "(#{@topfx}#{@step_arg1.inspect}, #{@bypfx}#{@step_arg2.inspect})" elsif @step_arg1 "(#{@topfx}#{@step_arg1.inspect})" end "(#{@receiver_num.inspect}.#{@creation_method}#{args})" else args = unless @skipped_arg "(#{@step})" end "((#{@range.inspect}).#{@creation_method}#{args})" end end alias === == alias eql? == end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/enumerator/yielder.rb
opal/corelib/enumerator/yielder.rb
# backtick_javascript: true # use_strict: true class Enumerator class Yielder def initialize(&block) @block = block # rubocop:disable Lint/Void self # rubocop:enable Lint/Void end def yield(*values) %x{ var value = Opal.yieldX(#{@block}, values); if (value && value.$thrower_type == "break") { throw value; } return value; } end def <<(value) self.yield(value) self end def to_proc proc do |*values| self.yield(*values) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/pattern_matching/base.rb
opal/corelib/pattern_matching/base.rb
class ::Array def deconstruct self end end class ::Hash def deconstruct_keys(_) self end end class ::Struct alias deconstruct to_a # This function is specified in a very weird way... def deconstruct_keys(keys) return to_h if keys.nil? ::Kernel.raise ::TypeError, 'expected Array or nil' unless ::Array === keys return {} if keys.length > values.length out = {} keys.each do |key| should_break = case key when ::Integer values.length < key when ::Symbol # Or String? Doesn't matter, we're in Opal. !members.include?(key) end break if should_break out[key] = self[key] end out end end class ::NoMatchingPatternError < ::StandardError; end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/complex/base.rb
opal/corelib/complex/base.rb
module ::Kernel def Complex(real, imag = nil) if imag Complex.new(real, imag) else Complex.new(real, 0) end end end class ::String def to_c Complex.from_string(self) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/marshal/read_buffer.rb
opal/corelib/marshal/read_buffer.rb
# backtick_javascript: true # https://github.com/ruby/ruby/blob/trunk/doc/marshal.rdoc # https://github.com/ruby/ruby/blob/trunk/marshal.c module ::Marshal class self::ReadBuffer %x{ function stringToBytes(string) { var i, singleByte, l = string.length, result = []; for (i = 0; i < l; i++) { singleByte = string.charCodeAt(i); result.push(singleByte); } return result; } } attr_reader :version, :buffer, :index, :object_cache, :symbols_cache def initialize(input) @buffer = `stringToBytes(#{input.to_s})` @index = 0 major = read_byte minor = read_byte if major != MAJOR_VERSION || minor != MINOR_VERSION ::Kernel.raise ::TypeError, "incompatible marshal file format (can't be read)" end @version = "#{major}.#{minor}" @object_cache = [] @symbols_cache = [] @ivars = [] end def length @buffer.length end def read(cache: true) code = read_char # The first character indicates the type of the object case code when '0' nil when 'T' true when 'F' false when 'i' read_fixnum when 'f' read_float when 'l' read_bignum when '"' read_string when ':' read_symbol when ';' read_cached_symbol when '[' read_array when '{' read_hash when '}' read_hashdef when '/' read_regexp when 'S' read_struct when 'c' read_class when 'm' read_module when 'o' read_object when '@' read_cached_object when 'e' read_extended_object when 'I' read_primitive_with_ivars when 'C' read_user_class when 'u' read_user_defined when 'U' read_user_marshal when 'M' ::Kernel.raise ::NotImplementedError, 'ModuleOld type cannot be demarshaled yet' # read_module_old when 'd' ::Kernel.raise ::NotImplementedError, 'Data type cannot be demarshaled' else ::Kernel.raise ::ArgumentError, 'dump format error' end end def read_byte if @index >= length ::Kernel.raise ::ArgumentError, 'marshal data too short' end result = @buffer[@index] @index += 1 result end def read_char `String.fromCharCode(#{read_byte})` end # Reads and returns a fixnum from an input stream # def read_fixnum %x{ var x, i, c = (#{read_byte} ^ 128) - 128; if (c === 0) { return 0; } if (c > 0) { if (4 < c && c < 128) { return c - 5; } x = 0; for (i = 0; i < c; i++) { x |= (#{read_byte} << (8*i)); } } else { if (-129 < c && c < -4) { return c + 5; } c = -c; x = -1; for (i = 0; i < c; i++) { x &= ~(0xff << (8*i)); x |= (#{read_byte} << (8*i)); } } return x; } end # Reads and returns Float from an input stream # # @example # 123.456 # Is encoded as # 'f', '123.456' # def read_float s = read_string(cache: false) result = if s == 'nan' 0.0 / 0 elsif s == 'inf' 1.0 / 0 elsif s == '-inf' -1.0 / 0 else s.to_f end @object_cache << result result end # Reads and returns Bignum from an input stream # def read_bignum sign = read_char == '-' ? -1 : 1 size = read_fixnum * 2 result = 0 (0...size).each do |exp| result += read_char.ord * 2**(exp * 8) end result = result.to_i * sign @object_cache << result result end # Reads and returns a string from an input stream # Sometimes string shouldn't be cached using # an internal object cache, for a: # + class/module name # + string representation of float # + string representation of regexp # def read_string(cache: true) length = read_fixnum %x{ var i, result = ''; for (i = 0; i < length; i++) { result += #{read_char}; } if (cache) { self.object_cache.push(result); } return result; } end # Reads and returns a symbol from an input stream # def read_symbol length = read_fixnum %x{ var i, result = ''; for (i = 0; i < length; i++) { result += #{read_char}; } self.symbols_cache.push(result); return result; } end # Reads a symbol that was previously cache by its link # # @example # [:a, :a, :b, :b, :c, :c] # Is encoded as # '[', 6, :a, @0, :b, @1, :c, @2 # def read_cached_symbol symbols_cache[read_fixnum] end # Reads and returns an array from an input stream # # @example # [100, 200, 300] # is encoded as # '[', 3, 100, 200, 300 # def read_array result = [] @object_cache << result length = read_fixnum %x{ if (length > 0) { while (result.length < length) { result.push(#{read}); } } return result; } end # Reads and returns a hash from an input stream # Sometimes hash shouldn't be cached using # an internal object cache, for a: # + hash of instance variables # + hash of struct attributes # # @example # {100 => 200, 300 => 400} # is encoded as # '{', 2, 100, 200, 300, 400 # def read_hash(cache: true) result = {} if cache @object_cache << result end length = read_fixnum %x{ if (length > 0) { var key, value, i; for (i = 0; i < #{length}; i++) { key = #{read}; value = #{read}; #{result[`key`] = `value`}; } } return result; } end # Reads and returns a hash with default value # # @example # Hash.new(:default).merge(100 => 200) # is encoded as # '}', 1, 100, 200, :default # def read_hashdef hash = read_hash default_value = read hash.default = default_value hash end # Reads and returns Regexp from an input stream # # @example # r = /regexp/mix # is encoded as # '/', 'regexp', r.options.chr # def read_regexp string = read_string(cache: false) options = read_byte result = ::Regexp.new(string, options) @object_cache << result result end # Reads and returns a Struct from an input stream # # @example # Point = Struct.new(:x, :y) # Point.new(100, 200) # is encoded as # 'S', :Point, {:x => 100, :y => 200} # def read_struct klass_name = read(cache: false) klass = safe_const_get(klass_name) attributes = read_hash(cache: false) args = attributes.values_at(*klass.members) result = klass.new(*args) @object_cache << result result end # Reads and returns a Class from an input stream # # @example # String # is encoded as # 'c', 'String' # def read_class klass_name = read_string(cache: false) result = safe_const_get(klass_name) unless result.class == ::Class ::Kernel.raise ::ArgumentError, "#{klass_name} does not refer to a Class" end @object_cache << result result end # Reads and returns a Module from an input stream # # @example # Kernel # is encoded as # 'm', 'Kernel' # def read_module mod_name = read_string(cache: false) result = safe_const_get(mod_name) unless result.class == ::Module ::Kernel.raise ::ArgumentError, "#{mod_name} does not refer to a Module" end @object_cache << result result end # Reads and returns an abstract object from an input stream # # @example # obj = Object.new # obj.instance_variable_set(:@ivar, 100) # obj # is encoded as # 'o', :Object, {:@ivar => 100} # # The only exception is a Range class (and its subclasses) # For some reason in MRI isntances of this class have instance variables # - begin # - end # - excl # without '@' perfix. # def read_object klass_name = read(cache: false) klass = safe_const_get(klass_name) object = klass.allocate @object_cache << object ivars = read_hash(cache: false) ivars.each do |name, value| if name[0] == '@' object.instance_variable_set(name, value) else # MRI allows an object to have ivars that do not start from '@' # https://github.com/ruby/ruby/blob/ab3a40c1031ff3a0535f6bcf26de40de37dbb1db/range.c#L1225 `object[name] = value` end end object end # Reads an object that was cached previously by its link # # @example # obj1 = Object.new # obj2 = Object.new # obj3 = Object.new # [obj1, obj1, obj2, obj2, obj3, obj3] # is encoded as # [obj1, @1, obj2, @2, obj3, @3] # # NOTE: array itself is cached as @0, that's why obj1 is cached a @1, obj2 is @2, etc. # def read_cached_object object_cache[read_fixnum] end # Reads an object that was dynamically extended before marshaling like # # @example # M1 = Module.new # M2 = Module.new # obj = Object.new # obj.extend(M1) # obj.extend(M2) # obj # is encoded as # 'e', :M2, :M1, obj # def read_extended_object mod = safe_const_get(read) object = read object.extend(mod) object end # Reads a primitive object with instance variables # (classes that have their own marshalling rules, like Array/Hash/Regexp/etc) # # @example # arr = [100, 200, 300] # arr.instance_variable_set(:@ivar, :value) # arr # is encoded as # 'I', [100, 200, 300], {:@ivar => value} # def read_primitive_with_ivars object = read primitive_ivars = read_hash(cache: false) if primitive_ivars.any? && object.is_a?(String) object = `Opal.str(object)` end primitive_ivars.each do |name, value| if name != 'E' object.instance_variable_set(name, value) end end object end # Reads and User Class (instance of String/Regexp/Array/Hash subclass) # # @example # UserArray = Class.new(Array) # UserArray[100, 200, 300] # is encoded as # 'C', :UserArray, [100, 200, 300] # def read_user_class klass_name = read(cache: false) klass = safe_const_get(klass_name) value = read(cache: false) result = if klass < Hash klass[value] else klass.new(value) end @object_cache << result result end # Reads a 'User Defined' object that has '_dump/self._load' methods # # @example # class UserDefined # def _dump(level) # '_dumped' # end # end # # UserDefined.new # is encoded as # 'u', :UserDefined, '_dumped' # # To load it back UserDefined._load' must be used. # def read_user_defined klass_name = read(cache: false) klass = safe_const_get(klass_name) data = read_string(cache: false) result = klass._load(data) @object_cache << result result end # Reads a 'User Marshal' object that has 'marshal_dump/marshal_load' methods # # @example # class UserMarshal < Struct.new(:a, :b) # def marshal_dump # [a, b] # end # # def marshal_load(data) # self.a, self.b = data # end # end # # UserMarshal.new(100, 200) # is encoded as # 'U', :UserMarshal, [100, 200] # # To load it back `UserMarshal.allocate` and `UserMarshal#marshal_load` must be called # def read_user_marshal klass_name = read(cache: false) klass = safe_const_get(klass_name) result = klass.allocate @object_cache << result data = read(cache: false) result.marshal_load(data) result end # Returns a constant by passed const_name, # re-raises Marshal-specific error when it's missing # def safe_const_get(const_name) ::Object.const_get(const_name) rescue ::NameError ::Kernel.raise ::ArgumentError, "undefined class/module #{const_name}" end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/marshal/write_buffer.rb
opal/corelib/marshal/write_buffer.rb
# backtick_javascript: true class ::NilClass def __marshal__(buffer) buffer.append('0') end end class ::Boolean def __marshal__(buffer) if `self == true` buffer.append('T') else buffer.append('F') end end end class ::Integer def __marshal__(buffer) if self >= -0x40000000 && self < 0x40000000 buffer.append('i') buffer.write_fixnum(self) else buffer.append('l') buffer.write_bignum(self) end end end class ::Float def __marshal__(buffer) buffer.save_link(self) buffer.append('f') buffer.write_float(self) end end class ::String def __marshal__(buffer) buffer.save_link(self) buffer.write_ivars_prefix(self) buffer.write_extends(self) buffer.write_user_class(::String, self) buffer.append('"') buffer.write_string(self) end end class ::Array def __marshal__(buffer) buffer.save_link(self) buffer.write_ivars_prefix(self) buffer.write_extends(self) buffer.write_user_class(::Array, self) buffer.append('[') buffer.write_array(self) buffer.write_ivars_suffix(self) end end class ::Hash def __marshal__(buffer) if default_proc ::Kernel.raise ::TypeError, "can't dump hash with default proc" end buffer.save_link(self) buffer.write_ivars_prefix(self) buffer.write_extends(self) buffer.write_user_class(Hash, self) if default buffer.append('}') buffer.write_hash(self) buffer.write(default) else buffer.append('{') buffer.write_hash(self) end buffer.write_ivars_suffix(self) end end class ::Regexp def __marshal__(buffer) buffer.save_link(self) buffer.write_ivars_prefix(self) buffer.write_extends(self) buffer.write_user_class(::Regexp, self) buffer.append('/') buffer.write_regexp(self) buffer.write_ivars_suffix(self) end end class ::Proc def __marshal__(buffer) ::Kernel.raise ::TypeError, "no _dump_data is defined for class #{self.class}" end end class ::Method def __marshal__(buffer) ::Kernel.raise ::TypeError, "no _dump_data is defined for class #{self.class}" end end class ::MatchData def __marshal__(buffer) ::Kernel.raise ::TypeError, "no _dump_data is defined for class #{self.class}" end end class ::Module def __marshal__(buffer) unless name ::Kernel.raise ::TypeError, "can't dump anonymous module" end buffer.save_link(self) buffer.append('m') buffer.write_module(self) end end class ::Class def __marshal__(buffer) unless name ::Kernel.raise ::TypeError, "can't dump anonymous class" end if singleton_class? ::Kernel.raise ::TypeError, "singleton class can't be dumped" end buffer.save_link(self) buffer.append('c') buffer.write_class(self) end end class ::BasicObject def __marshal__(buffer) buffer.save_link(self) buffer.write_extends(self) buffer.append('o') buffer.write_object(self) end end class ::Range def __marshal__(buffer) buffer.save_link(self) buffer.write_extends(self) buffer.append('o') buffer.append_symbol(self.class.name) buffer.write_fixnum(3) buffer.append_symbol('excl') buffer.write(exclude_end?) buffer.append_symbol('begin') buffer.write(self.begin) buffer.append_symbol('end') buffer.write(self.end) end end class ::Struct def __marshal__(buffer) buffer.save_link(self) buffer.write_ivars_prefix(self) buffer.write_extends(self) buffer.append('S') buffer.append_symbol(self.class.name) buffer.write_fixnum(length) each_pair do |attr_name, value| buffer.append_symbol(attr_name) buffer.write(value) end buffer.write_ivars_suffix(self) end end module ::Marshal class self::WriteBuffer attr_reader :buffer def initialize(object) @object = object @buffer = '' @cache = [] @extends = ::Hash.new { |h, k| h[k] = [] } append(version) end def write(object = @object) if idx = @cache.index(object.object_id) write_object_link(idx) elsif object.respond_to?(:marshal_dump) write_usr_marshal(object) elsif object.respond_to?(:_dump) write_userdef(object) else case object when nil, true, false, ::Proc, ::Method, ::MatchData, ::Range, ::Struct, ::Array, ::Class, ::Module, ::Hash, ::Regexp object.__marshal__(self) when ::Integer ::Integer.instance_method(:__marshal__).bind(object).call(self) when ::Float ::Float.instance_method(:__marshal__).bind(object).call(self) when ::String ::String.instance_method(:__marshal__).bind(object).call(self) else ::BasicObject.instance_method(:__marshal__).bind(object).call(self) end end `Opal.str(#{@buffer}, "BINARY")` end def write_fixnum(n) %x{ var s; if (n == 0) { s = String.fromCharCode(n); } else if (n > 0 && n < 123) { s = String.fromCharCode(n + 5); } else if (n < 0 && n > -124) { s = String.fromCharCode(256 + n - 5); } else { s = ""; var cnt = 0; for (var i = 0; i < 4; i++) { var b = n & 255; s += String.fromCharCode(b); n >>= 8 cnt += 1; if (n === 0 || n === -1) { break; } } var l_byte; if (n < 0) { l_byte = 256 - cnt; } else { l_byte = cnt; } s = String.fromCharCode(l_byte) + s; } #{append(`s`)} } end def write_bignum(n) sign = n > 0 ? '+' : '-' append(sign) num = n > 0 ? n : -n arr = [] while num > 0 arr << (num & 0xffff) num = (num / 0x10000).floor end write_fixnum(arr.size) arr.each do |x| append(`String.fromCharCode(x & 0xff)`) append(`String.fromCharCode(#{(x / 0x100).floor})`) end end def write_string(s) write_fixnum(s.length) append(s) end def append_symbol(sym) append(':') write_fixnum(sym.length) append(sym) end def write_array(a) write_fixnum(a.length) a.each do |item| write(item) end end def write_hash(h) write_fixnum(h.length) h.each do |key, value| write(key) write(value) end end def write_object(obj) append_symbol(obj.class.name) write_ivars_suffix(obj, true) end def write_class(klass) write_string(klass.name) end def write_module(mod) write_string(mod.name) end def write_regexp(regexp) write_string(regexp.to_s) append(`String.fromCharCode(#{regexp.options})`) end def write_float(f) if f.equal?(::Float::INFINITY) write_string('inf') elsif f.equal?(-::Float::INFINITY) write_string('-inf') elsif f.equal?(::Float::NAN) write_string('nan') else write_string(f.to_s) end end def write_ivars_suffix(object, force = false) if object.instance_variables.empty? && !force return end write_fixnum(object.instance_variables.length) object.instance_variables.each do |ivar_name| append_symbol(ivar_name) write(object.instance_variable_get(ivar_name)) end end def write_extends(object) singleton_mods = object.singleton_class.ancestors.reject { |mod| mod.is_a?(Class) } class_mods = object.class.ancestors.reject { |mod| mod.is_a?(Class) } own_mods = singleton_mods - class_mods unless own_mods.empty? own_mods.each do |mod| append('e') append_symbol(mod.name) end end end def write_user_class(klass, object) unless object.class.equal?(klass) append('C') append_symbol(object.class.name) end end def write_object_link(idx) append('@') write_fixnum(idx) end def save_link(object) @cache << object.object_id end def write_usr_marshal(object) value = object.marshal_dump klass = object.class append('U') namespace = `#{klass}.$$base_module` if namespace.equal?(::Object) append_symbol(`#{klass}.$$name`) else append_symbol(namespace.name + '::' + `#{klass}.$$name`) end write(value) end def write_userdef(object) value = object._dump(0) unless value.is_a?(::String) ::Kernel.raise ::TypeError, '_dump() must return string' end write_ivars_prefix(value) append('u') append_symbol(object.class.name) write_string(value) end def write_ivars_prefix(object) unless object.instance_variables.empty? append('I') end end def append(s) `#{@buffer} += #{s}` end def version `String.fromCharCode(#{MAJOR_VERSION}, #{MINOR_VERSION})` end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/array/pack.rb
opal/corelib/array/pack.rb
# helpers: coerce_to # backtick_javascript: true require 'corelib/pack_unpack/format_string_parser' class ::Array %x{ // Format Parser var eachDirectiveAndCount = Opal.PackUnpack.eachDirectiveAndCount; function identityFunction(value) { return value; } function utf8BytesToUtf16LEString(bytes) { var str = String.fromCharCode.apply(null, bytes), out = "", i = 0, len = str.length, c, char2, char3; while (i < len) { c = str.charCodeAt(i++); switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += str.charAt(i - 1); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx10xx xxxx10xx xxxx char2 = str.charCodeAt(i++); char3 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out; } function asciiBytesToUtf16LEString(bytes) { return String.fromCharCode.apply(null, bytes); } function asciiStringFromUnsignedInt(bytes, callback) { return function(data) { var buffer = callback(data); return buffer.map(function(item) { var result = []; for (var i = 0; i < bytes; i++) { var bit = item & 255; result.push(bit); item = item >> 8; }; return asciiBytesToUtf16LEString(result); }); } } function asciiStringFromSignedInt(bytes, callback) { return function(data) { var buffer = callback(data), bits = bytes * 8, limit = Math.pow(2, bits); return buffer.map(function(item) { if (item < 0) { item += limit; } var result = []; for (var i = 0; i < bytes; i++) { var bit = item & 255; result.push(bit); item = item >> 8; }; return asciiBytesToUtf16LEString(result); }); } } function toInt(callback) { return function(data) { var buffer = callback(data); return buffer.map(function(item) { return $coerce_to(item, #{::Integer}, 'to_int') }); } } function ToStr(callback) { return function(data) { var buffer = callback(data); return buffer.map(function(item) { return $coerce_to(item, #{::String}, 'to_str') }); } } function toFloat(callback) { return function(data) { var buffer = callback(data); return buffer.map(function(item) { if (!Opal.is_a(item, Opal.Numeric)) { #{::Kernel.raise ::TypeError, "can't convert Object into Float"}; } return $coerce_to(item, #{::Float}, 'to_f'); }); } } var hostLittleEndian = (function() { var uint32 = new Uint32Array([0x11223344]); return new Uint8Array(uint32.buffer)[0] === 0x44; })(); function asciiStringFromFloat(bytes, little, callback) { return function(data) { var buffer = callback(data); return buffer.map(function(item) { var arr = new ArrayBuffer(bytes); var view = new DataView(arr); if (bytes === 4) { view.setFloat32(0, item, little); } else { view.setFloat64(0, item, little); } var uint8 = new Uint8Array(arr); return asciiBytesToUtf16LEString(Array.from(uint8)); }); } } function fromCodePoint(callback) { return function(data) { var buffer = callback(data); return buffer.map(function(item) { try { return String.fromCodePoint(item); } catch (error) { if (error instanceof RangeError) { #{::Kernel.raise ::RangeError, 'value out of range'}; } throw error; } }); } } function joinChars(callback) { return function(data) { var buffer = callback(data); return buffer.join(''); } } var handlers = { // Integer 'C': joinChars(asciiStringFromUnsignedInt(1, toInt(identityFunction))), 'S': joinChars(asciiStringFromUnsignedInt(2, toInt(identityFunction))), 'L': joinChars(asciiStringFromUnsignedInt(4, toInt(identityFunction))), 'Q': joinChars(asciiStringFromUnsignedInt(8, toInt(identityFunction))), 'J': null, 'S>': null, 'L>': null, 'Q>': null, 'c': joinChars(asciiStringFromSignedInt(1, toInt(identityFunction))), 's': joinChars(asciiStringFromSignedInt(2, toInt(identityFunction))), 'l': joinChars(asciiStringFromSignedInt(4, toInt(identityFunction))), 'q': joinChars(asciiStringFromSignedInt(8, toInt(identityFunction))), 'j': null, 's>': null, 'l>': null, 'q>': null, 'n': null, 'N': null, 'v': null, 'V': null, 'U': joinChars(fromCodePoint(toInt(identityFunction))), 'w': null, 'x': function(chunk) { return asciiBytesToUtf16LEString(chunk); }, // Float 'D': joinChars(asciiStringFromFloat(8, hostLittleEndian, toFloat(identityFunction))), 'd': joinChars(asciiStringFromFloat(8, hostLittleEndian, toFloat(identityFunction))), 'F': joinChars(asciiStringFromFloat(4, hostLittleEndian, toFloat(identityFunction))), 'f': joinChars(asciiStringFromFloat(4, hostLittleEndian, toFloat(identityFunction))), 'E': joinChars(asciiStringFromFloat(8, true, toFloat(identityFunction))), 'e': joinChars(asciiStringFromFloat(4, true, toFloat(identityFunction))), 'G': joinChars(asciiStringFromFloat(8, false, toFloat(identityFunction))), 'g': joinChars(asciiStringFromFloat(4, false, toFloat(identityFunction))), // String 'A': joinChars(identityFunction), 'a': joinChars(identityFunction), 'Z': null, 'B': null, 'b': null, 'H': null, 'h': null, 'u': null, 'M': null, 'm': null, 'P': null, 'p': null }; function readNTimesFromBufferAndMerge(callback) { return function(buffer, count) { var chunk = [], chunkData; if (count === Infinity) { while (buffer.length > 0) { chunkData = callback(buffer); buffer = chunkData.rest; chunk = chunk.concat(chunkData.chunk); } } else { if (buffer.length < count) { #{::Kernel.raise ::ArgumentError, 'too few arguments'}; } for (var i = 0; i < count; i++) { chunkData = callback(buffer); buffer = chunkData.rest; chunk = chunk.concat(chunkData.chunk); } } return { chunk: chunk, rest: buffer }; } } function readItem(buffer) { var chunk = buffer.slice(0, 1); buffer = buffer.slice(1, buffer.length); return { chunk: chunk, rest: buffer }; } function readNCharsFromTheFirstItemAndMergeWithFallback(fallback, callback) { return function(buffer, count) { var chunk = [], source = buffer[0]; if (source === nil) { source = ''; } else if (source === undefined) { #{::Kernel.raise ::ArgumentError, 'too few arguments'}; } else { source = $coerce_to(source, #{::String}, 'to_str'); } buffer = buffer.slice(1, buffer.length); function infiniteReeder() { var chunkData = callback(source); source = chunkData.rest; var subChunk = chunkData.chunk; if (subChunk.length === 1 && subChunk[0] === nil) { subChunk = [] } chunk = chunk.concat(subChunk); } function finiteReeder() { var chunkData = callback(source); source = chunkData.rest; var subChunk = chunkData.chunk; if (subChunk.length === 0) { subChunk = [fallback]; } if (subChunk.length === 1 && subChunk[0] === nil) { subChunk = [fallback]; } chunk = chunk.concat(subChunk); } if (count === Infinity) { while (source.length > 0) { infiniteReeder(); } } else { for (var i = 0; i < count; i++) { finiteReeder(); } } return { chunk: chunk, rest: buffer }; } } var readChunk = { // Integer 'C': readNTimesFromBufferAndMerge(readItem), 'S': readNTimesFromBufferAndMerge(readItem), 'L': readNTimesFromBufferAndMerge(readItem), 'Q': readNTimesFromBufferAndMerge(readItem), 'J': null, 'S>': null, 'L>': null, 'Q>': null, 'c': readNTimesFromBufferAndMerge(readItem), 's': readNTimesFromBufferAndMerge(readItem), 'l': readNTimesFromBufferAndMerge(readItem), 'q': readNTimesFromBufferAndMerge(readItem), 'j': null, 's>': null, 'l>': null, 'q>': null, 'n': null, 'N': null, 'v': null, 'V': null, 'U': readNTimesFromBufferAndMerge(readItem), 'w': null, 'x': function(buffer, count) { if (count === Infinity) count = 1; return { chunk: new Array(count).fill(0), rest: buffer }; }, // Float 'D': readNTimesFromBufferAndMerge(readItem), 'd': readNTimesFromBufferAndMerge(readItem), 'F': readNTimesFromBufferAndMerge(readItem), 'f': readNTimesFromBufferAndMerge(readItem), 'E': readNTimesFromBufferAndMerge(readItem), 'e': readNTimesFromBufferAndMerge(readItem), 'G': readNTimesFromBufferAndMerge(readItem), 'g': readNTimesFromBufferAndMerge(readItem), // String 'A': readNCharsFromTheFirstItemAndMergeWithFallback(" ", readItem), 'a': readNCharsFromTheFirstItemAndMergeWithFallback("\x00", readItem), 'Z': null, 'B': null, 'b': null, 'H': null, 'h': null, 'u': null, 'M': null, 'm': null, 'P': null, 'p': null }; var autocompletion = { // Integer 'C': false, 'S': false, 'L': false, 'Q': false, 'J': null, 'S>': null, 'L>': null, 'Q>': null, 'c': false, 's': false, 'l': false, 'q': false, 'j': null, 's>': null, 'l>': null, 'q>': null, 'n': null, 'N': null, 'v': null, 'V': null, 'U': false, 'w': null, 'x': false, // Float 'D': false, 'd': false, 'F': false, 'f': false, 'E': false, 'e': false, 'G': false, 'g': false, // String 'A': false, 'a': false, 'Z': null, 'B': null, 'b': null, 'H': null, 'h': null, 'u': false, 'M': null, 'm': null, 'P': null, 'p': null }; } def pack(format) format = ::Opal.coerce_to!(format, ::String, :to_str) .gsub(/#.*/, '') .gsub(/\s/, '') .delete("\000") %x{ var output = ''; var buffer = self.slice(); function autocomplete(array, size) { while (array.length < size) { array.push(nil); } return array; } function processChunk(directive, count) { var chunk, chunkReader = readChunk[directive]; if (chunkReader == null) { #{::Kernel.raise "Unsupported pack directive #{`directive`.inspect} (no chunk reader defined)"} } var chunkData = chunkReader(buffer, count); chunk = chunkData.chunk; buffer = chunkData.rest; var handler = handlers[directive]; if (handler == null) { #{::Kernel.raise "Unsupported pack directive #{`directive`.inspect} (no handler defined)"} } return handler(chunk); } eachDirectiveAndCount(format, function(directive, count) { var part = processChunk(directive, count); if (count !== Infinity) { var shouldAutocomplete = autocompletion[directive] if (shouldAutocomplete == null) { #{::Kernel.raise "Unsupported pack directive #{`directive`.inspect} (no autocompletion rule defined)"} } if (shouldAutocomplete) { autocomplete(part, count); } } output = output.concat(part); }); if (format.match(/^(U\*?)+$/)) { return output; } else { return Opal.str(output, "binary"); } } end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/rational/base.rb
opal/corelib/rational/base.rb
module ::Kernel def Rational(numerator, denominator = 1) ::Rational.convert(numerator, denominator) end end class ::String def to_r ::Rational.from_string(self) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/io/buffer.rb
opal/corelib/io/buffer.rb
# backtick_javascript: true require 'corelib/string/encoding' class ::IO class Buffer # Types that can be requested from the buffer: # # :U8: unsigned integer, 1 byte # :S8: signed integer, 1 byte # :u16: unsigned integer, 2 bytes, little-endian # :U16: unsigned integer, 2 bytes, big-endian # :s16: signed integer, 2 bytes, little-endian # :S16: signed integer, 2 bytes, big-endian # :u32: unsigned integer, 4 bytes, little-endian # :U32: unsigned integer, 4 bytes, big-endian # :s32: signed integer, 4 bytes, little-endian # :S32: signed integer, 4 bytes, big-endian # :u64: unsigned integer, 8 bytes, little-endian # :U64: unsigned integer, 8 bytes, big-endian # :s64: signed integer, 8 bytes, little-endian # :S64: signed integer, 8 bytes, big-endian # :f32: float, 4 bytes, little-endian # :F32: float, 4 bytes, big-endian # :f64: double, 8 bytes, little-endian # :F64: double, 8 bytes, big-endian include Comparable class AccessError < ::StandardError; end class LockedError < ::StandardError; end DEFAULT_SIZE = 4096 EXTERNAL = 1 INTERNAL = 2 MAPPED = 4 SHARED = 8 LOCKED = 32 PRIVATE = 64 READONLY = 128 %x{ let size_map = new Map() .set('U8', 1).set('S8', 1) .set('u16', 2).set('U16', 2).set('s16', 2).set('S16', 2) .set('u32', 4).set('U32', 4).set('s32', 4).set('S32', 4) .set('u64', 8).set('U64', 8).set('s64', 8).set('S64', 8) .set('f16', 2).set('F16', 2) .set('f32', 4).set('F32', 4) .set('f64', 8).set('F64', 8); let fun_map = new Map() .set('U8', 'Uint8').set('S8', 'Int8') .set('u16', 'Uint16').set('U16', 'Uint16').set('s16', 'Int16').set('S16', 'Int16') .set('u32', 'Uint32').set('U32', 'Uint32').set('s32', 'Int32').set('S32', 'Int32') .set('u64', 'BigUint64').set('U64', 'BigUint64').set('s64', 'BigInt64').set('S64', 'BigInt64') .set('f16', 'Float16').set('F16', 'Float16') .set('f32', 'Float32').set('F32', 'Float32') .set('f64', 'Float64').set('F64', 'Float64'); function is_le(buffer_type_s) { let c = buffer_type_s[0]; return (c === 'u' || c === 's' || c === 'f') ? true : false; } function op_not(source, target, length) { for(let i = 0; i < length;) { if ((length - i) > 4) { target.data_view.setUint32(i, ~source.data_view.getUint32(i)); i += 4; } else { target.data_view.setUint8(i, ~source.data_view.getUint8(i)); i++; } } } function op_and(source, target, length, mask) { let mask_length = mask.data_view.byteLength, m = 0; for(let i = 0; i < length; i++) { target.data_view.setUint8(i, source.data_view.getUint8(i) & mask.data_view.getUint8(m)); m++; if (m >= mask_length) m = 0; } } function op_or(source, target, length, mask) { let mask_length = mask.data_view.byteLength, m = 0; for(let i = 0; i < length; i++) { target.data_view.setUint8(i, source.data_view.getUint8(i) | mask.data_view.getUint8(m)); m++; if (m >= mask_length) m = 0; } } function op_xor(source, target, length, mask) { let mask_length = mask.data_view.byteLength, m = 0; for(let i = 0; i < length; i++) { target.data_view.setUint8(i, source.data_view.getUint8(i) ^ mask.data_view.getUint8(m)); m++; if (m >= mask_length) m = 0; } } function string_to_uint8(string) { let uint8_a; if (string.internal_encoding == Opal.encodings["BINARY"]) { let length = string.length; uint8_a = new Uint8Array(length); for(let i = 0; i < length; i++) { uint8_a[i] = string.charCodeAt(i); } } else { let encoder = new TextEncoder(); uint8_a = encoder.encode(string); } return uint8_a; } function endianess() { let uint32_a = new Uint32Array([0x11223344]); let uint8_a = new Uint8Array(uint32_a.buffer); if (uint8_a[0] === 0x44) { return 4; } // LITTLE_ENDIAN else if (uint8_a[0] === 0x11) { return 8; } // BIG_ENDIAN return nil; } } LITTLE_ENDIAN = 4 BIG_ENDIAN = 8 NETWORK_ENDIAN = 8 HOST_ENDIAN = `endianess()` class << self def for(string) # Ruby docs: Creates a zero-copy IO::Buffer from the given string’s memory. # Opal: We have to copy. raise(TypeError, 'arg must be a String') unless string.is_a?(String) `let uint8_a = string_to_uint8(string)` buf = new(`uint8_a.byteLength`) `buf.data_view = new DataView(uint8_a.buffer)` `buf.readonly = true` if string.frozen? return yield buf if block_given? buf ensure `buf.readonly = true` if buf end def map(file, size = nil, offset = 0, flags = READONLY) # Create an IO::Buffer for reading from file by memory-mapping the file. # file should be a File instance, opened for reading. raise(NotImplementedError, 'IO::Buffer#map is not supported!') end def size_of(buffer_type) # Returns the size of the given buffer type(s) in bytes. size = 0 if buffer_type.is_a?(Array) buffer_type.each do |type| size += `size_map.get(type.$to_s())` end else size = `size_map.get(buffer_type.$to_s())` end size end def string(length) # Creates a new string of the given length and yields a zero-copy IO::Buffer # instance to the block which uses the string as a source. The block is # expected to write to the buffer and the string will be returned. raise(ArgumentError, 'length must be a numer') unless length.is_a?(Number) raise(ArgumentError, 'length must be >= 0') if length < 0 # We assume length is in bytes. buffer = new(length) yield buffer buffer.get_string end end def initialize(size = DEFAULT_SIZE, flags = 0) raise(NotImplementedError, 'mapped buffers are not supported') if (flags & MAPPED) > 0 @readonly = (flags & READONLY) > 0 @locked = (flags & LOCKED) > 0 @external = (flags & EXTERNAL) > 0 @internal = !@external @data_view = `new DataView(new ArrayBuffer(size))` end # # special properties of the buffer # def external? # The buffer is external if it references the memory which is not allocated or mapped by the buffer itself. # A buffer created using ::for has an external reference to the string’s memory. # External buffer can’t be resized. @external end def internal? # If the buffer is internal, meaning it references memory allocated by the buffer itself. # An internal buffer is not associated with any external memory (e.g. string) or file mapping. # Internal buffers can be resized, and such an operation will typically invalidate all slices, but not always. @internal end def mapped? # If the buffer is mapped, meaning it references memory mapped by the buffer. # Mapped buffers can usually be resized, and such an operation will typically invalidate all slices, but not always. false end def private? # If the buffer is private, meaning modifications to the buffer will not be replicated to the underlying file mapping. true end def shared? # If the buffer is shared, meaning it references memory that can be shared with other processes # (and thus might change without being modified locally). false end # # logical operators # def ~ # Generate a new buffer the same size as the source by applying the binary NOT # operation to the source. dup.not! end def not! # Modify the source buffer in place by applying the binary NOT operation to the source. raise(AccessError, 'Buffer has been freed!') if null? `op_not(self, self, self.data_view.byteLength)` self end def &(mask) # Generate a new buffer the same size as the source by applying the binary AND # operation to the source, using the mask, repeating as necessary. dup.and!(mask) end def and!(mask) # Modify the source buffer in place by applying the binary AND # operation to the source, using the mask, repeating as necessary. raise(AccessError, 'Buffer has been freed!') if null? `op_and(self, self, self.data_view.byteLength, mask)` self end def |(mask) # Generate a new buffer the same size as the source by applying the binary OR # operation to the source, using the mask, repeating as necessary. dup.or!(mask) end def or!(mask) # Modify the source buffer in place by applying the binary OR operation to the source, using the mask. raise(AccessError, 'Buffer has been freed!') if null? `op_or(self, self, self.data_view.byteLength, mask)` self end def ^(mask) # Generate a new buffer the same size as the source by applying the binary XOR # operation to the source, using the mask, repeating as necessary. dup.xor!(mask) end def xor!(mask) # Modify the source buffer in place by applying the binary XOR # operation to the source, using the mask, repeating as necessary. raise(AccessError, 'Buffer has been freed!') if null? `op_xor(self, self, self.data_view.byteLength, mask)` self end # # other methods # def <=>(other) # Buffers are compared by size and exact contents of the memory they are referencing using memcmp return -1 if size < other.size return 1 if size > other.size %x{ let a, b, length = self.data_view.byteLength; for(let i = 0; i < length; i++) { a = self.data_view.getUint8(i); b = other.data_view.getUint8(i); if (a < b) { return -1; } if (a > b) { return 1; } } } 0 end def clear(value = 0, offset = 0, length = nil) # Fill buffer with value, starting with offset and going for length bytes. raise(AccessError, 'Buffer is not writable!') if readonly? || null? length ||= size %x{ let uint8_a = new Uint8Array(self.data_view.buffer, self.data_view.byteOffset, self.data_view.byteLength); uint8_a.fill(value, offset, length); } self end def copy(source, offset = 0, length = nil, source_offset = 0) # Efficiently copy from a source IO::Buffer into the buffer, # at offset using memcpy. For copying String instances, see set_string. raise(AccessError, 'Buffer is not writable!') if readonly? || null? raise(ArgumentError, 'source must be a ::IO::Buffer') unless source.is_a?(Buffer) length ||= offset + source.size if (offset + length) > size raise(ArgumentError, 'Specified offset+length is bigger than the buffer size!') end %x{ let value; for(let i = 0; i < length;) { if ((length - i) > 4) { value = source.data_view.getUint32(source_offset + i); self.data_view.setUint32(offset + i, value); i += 4; } else { value = source.data_view.getUint8(source_offset + i); self.data_view.setUint8(offset + i, value); i++; } } } length end def each(buffer_type, offset = 0, count = nil) # Iterates over the buffer, yielding each value of buffer_type starting from offset. raise(AccessError, 'Buffer has been freed!') if null? return enum_for(:each, buffer_type, offset, count) unless block_given? step = `size_map.get(buffer_type.$to_s())` i = offset count ||= (size / step).to_i while count > 0 yield i, get_value(buffer_type, i) i += step count -= 1 end self end def each_byte(offset = 0, count = nil) # Iterates over the buffer, yielding each byte starting from offset. raise(AccessError, 'Buffer has been freed!') if null? return enum_for(:each_byte, offset, count) unless block_given? count ||= size while count > 0 yield `self.data_view.getUint8(offset)` offset += 1 count -= 1 end self end def empty? # If the buffer has 0 size size == 0 end def free # If the buffer references memory, release it back to the operating system. raise LockedError if locked? @data_view = nil @locked = true end def get_string(offset = 0, length = nil, encoding = nil) # Read a chunk or all of the buffer into a string, in the specified encoding. # If no encoding is provided Encoding::BINARY is used. raise(AccessError, 'Buffer has been freed!') if null? s = size length ||= s - offset raise(ArgumentError, 'Offset + length is bigger than the buffer size') if offset > s || (offset + length) > s raise(ArgumentError, "Offset can't be negative") if offset < 0 encoding ||= ::Encoding::BINARY js_encoding = case encoding when ::Encoding::ASCII_8BIT then 'ascii' when ::Encoding::BINARY then 'ascii' when ::Encoding::US_ASCII then 'ascii' when ::Encoding::ISO_8859_1 then 'ascii' when ::Encoding::UTF_8 then 'utf-8' when ::Encoding::UTF_16LE then 'utf-16le' when ::Encoding::UTF_16BE then 'utf-16be' else raise(ArgumentError, "#{encoding} not yet supported!") end %x{ let decoder = new TextDecoder(js_encoding); let string = decoder.decode(new DataView(self.data_view.buffer, self.data_view.byteOffset + offset, length)); let n = string.indexOf('\0'); if (n >= 0) { string = string.substring(0, n); } if (string.encoding != encoding) { string = Opal.str(string, encoding.$name()); } return string; } end def get_value(buffer_type, offset) # Read from buffer a value raise(AccessError, 'Buffer has been freed!') if null? buffer_type_s = buffer_type.to_s %x{ let val = self.data_view['get' + fun_map.get(buffer_type_s)](offset, is_le(buffer_type_s)); if (typeof(val) === "bigint") { return Number(val); } return val; } end def get_values(buffer_types, offset) # Similar to get_value, except that it can handle multiple buffer types and returns an array of values. raise(AccessError, 'Buffer has been freed!') if null? array = [] buffer_types.each do |buffer_type| array << get_value(buffer_type, offset) offset += `size_map.get(buffer_type.$to_s())` end array end def hexdump(offset = 0, length = nil, _width = nil) # Returns a human-readable string representation of the buffer. The exact format is subject to change. raise(AccessError, 'Buffer has been freed!') if null? length ||= size %x{ let res = [] for (let i = 0; i < length; i++) { res.push(self.data_view.getUint8(offset + i).toString(16).padStart(2, '0')); } return res.join(' '); } end def initialize_copy(orig) %x{ let odv = orig.data_view; if (odv == nil) { self.data_view = nil; } else { self.data_view = new DataView(new ArrayBuffer(odv.byteLength)); new Uint8Array(self.data_view.buffer).set(new Uint8Array(odv.buffer, odv.byteOffset, odv.byteLength)); } } self end def inspect # #<IO::Buffer 0x000000010198ccd8+11 EXTERNAL READONLY SLICE> "##{self.class} #{hexdump(0, `Math.min(8, #{size})`)} INTERNAL #{' READONLY' if readonly?}" end def locked raise LockedError if locked? @locked = true yield ensure @locked = false end def locked? @locked == true end def null? `(self.data_view && self.data_view != nil) ? false : true` end def pread(io, from, length = nil, offset = 0) # Read at least length bytes from the io starting at the specified from position, # into the buffer starting at offset. If an error occurs, return -errno. raise(AccessError, 'Buffer is not writable!') if readonly? || null? string = io.pread(length, from) set_string(string, offset) string rescue -4 # Errno::EINTR end def pwrite(io, from, length = nil, offset = 0) # Write at least length bytes from the buffer starting at offset, # into the io starting at the specified from position. If an error occurs, return -errno. io.pwrite(get_string(offset, length), from) rescue -4 # Errno::EINTR end def read(io, length = nil, offset = 0) # Read at least length bytes from the io, into the buffer starting at offset. # If an error occurs, return -errno. raise(AccessError, 'Buffer is not writable!') if readonly? || null? string = io.read(length) set_string(string, offset) length rescue -4 # Errno::EINTR end def readonly? # Frozen strings and read-only files create read-only buffers. @readonly end def resize(new_size) # Resizes a buffer to a new_size bytes, preserving its content. raise(AccessError, 'Buffer is not writable!') if readonly? || null? raise(AccessError, 'Buffer references external memory!') if external? raise LockedError if locked? %x{ let dv = self.data_view; let buffer = new ArrayBuffer(new_size); let length = (new_size > dv.byteLength) ? dv.byteLength : new_size; new Uint8Array(buffer).set(new Uint8Array(dv.buffer, dv.byteOffset, length)); self.data_view = new DataView(buffer); } self end def set_string(string, offset = 0, length = nil, source_offset = nil) # Efficiently copy from a source String into the buffer, at offset using memcpy. # Ruby does a byte copy from the C string to the buffer, with the C string most likely # being UTF8 encoded. So we do the same, asuming UTF8 for Ruby compatibility, # although JavaScript is using UTF16. Efficiently here only happens for UTF8 anyway. raise(AccessError, 'Buffer is not writable!') if readonly? || null? %x{ if (typeof(source_offset) === "number") { string = string.slice(source_offset); } let uint8_a = string_to_uint8(string); let strg_dv = new DataView(uint8_a.buffer); if (typeof(length) !== "number") { length = uint8_a.byteLength; } for (let i = 0; i < length;) { if ((length - i) > 4) { self.data_view.setUint32(offset + i, strg_dv.getUint32(i)); i += 4; } else { self.data_view.setUint8(offset + i, strg_dv.getUint8(i)); i++; } } } length end def set_value(buffer_type, offset, value) # Write to a buffer a value of type at offset. raise(AccessError, 'Buffer is not writable!') if readonly? || null? buffer_type_s = buffer_type.to_s %x{ let fun = 'set' + fun_map.get(buffer_type_s); if (fun[3] === 'B') { value = BigInt(value); } self.data_view[fun](offset, value, is_le(buffer_type_s)); } offset + `size_map.get(buffer_type_s)` end def set_values(buffer_types, offset, values) # Write values of buffer_types at offset to the buffer. buffer_types should be an array # of symbols as described in get_value. values should be an array of values to write. raise(AccessError, 'Buffer is not writable!') if readonly? || null? raise(ArgumentError, 'Argument buffer_types must be an array!') unless buffer_types.is_a?(Array) raise(ArgumentError, 'Argument values must be an array!') unless values.is_a?(Array) raise(ArgumentError, 'Arrays buffer_types and values must have the same length!') unless buffer_types.size == values.size buffer_types.each_with_index do |buffer_type, idx| offset = set_value(buffer_type, offset, values[idx]) end offset end def size # Returns the size of the buffer that was explicitly set (on creation with ::new or on resize), # or deduced on buffer’s creation from string or file. return 0 if null? `self.data_view.byteLength` end def slice(offset = 0, length = nil) # Produce another IO::Buffer which is a slice (or view into) the current one # starting at offset bytes and going for length bytes. raise(AccessError, 'Buffer has been freed!') if null? raise(ArgumentError, 'offset must be >= 0') if offset < 0 length ||= size - offset raise(ArgumentError, 'length must be >= 0') if length < 0 end_pos = offset + length raise(ArgumentError, "Index #{end_pos} out buffer bounds") if end_pos > size io_buffer = Buffer.new(0, EXTERNAL) `io_buffer.data_view = new DataView(self.data_view.buffer, self.data_view.byteOffset + offset, length)` `io_buffer.readonly = true` if readonly? io_buffer end def to_s inspect end def transfer # Transfers ownership of the underlying memory to a new buffer, causing the current buffer to become uninitialized. raise(AccessError, 'Buffer has been freed!') if null? raise(LockedError, 'Cannot transfer ownership of locked buffer!') if locked? io_buffer = Buffer.new(0) `io_buffer.data_view = self.data_view` `io_buffer.readonly = true` if readonly? @data_view = nil io_buffer end def valid? # Returns whether the buffer buffer is accessible. !null? end def values(buffer_type, offset = 0, count = nil) # Returns an array of values of buffer_type starting from offset. array = [] step = `size_map.get(buffer_type.$to_s())` count ||= (size / step).to_i while count > 0 array << get_value(buffer_type, offset) offset += step count -= 1 end array end def write(io, length = nil, offset = 0) # Write at least length bytes from the buffer starting at offset, into the io. If an error occurs, return -errno. raise(AccessError, 'Buffer has been freed!') if null? length ||= size - offset io.write(get_string(offset, length)) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/random/seedrandom.js.rb
opal/corelib/random/seedrandom.js.rb
# backtick_javascript: true # use_strict: true class ::Random %x{ var module = { exports: {} }; /* eslint-disable */ /* seedrandom.min.js 2.4.1 (original source: https://github.com/davidbau/seedrandom/blob/2.4.1/seedrandom.min.js) How to update: . Chekout the latest release from GitHub: https://github.com/davidbau/seedrandom . Apply the following commits: .. Check for hasOwnProperty in flatten(): https://github.com/iliabylich/seedrandom/commit/06a94f59ae3d3956c8b1a2488334cafab6744b04 .. Add a module id for the RequireJS `define` method: https://github.com/Mogztter/seedrandom/commit/e047540c3d81f955cab9a01d17b8141d439fbd7d */ !function(a,b){function c(c,j,k){var n=[];j=1==j?{entropy:!0}:j||{};var s=g(f(j.entropy?[c,i(a)]:null==c?h():c,3),n),t=new d(n),u=function(){for(var a=t.g(m),b=p,c=0;a<q;)a=(a+c)*l,b*=l,c=t.g(1);for(;a>=r;)a/=2,b/=2,c>>>=1;return(a+c)/b};return u.int32=function(){return 0|t.g(4)},u.quick=function(){return t.g(4)/4294967296},u.double=u,g(i(t.S),a),(j.pass||k||function(a,c,d,f){return f&&(f.S&&e(f,t),a.state=function(){return e(t,{})}),d?(b[o]=a,c):a})(u,s,"global"in j?j.global:this==b,j.state)}function d(a){var b,c=a.length,d=this,e=0,f=d.i=d.j=0,g=d.S=[];for(c||(a=[c++]);e<l;)g[e]=e++;for(e=0;e<l;e++)g[e]=g[f=s&f+a[e%c]+(b=g[e])],g[f]=b;(d.g=function(a){for(var b,c=0,e=d.i,f=d.j,g=d.S;a--;)b=g[e=s&e+1],c=c*l+g[s&(g[e]=g[f=s&f+b])+(g[f]=b)];return d.i=e,d.j=f,c})(l)}function e(a,b){return b.i=a.i,b.j=a.j,b.S=a.S.slice(),b}function f(a,b){var c,d=[],e=typeof a;if(b&&"object"==e)for(c in a)if(a.hasOwnProperty(c))try{d.push(f(a[c],b-1))}catch(a){}return d.length?d:"string"==e?a:a+"\0"}function g(a,b){for(var c,d=a+"",e=0;e<d.length;)b[s&e]=s&(c^=19*b[s&e])+d.charCodeAt(e++);return i(b)}function h(){try{if(j)return i(j.randomBytes(l));var b=new Uint8Array(l);return(k.crypto||k.msCrypto).getRandomValues(b),i(b)}catch(b){var c=k.navigator,d=c&&c.plugins;return[+new Date,k,d,k.screen,i(a)]}}function i(a){return String.fromCharCode.apply(0,a)}var j,k=this,l=256,m=6,n=52,o="random",p=b.pow(l,m),q=b.pow(2,n),r=2*q,s=l-1;if(b["seed"+o]=c,g(b.random(),a),"object"==typeof module&&module.exports){module.exports=c;try{j=require("crypto")}catch(a){}}else"function"==typeof define&&define.amd&&define('seekrandom',function(){return c})}([],Math); /* eslint-enable */ var seedrandom = module.exports var $seed_generator = new Math.seedrandom('opal', { entropy: true }) } self::SEEDRANDOM_GENERATOR = `{ new_seed: function() { return Math.abs($seed_generator.int32()); }, reseed: function(seed) { return new seedrandom(seed); }, rand: function($rng) { return $rng.quick(); } }` self.generator = self::SEEDRANDOM_GENERATOR end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/random/mersenne_twister.rb
opal/corelib/random/mersenne_twister.rb
# backtick_javascript: true # use_strict: true # This is based on an adaptation of Makoto Matsumoto and Takuji Nishimura's code # done by Sean McCullough <banksean@gmail.com> and Dave Heitzman # <daveheitzman@yahoo.com>, subsequently readapted from an updated version of # ruby's random.c (rev c38a183032a7826df1adabd8aa0725c713d53e1c). # # The original copyright notice from random.c follows. # # This is based on trimmed version of MT19937. To get the original version, # contact <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html>. # # The original copyright notice follows. # # A C-program for MT19937, with initialization improved 2002/2/10. # Coded by Takuji Nishimura and Makoto Matsumoto. # This is a faster version by taking Shawn Cokus's optimization, # Matthe Bellew's simplification, Isaku Wada's real version. # # Before using, initialize the state by using init_genrand(mt, seed) # or init_by_array(mt, init_key, key_length). # # Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, # 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.keio.ac.jp/matumoto/emt.html # email: matumoto@math.keio.ac.jp class ::Random mersenne_twister = %x{(function() { /* Period parameters */ var N = 624; var M = 397; var MATRIX_A = 0x9908b0df; /* constant vector a */ var UMASK = 0x80000000; /* most significant w-r bits */ var LMASK = 0x7fffffff; /* least significant r bits */ var MIXBITS = function(u,v) { return ( ((u) & UMASK) | ((v) & LMASK) ); }; var TWIST = function(u,v) { return (MIXBITS((u),(v)) >>> 1) ^ ((v & 0x1) ? MATRIX_A : 0x0); }; function init(s) { var mt = {left: 0, next: N, state: new Array(N)}; init_genrand(mt, s); return mt; } /* initializes mt[N] with a seed */ function init_genrand(mt, s) { var j, i; mt.state[0] = s >>> 0; for (j=1; j<N; j++) { mt.state[j] = (1812433253 * ((mt.state[j-1] ^ (mt.state[j-1] >> 30) >>> 0)) + j); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array state[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt.state[j] &= 0xffffffff; /* for >32 bit machines */ } mt.left = 1; mt.next = N; } /* generate N words at one time */ function next_state(mt) { var p = 0, _p = mt.state; var j; mt.left = N; mt.next = 0; for (j=N-M+1; --j; p++) _p[p] = _p[p+(M)] ^ TWIST(_p[p+(0)], _p[p+(1)]); for (j=M; --j; p++) _p[p] = _p[p+(M-N)] ^ TWIST(_p[p+(0)], _p[p+(1)]); _p[p] = _p[p+(M-N)] ^ TWIST(_p[p+(0)], _p[0]); } /* generates a random number on [0,0xffffffff]-interval */ function genrand_int32(mt) { /* mt must be initialized */ var y; if (--mt.left <= 0) next_state(mt); y = mt.state[mt.next++]; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y >>> 0; } function int_pair_to_real_exclusive(a, b) { a >>>= 5; b >>>= 6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } // generates a random number on [0,1) with 53-bit resolution function genrand_real(mt) { /* mt must be initialized */ var a = genrand_int32(mt), b = genrand_int32(mt); return int_pair_to_real_exclusive(a, b); } return { genrand_real: genrand_real, init: init }; })()} `var MAX_INT = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1` self::MERSENNE_TWISTER_GENERATOR = `{ new_seed: function() { return Math.round(Math.random() * MAX_INT); }, reseed: function(seed) { return mersenne_twister.init(seed); }, rand: function(mt) { return mersenne_twister.genrand_real(mt); } }` self.generator = self::MERSENNE_TWISTER_GENERATOR end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/random/math_random.js.rb
opal/corelib/random/math_random.js.rb
# backtick_javascript: true # use_strict: true class ::Random MATH_RANDOM_GENERATOR = `{ new_seed: function() { return 0; }, reseed: function(seed) { return {}; }, rand: function($rng) { return Math.random(); } }` self.generator = MATH_RANDOM_GENERATOR end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/random/formatter.rb
opal/corelib/random/formatter.rb
# backtick_javascript: true # use_strict: true class ::Random module self::Formatter def hex(count = nil) count = ::Random._verify_count(count) %x{ var bytes = #{bytes(count)}; var out = ""; for (var i = 0; i < #{count}; i++) { out += bytes.charCodeAt(i).toString(16).padStart(2, '0'); } return #{`out`.encode('US-ASCII')}; } end def random_bytes(count = nil) bytes(count) end def base64(count = nil) ::Base64.strict_encode64(random_bytes(count)).encode('US-ASCII') end def urlsafe_base64(count = nil, padding = false) ::Base64.urlsafe_encode64(random_bytes(count), padding).encode('US-ASCII') end def uuid str = hex(16).split('') str[12] = '4' str[16] = `(parseInt(#{str[16]}, 16) & 3 | 8).toString(16)` str = [str[0...8], str[8...12], str[12...16], str[16...20], str[20...32]] str = str.map(&:join) str.join('-') end # Implemented in terms of `#bytes` for SecureRandom, but Random overrides this # method to implement `#bytes` in terms of `#random_float`. Not part of standard # Ruby interface - use random_number for portability. def random_float bs = bytes(4) num = 0 4.times do |i| num <<= 8 num |= bs[i].ord end num.abs / 0x7fffffff end def random_number(limit = undefined) %x{ function randomFloat() { return #{random_float}; } function randomInt(max) { return Math.floor(randomFloat() * max); } function randomRange() { var min = limit.begin, max = limit.end; if (min === nil || max === nil) { return nil; } var length = max - min; if (length < 0) { return nil; } if (length === 0) { return min; } if (max % 1 === 0 && min % 1 === 0 && !limit.excl) { length++; } return randomInt(length) + min; } if (limit == null) { return randomFloat(); } else if (limit.$$is_range) { return randomRange(); } else if (limit.$$is_number) { if (limit <= 0) { #{::Kernel.raise ::ArgumentError, "invalid argument - #{limit}"} } if (limit % 1 === 0) { // integer return randomInt(limit); } else { return randomFloat() * limit; } } else { limit = #{::Opal.coerce_to!(limit, ::Integer, :to_int)}; if (limit <= 0) { #{::Kernel.raise ::ArgumentError, "invalid argument - #{limit}"} } return randomInt(limit); } } end def alphanumeric(count = nil) count = Random._verify_count(count) map = ['0'..'9', 'a'..'z', 'A'..'Z'].map(&:to_a).flatten ::Array.new(count) do |i| map[random_number(map.length)] end.join end end include ::Random::Formatter extend ::Random::Formatter end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/pack_unpack/format_string_parser.rb
opal/corelib/pack_unpack/format_string_parser.rb
# backtick_javascript: true module ::PackUnpack %x{ var directives = [ // Integer 'C', 'S', 'L', 'Q', 'J', 'c', 's', 'l', 'q', 'j', 'n', 'N', 'v', 'V', 'U', 'w', // Float 'D', 'd', 'F', 'f', 'E', 'e', 'G', 'g', // String 'A', 'a', 'Z', 'B', 'b', 'H', 'h', 'u', 'M', 'm', 'P', 'p', // Misc '@', 'X', 'x' ]; var modifiers = [ '!', // ignored '_', // ignored '>', // big endian '<' // little endian ]; self.eachDirectiveAndCount = function(format, callback) { var currentDirective, currentCount, currentModifiers, countSpecified; function reset() { currentDirective = null; currentCount = 0; currentModifiers = []; countSpecified = false; } reset(); function yieldAndReset() { if (currentDirective == null) { reset(); return; } var directiveSupportsModifiers = /[sSiIlLqQjJ]/.test(currentDirective); if (!directiveSupportsModifiers && currentModifiers.length > 0) { #{::Kernel.raise ::ArgumentError, "'#{`currentModifiers[0]`}' allowed only after types sSiIlLqQjJ"} } if (currentModifiers.indexOf('<') !== -1 && currentModifiers.indexOf('>') !== -1) { #{::Kernel.raise ::RangeError, "Can't use both '<' and '>'"} } if (!countSpecified) { currentCount = 1; } if (currentModifiers.indexOf('>') !== -1) { currentDirective = currentDirective + '>'; } callback(currentDirective, currentCount); reset(); } for (var i = 0; i < format.length; i++) { var currentChar = format[i]; if (directives.indexOf(currentChar) !== -1) { // Directive char always resets current state yieldAndReset(); currentDirective = currentChar; } else if (currentDirective) { if (/\d/.test(currentChar)) { // Count can be represented as a sequence of digits currentCount = currentCount * 10 + parseInt(currentChar, 10); countSpecified = true; } else if (currentChar === '*' && countSpecified === false) { // Count can be represented by a star character currentCount = Infinity; countSpecified = true; } else if (modifiers.indexOf(currentChar) !== -1 && countSpecified === false) { // Directives can be specified only after directive and before count currentModifiers.push(currentChar); } else { yieldAndReset(); } } } yieldAndReset(); } } end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/opal/full.rb
opal/opal/full.rb
::Object.autoload :Marshal, 'corelib/marshal' ::Object.require 'corelib/string/encoding/dummy' ::Object.require 'corelib/string/encoding/eucjp' ::Object.require 'corelib/string/encoding/jis' ::Object.require 'corelib/string/encoding/sjis' ::Object.require 'corelib/string/unpack' ::Object.require 'corelib/array/pack' ::Object.autoload :ObjectSpace, 'corelib/object_space' ::Object.require 'corelib/pattern_matching/base' ::Object.autoload :PatternMatching, 'corelib/pattern_matching' ::Object.autoload :TracePoint, 'corelib/trace_point' ::Object.require 'corelib/io/buffer'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/opal/base.rb
opal/opal/base.rb
::Object.require 'runtime/runtime' ::Object.require 'corelib/module' ::Object.require 'corelib/class' ::Object.require 'corelib/basic_object' ::Object.require 'corelib/kernel' ::Object.require 'corelib/main' ::Object.require 'corelib/error' ::Object.require 'corelib/constants'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/opal/mini.rb
opal/opal/mini.rb
::Object.require 'opal/base' ::Object.require 'corelib/nil' ::Object.require 'corelib/boolean' ::Object.require 'corelib/comparable' ::Object.require 'corelib/regexp' ::Object.require 'corelib/string' ::Object.require 'corelib/enumerable' ::Object.require 'corelib/enumerator' ::Object.require 'corelib/array' ::Object.require 'corelib/hash' ::Object.require 'corelib/number' ::Object.require 'corelib/range' ::Object.require 'corelib/proc' ::Object.require 'corelib/method' ::Object.require 'opal/regexp_transpiler' ::Object.require 'opal/regexp_anchors' ::Object.require 'corelib/variables' ::Object.require 'corelib/string/encoding' ::Object.require 'corelib/io'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/proc.rb
opal/runtime/proc.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: apply_blockopts, raise module ::Opal %x{ function call_lambda(block, arg, ret) { try { block(arg); } catch (e) { if (e === ret) { return ret.$v; } throw e; } } } def self.lambda(block, blockopts) %x{ block.$$is_lambda = true; $apply_blockopts(block, blockopts); return block; } end # Arity count error dispatcher for blocks # # @param actual [Fixnum] number of arguments given to block # @param expected [Fixnum] expected number of arguments # @param context [Object] context of the block definition # @raise [ArgumentError] def self.block_ac(actual, expected, context) %x{ var inspect = "`block in " + context + "'"; $raise(Opal.ArgumentError, inspect + ': wrong number of arguments (given ' + actual + ', expected ' + expected + ')'); } end # handles yield calls for 1 yielded arg def self.yield1(block, arg) %x{ if (typeof(block) !== "function") { $raise(Opal.LocalJumpError, "no block given"); } var has_mlhs = block.$$has_top_level_mlhs_arg, has_trailing_comma = block.$$has_trailing_comma_in_args, is_returning_lambda = block.$$is_lambda && block.$$ret; if (block.length > 1 || ((has_mlhs || has_trailing_comma) && block.length === 1)) { arg = Opal.to_ary(arg); } if ((block.length > 1 || (has_trailing_comma && block.length === 1)) && arg.$$is_array) { if (is_returning_lambda) { return call_lambda(block.apply.bind(block, null), arg, block.$$ret); } return block.apply(null, arg); } else { if (is_returning_lambda) { return call_lambda(block, arg, block.$$ret); } return block(arg); } } end # handles yield for > 1 yielded arg def self.yieldX(block, args) %x{ if (typeof(block) !== "function") { $raise(Opal.LocalJumpError, "no block given"); } if (block.length > 1 && args.length === 1) { if (args[0].$$is_array) { args = args[0]; } } if (block.$$is_lambda && block.$$ret) { return call_lambda(block.apply.bind(block, null), args, block.$$ret); } return block.apply(null, args); } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/method.rb
opal/runtime/method.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: deny_frozen_access, prop, has_own, jsid, raise, ancestors, get_ancestors module ::Opal # Method creation/deletion # ------------------------ # Used to define methods on an object. This is a helper method, used by the # compiled source to define methods on special case objects when the compiler # can not determine the destination object, or the object is a Module # instance. This can get called by `Module#define_method` as well. # # ## Modules # # Any method defined on a module will come through this runtime helper. # The method is added to the module body, and the owner of the method is # set to be the module itself. This is used later when choosing which # method should show on a class if more than 1 included modules define # the same method. Finally, if the module is in `module_function` mode, # then the method is also defined onto the module itself. # # ## Classes # # This helper will only be called for classes when a method is being # defined indirectly; either through `Module#define_method`, or by a # literal `def` method inside an `instance_eval` or `class_eval` body. In # either case, the method is simply added to the class' prototype. A special # exception exists for `BasicObject` and `Object`. These two classes are # special because they are used in toll-free bridged classes. In each of # these two cases, extra work is required to define the methods on toll-free # bridged class' prototypes as well. # # ## Objects # # If a simple ruby object is the object, then the method is simply just # defined on the object as a singleton method. This would be the case when # a method is defined inside an `instance_eval` block. # # @param obj [Object, Class] the actual obj to define method for # @param jsid [String] the JavaScript friendly method name (e.g. '$foo') # @param body [JS.Function] the literal JavaScript function used as method # @param blockopts [Object, Number] optional properties to set on the body # @return [null] def self.def(obj, jsid, body, blockopts) %x{ $apply_blockopts(body, blockopts); // Special case for a method definition in the // top-level namespace if (obj === Opal.top) { return Opal.defn(Opal.Object, jsid, body); } // if instance_eval is invoked on a module/class, it sets inst_eval_mod else if (!obj.$$eval && obj.$$is_a_module) { return Opal.defn(obj, jsid, body); } else { return Opal.defs(obj, jsid, body); } } end # Define method on a module or class (see Opal.def). def self.defn(mod, jsid, body) %x{ $deny_frozen_access(mod); body.displayName = jsid; body.$$owner = mod; var name = jsid.substr(1); var proto = mod.$$prototype; if (proto.hasOwnProperty('$$dummy')) { proto = proto.$$define_methods_on; } $prop(proto, jsid, body); if (mod.$$is_module) { if (mod.$$module_function) { Opal.defs(mod, jsid, body) } for (var i = 0, iclasses = mod.$$iclasses, length = iclasses.length; i < length; i++) { var iclass = iclasses[i]; $prop(iclass, jsid, body); } } var singleton_of = mod.$$singleton_of; if (mod.$method_added && !mod.$method_added.$$stub && !singleton_of) { mod.$method_added(name); } else if (singleton_of && singleton_of.$singleton_method_added && !singleton_of.$singleton_method_added.$$stub) { singleton_of.$singleton_method_added(name); } return name; } end # Define a singleton method on the given object (see Opal.def). def self.defs(obj, jsid, body, blockopts) %x{ $apply_blockopts(body, blockopts); if (obj.$$is_string || obj.$$is_number) { $raise(Opal.TypeError, "can't define singleton"); } return Opal.defn(Opal.get_singleton_class(obj), jsid, body); } end # Since JavaScript has no concept of modules, we create proxy classes # called `iclasses` that store copies of methods loaded. We need to # update them if we remove a method. def self.remove_method_from_iclasses(obj, jsid) %x{ if (obj.$$is_module) { for (var i = 0, iclasses = obj.$$iclasses, length = iclasses.length; i < length; i++) { var iclass = iclasses[i]; delete iclass[jsid]; } } } end # Called from #remove_method. def self.rdef(obj, jsid) %x{ if (!$has_own(obj.$$prototype, jsid)) { $raise(Opal.NameError, "method '" + jsid.substr(1) + "' not defined in " + obj.$name()); } delete obj.$$prototype[jsid]; Opal.remove_method_from_iclasses(obj, jsid); if (obj.$$is_singleton) { if (obj.$$prototype.$singleton_method_removed && !obj.$$prototype.$singleton_method_removed.$$stub) { obj.$$prototype.$singleton_method_removed(jsid.substr(1)); } } else { if (obj.$method_removed && !obj.$method_removed.$$stub) { obj.$method_removed(jsid.substr(1)); } } } end # Called from #undef_method. def self.udef(obj, jsid) %x{ if (!obj.$$prototype[jsid] || obj.$$prototype[jsid].$$stub) { $raise(Opal.NameError, "method '" + jsid.substr(1) + "' not defined in " + obj.$name()); } Opal.add_stub_for(obj.$$prototype, jsid); Opal.remove_method_from_iclasses(obj, jsid); if (obj.$$is_singleton) { if (obj.$$prototype.$singleton_method_undefined && !obj.$$prototype.$singleton_method_undefined.$$stub) { obj.$$prototype.$singleton_method_undefined(jsid.substr(1)); } } else { if (obj.$method_undefined && !obj.$method_undefined.$$stub) { obj.$method_undefined(jsid.substr(1)); } } } end def self.alias(obj, name, old) %x{ function is_method_body(body) { return (typeof(body) === "function" && !body.$$stub); } var id = $jsid(name), old_id = $jsid(old), body, alias; // Aliasing on main means aliasing on Object... if (typeof obj.$$prototype === 'undefined') { obj = Opal.Object; } body = obj.$$prototype[old_id]; // When running inside #instance_eval the alias refers to class methods. if (obj.$$eval) { return Opal.alias(Opal.get_singleton_class(obj), name, old); } if (!is_method_body(body)) { var ancestor = obj.$$super; while (typeof(body) !== "function" && ancestor) { body = ancestor[old_id]; ancestor = ancestor.$$super; } if (!is_method_body(body) && obj.$$is_module) { // try to look into Object body = Opal.Object.$$prototype[old_id] } if (!is_method_body(body)) { $raise(Opal.NameError, "undefined method `" + old + "' for class `" + obj.$name() + "'") } } // If the body is itself an alias use the original body // to keep the max depth at 1. if (body.$$alias_of) body = body.$$alias_of; // We need a wrapper because otherwise properties // would be overwritten on the original body. alias = Opal.wrap_method_body(body); // Try to make the browser pick the right name alias.displayName = name; alias.$$alias_of = body; alias.$$alias_name = name; Opal.defn(obj, id, alias); return obj; } end def self.alias_native(obj, name, native_name) %x{ var id = $jsid(name), body = obj.$$prototype[native_name]; if (typeof(body) !== "function" || body.$$stub) { $raise(Opal.NameError, "undefined native method `" + native_name + "' for class `" + obj.$name() + "'") } Opal.defn(obj, id, body); return obj; } end def self.wrap_method_body(body) %x{ var wrapped = function() { var block = wrapped.$$p; wrapped.$$p = null; return Opal.send(this, body, arguments, block); }; // Assign the 'length' value with defineProperty because // in strict mode the property is not writable. // It doesn't work in older browsers (like Chrome 38), where // an exception is thrown breaking Opal altogether. try { Object.defineProperty(wrapped, 'length', { value: body.length }); } catch {} wrapped.$$arity = body.$$arity == null ? body.length : body.$$arity; wrapped.$$parameters = body.$$parameters; wrapped.$$source_location = body.$$source_location; return wrapped; } end # Method arguments # ---------------- # Arity count error dispatcher for methods # # @param actual [Fixnum] number of arguments given to method # @param expected [Fixnum] expected number of arguments # @param object [Object] owner of the method +meth+ # @param meth [String] method name that got wrong number of arguments # @raise [ArgumentError] def self.ac(actual, expected, object, meth) %x{ var inspect = ''; if (object.$$is_a_module) { inspect += object.$$name + '.'; } else { inspect += object.$$class.$$name + '#'; } inspect += meth; $raise(Opal.ArgumentError, '[' + inspect + '] wrong number of arguments (given ' + actual + ', expected ' + expected + ')'); } end # Method iteration # ---------------- # rubocop:disable Naming/PredicatePrefix def self.is_method(prop) `prop[0] === '$' && prop[1] !== '$'` end # rubocop:enable Naming/PredicatePrefix def self.instance_methods(mod) %x{ var processed = Object.create(null), results = [], ancestors = $ancestors(mod); for (var i = 0, l = ancestors.length; i < l; i++) { var ancestor = ancestors[i], proto = ancestor.$$prototype; if (proto.hasOwnProperty('$$dummy')) { proto = proto.$$define_methods_on; } var props = Object.getOwnPropertyNames(proto); for (var j = 0, ll = props.length; j < ll; j++) { var prop = props[j]; if (processed[prop]) { continue; } if (Opal.is_method(prop)) { var method = proto[prop]; if (!method.$$stub) { var method_name = prop.slice(1); results.push(method_name); } } processed[prop] = true; } } return results; } end def self.own_instance_methods(mod) %x{ var results = [], proto = mod.$$prototype; if (proto.hasOwnProperty('$$dummy')) { proto = proto.$$define_methods_on; } var props = Object.getOwnPropertyNames(proto); for (var i = 0, length = props.length; i < length; i++) { var prop = props[i]; if (Opal.is_method(prop)) { var method = proto[prop]; if (!method.$$stub) { var method_name = prop.slice(1); results.push(method_name); } } } return results; } end def self.methods(obj) `Opal.instance_methods(obj.$$meta || obj.$$class)` end def self.own_methods(obj) `obj.$$meta ? Opal.own_instance_methods(obj.$$meta) : []` end def self.receiver_methods(obj) %x{ var mod = Opal.get_singleton_class(obj); var singleton_methods = Opal.own_instance_methods(mod); var instance_methods = Opal.own_instance_methods(mod.$$super); return singleton_methods.concat(instance_methods); } end # Super call # ---------- # Super dispatcher def self.find_super(obj, mid, current_func, defcheck, allow_stubs) %x{ var jsid = $jsid(mid), ancestors, ancestor, super_method, method_owner, current_index = -1, i; ancestors = $get_ancestors(obj); method_owner = current_func.$$owner; for (i = 0; i < ancestors.length; i++) { ancestor = ancestors[i]; if (ancestor === method_owner || ancestor.$$cloned_from.indexOf(method_owner) !== -1) { current_index = i; break; } } for (i = current_index + 1; i < ancestors.length; i++) { ancestor = ancestors[i]; var proto = ancestor.$$prototype; if (proto.hasOwnProperty('$$dummy')) { proto = proto.$$define_methods_on; } if (proto.hasOwnProperty(jsid)) { super_method = proto[jsid]; break; } } if (!defcheck && super_method && super_method.$$stub && obj.$method_missing.$$pristine) { // method_missing hasn't been explicitly defined $raise(Opal.NoMethodError, 'super: no superclass method `'+mid+"' for "+obj, mid); } return (super_method.$$stub && !allow_stubs) ? null : super_method; } end # Iter dispatcher for super in a block def self.find_block_super(obj, jsid, current_func, defcheck, implicit) %x{ var call_jsid = jsid; if (!current_func) { $raise(Opal.RuntimeError, "super called outside of method"); } if (implicit && current_func.$$define_meth) { $raise(Opal.RuntimeError, "implicit argument passing of super from method defined by define_method() is not supported. " + "Specify all arguments explicitly" ); } if (current_func.$$def) { call_jsid = current_func.$$jsid; } return Opal.find_super(obj, call_jsid, current_func, defcheck); } end def self.apply_blockopts(block, blockopts) %x{ if (typeof(blockopts) === 'number') { block.$$arity = blockopts; } else if (typeof(blockopts) === 'object') { Object.assign(block, blockopts); } } end `var $apply_blockopts = Opal.apply_blockopts` end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/const.rb
opal/runtime/const.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: prop, raise, Object, has_own module ::Opal # Walk up the nesting array looking for the constant def self.const_lookup_nesting(nesting, name) %x{ var i, ii, constant; if (nesting.length === 0) return; // If the nesting is not empty the constant is looked up in its elements // and in order. The ancestors of those elements are ignored. for (i = 0, ii = nesting.length; i < ii; i++) { constant = nesting[i].$$const[name]; if (constant != null) { return constant; } else if (nesting[i].$$autoload && nesting[i].$$autoload[name]) { return Opal.handle_autoload(nesting[i], name); } } } end # Walk up Object's ancestors chain looking for the constant, # but only if cref is missing or a module. def self.const_lookup_Object(cref, name) %x{ if (cref == null || cref.$$is_module) { return Opal.const_lookup_ancestors($Object, name); } } end # Call const_missing if nothing else worked def self.const_missing(cref, name) `(cref || $Object)`.const_missing(name) end def self.const_get_name(cref, name) %x{ if (cref) { if (cref.$$const[name] != null) { return cref.$$const[name]; } if (cref.$$autoload && cref.$$autoload[name]) { return Opal.handle_autoload(cref, name); } } } end # Walk up the ancestors chain looking for the constant def self.const_lookup_ancestors(cref, name) %x{ var i, ii, ancestors; if (cref == null) return; ancestors = $ancestors(cref); for (i = 0, ii = ancestors.length; i < ii; i++) { if (ancestors[i].$$const && $has_own(ancestors[i].$$const, name)) { return ancestors[i].$$const[name]; } else if (ancestors[i].$$autoload && ancestors[i].$$autoload[name]) { return Opal.handle_autoload(ancestors[i], name); } } } end def self.handle_autoload(cref, name) %x{ if (!cref.$$autoload[name].loaded) { cref.$$autoload[name].loaded = true; try { Opal.Kernel.$require(cref.$$autoload[name].path); } catch (e) { cref.$$autoload[name].exception = e; throw e; } cref.$$autoload[name].required = true; if (cref.$$const[name] != null) { cref.$$autoload[name].success = true; return cref.$$const[name]; } } else if (cref.$$autoload[name].loaded && !cref.$$autoload[name].required) { if (cref.$$autoload[name].exception) { throw cref.$$autoload[name].exception; } } } end # Look for the constant just in the current cref or call `#const_missing` def self.const_get_local(cref, name, skip_missing) %x{ var result; if (cref == null) return; if (cref === '::') cref = $Object; if (!cref.$$is_module && !cref.$$is_class) { $raise(Opal.TypeError, cref.toString() + " is not a class/module"); } result = Opal.const_get_name(cref, name); return result != null || skip_missing ? result : Opal.const_missing(cref, name); } end # Look for the constant relative to a cref or call `#const_missing` (when the # constant is prefixed by `::`). def self.const_get_qualified(cref, name, skip_missing) %x{ var result, cache, cached, current_version = Opal.const_cache_version; if (name == null) { // A shortpath for calls like ::String => $$$("String") result = Opal.const_get_name($Object, cref); if (result != null) return result; return Opal.const_get_qualified($Object, cref, skip_missing); } if (cref == null) return; if (cref === '::') cref = $Object; if (!cref.$$is_module && !cref.$$is_class) { $raise(Opal.TypeError, cref.toString() + " is not a class/module"); } if ((cache = cref.$$const_cache) == null) { $prop(cref, '$$const_cache', Object.create(null)); cache = cref.$$const_cache; } cached = cache[name]; if (cached == null || cached[0] !== current_version) { ((result = Opal.const_get_name(cref, name)) != null) || ((result = Opal.const_lookup_ancestors(cref, name)) != null); cache[name] = [current_version, result]; } else { result = cached[1]; } return result != null || skip_missing ? result : Opal.const_missing(cref, name); } end # Look for the constant in the open using the current nesting and the nearest # cref ancestors or call `#const_missing` (when the constant has no :: prefix). def self.const_get_relative(nesting, name, skip_missing) %x{ var cref = nesting[0], result, current_version = Opal.const_cache_version, cache, cached; if ((cache = nesting.$$const_cache) == null) { $prop(nesting, '$$const_cache', Object.create(null)); cache = nesting.$$const_cache; } cached = cache[name]; if (cached == null || cached[0] !== current_version) { ((result = Opal.const_get_name(cref, name)) != null) || ((result = Opal.const_lookup_nesting(nesting, name)) != null) || ((result = Opal.const_lookup_ancestors(cref, name)) != null) || ((result = Opal.const_lookup_Object(cref, name)) != null); cache[name] = [current_version, result]; } else { result = cached[1]; } return result != null || skip_missing ? result : Opal.const_missing(cref, name); } end # Get all the constants reachable from a given cref, by default will include # inherited constants. def self.constants(cref, inherit) %x{ if (inherit == null) inherit = true; var module, modules = [cref], i, ii, constants = {}, constant; if (inherit) modules = modules.concat(Opal.ancestors(cref)); if (inherit && cref.$$is_module) modules = modules.concat([Opal.Object]).concat(Opal.ancestors(Opal.Object)); for (i = 0, ii = modules.length; i < ii; i++) { module = modules[i]; // Do not show Objects constants unless we're querying Object itself if (cref !== $Object && module == $Object) break; for (constant in module.$$const) { constants[constant] = true; } if (module.$$autoload) { for (constant in module.$$autoload) { constants[constant] = true; } } } return Object.keys(constants); } end # Remove a constant from a cref. def self.const_remove(cref, name) %x{ Opal.const_cache_version++; if (cref.$$const[name] != null) { var old = cref.$$const[name]; delete cref.$$const[name]; return old; } if (cref.$$autoload && cref.$$autoload[name]) { delete cref.$$autoload[name]; return nil; } $raise(Opal.NameError, "constant "+cref+"::"+cref.$name()+" not defined"); } end # Generates a function that is a curried const_get_relative. def self.const_get_relative_factory(nesting) %x{ return function(name, skip_missing) { return Opal.$$(nesting, name, skip_missing); } } end %x{ // For compatibility, let's copy properties from // earlier Opal.$$. for (var i in Opal.$$) { if ($has_own(Opal.$$, i)) { Opal.const_get_relative[i] = Opal.$$[i]; } } // Setup some shortcuts to reduce compiled size Opal.$$ = Opal.const_get_relative; Opal.$$$ = Opal.const_get_qualified; Opal.$r = Opal.const_get_relative_factory; } # Ancestor utilities # ------------------ def self.own_ancestors(mod) `mod.$$own_prepended_modules.concat([mod]).concat(mod.$$own_included_modules)` end # The Array of ancestors for a given module/class def self.ancestors(mod) %x{ if (!mod) { return []; } if (mod.$$ancestors_cache_version === Opal.const_cache_version) { return mod.$$ancestors; } var result = [], i, mods, length; for (i = 0, mods = Opal.own_ancestors(mod), length = mods.length; i < length; i++) { result.push(mods[i]); } if (mod.$$super) { for (i = 0, mods = $ancestors(mod.$$super), length = mods.length; i < length; i++) { result.push(mods[i]); } } mod.$$ancestors_cache_version = Opal.const_cache_version; mod.$$ancestors = result; return result; } end `var $ancestors = Opal.ancestors` def self.get_ancestors(obj) %x{ if (obj.hasOwnProperty('$$meta') && obj.$$meta !== null) { return $ancestors(obj.$$meta); } else { return $ancestors(obj.$$class); } } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/variables.rb
opal/runtime/variables.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true module ::Opal # Instance variables # ------------------ %x{ var reserved_ivar_names = [ // properties "constructor", "displayName", "__count__", "__noSuchMethod__", "__parent__", "__proto__", // methods "hasOwnProperty", "valueOf" ]; } # Get the ivar name for a given name. # Mostly adds a trailing $ to reserved names. def self.ivar(name = undefined) %x{ if (reserved_ivar_names.indexOf(name) !== -1) { name += "$"; } return name; } end # Iterate over every instance variable and call func for each one # giving name of the ivar and optionally the property descriptor. def self.each_ivar(obj = undefined, func = undefined) %x{ var own_props = Object.keys(obj), own_props_length = own_props.length, i, prop; for (i = 0; i < own_props_length; i++) { prop = own_props[i]; if (prop[0] === '$') continue; func(prop); } } end # Global variables # ---------------- # Globals table `var $gvars = Opal.gvars = {}` def self.alias_gvar(new_name = undefined, old_name = undefined) %x{ Object.defineProperty($gvars, new_name, { configurable: true, enumerable: true, get: function() { return $gvars[old_name]; }, set: function(new_value) { $gvars[old_name] = new_value; } }); } nil end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/array.rb
opal/runtime/array.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: raise module ::Opal # Helpers for implementing multiple assignment # Our code for extracting the values and assigning them only works if the # return value is a JS array. # So if we get an Array subclass, extract the wrapped JS array from it # Used for: a, b = something (no splat) def self.to_ary(value) %x{ if (value.$$is_array) { return value; } else if (value['$respond_to?']('to_ary', true)) { var ary = value.$to_ary(); if (ary === nil) { return [value]; } else if (ary.$$is_array) { return ary; } else { $raise(Opal.TypeError, "Can't convert " + value.$$class + " to Array (" + value.$$class + "#to_ary gives " + ary.$$class + ")"); } } else { return [value]; } } end # Used for: a, b = *something (with splat) def self.to_a(value) %x{ if (value.$$is_array) { // A splatted array must be copied return value.slice(); } else if (value['$respond_to?']('to_a', true)) { var ary = value.$to_a(); if (ary === nil) { return [value]; } else if (ary.$$is_array) { return ary; } else { $raise(Opal.TypeError, "Can't convert " + value.$$class + " to Array (" + value.$$class + "#to_a gives " + ary.$$class + ")"); } } else { return [value]; } } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/bridge.rb
opal/runtime/bridge.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: raise, prop, set_proto module ::Opal # For performance, some core Ruby classes are toll-free bridged to their # native JavaScript counterparts (e.g. a Ruby Array is a JavaScript Array). # # This method is used to setup a native constructor (e.g. Array), to have # its prototype act like a normal Ruby class. Firstly, a new Ruby class is # created using the native constructor so that its prototype is set as the # target for the new class. Note: all bridged classes are set to inherit # from Object. # # Example: # # Opal.bridge(self, Function); # # @param klass [Class] the Ruby class to bridge # @param constructor [JS.Function] native JavaScript constructor to use # @return [Class] returns the passed Ruby class # def self.bridge(native_klass, klass) %x{ if (native_klass.hasOwnProperty('$$bridge')) { $raise(Opal.ArgumentError, "already bridged"); } // constructor is a JS function with a prototype chain like: // - constructor // - super // // What we need to do is to inject our class (with its prototype chain) // between constructor and super. For example, after injecting ::Object // into JS String we get: // // - constructor (window.String) // - Opal.Object // - Opal.Kernel // - Opal.BasicObject // - super (window.Object) // - null // $prop(native_klass, '$$bridge', klass); // native_klass may be a subclass of a subclass of a ... so look for either // Object.prototype in its prototype chain and inject there or inject at the // end of the chain. Also, there is a chance we meet some Ruby Class on the // way, if a bridged class has been subclassed or its protype has been // otherwise modified. Then we assume that the prototype is already modified // correctly and we dont need to inject anything. let prototype = native_klass.prototype, next_prototype; while (true) { if (prototype.$$bridge || prototype.$$class || prototype.$$is_class || prototype.$$module || prototype.$$is_module) { // hit a bridged class, a Ruby Class or Module break; } next_prototype = Object.getPrototypeOf(prototype); if (next_prototype === Object.prototype || !next_prototype) { // found the right spot, inject! $set_proto(prototype, (klass.$$super || Opal.Object).$$prototype); break; } prototype = next_prototype; } $prop(klass, '$$prototype', native_klass.prototype); $prop(klass.$$prototype, '$$class', klass); $prop(klass, '$$constructor', native_klass); $prop(klass, '$$bridge', true); } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/irb.rb
opal/runtime/irb.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: raise, slice, splice, has_own module ::Opal # Run in WebTools console with: Opal.irb(c => eval(c)) def self.irb(fun) ::Binding.new(fun).irb end def self.load_parser ::Opal::IRB.ensure_loaded('opal-parser') end %x{ if (typeof Opal.eval === 'undefined') { #{ def self.eval(str) `Opal.load_parser()` `Opal.eval(str)` end } } } %x{ if (typeof Opal.compile === 'undefined') { #{ def self.compile(str, options) `Opal.load_parser()` `Opal.compile(str, options)` end } } } end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/helpers.rb
opal/runtime/helpers.rb
# helpers: type_error, coerce_to # backtick_javascript: true # use_strict: true module ::Opal def self.coerce_to!(object, type, method, *args) coerced = `$coerce_to(object, type, method, args)` unless type === coerced ::Kernel.raise `$type_error(object, type, method, coerced)` end coerced end def self.coerce_to?(object, type, method, *args) return unless object.respond_to? method coerced = `$coerce_to(object, type, method, args)` return if coerced.nil? unless type === coerced ::Kernel.raise `$type_error(object, type, method, coerced)` end coerced end def self.try_convert(object, type, method) return object if type === object if object.respond_to? method object.__send__ method end end def self.compare(a, b) compare = a <=> b if `compare === nil` ::Kernel.raise ::ArgumentError, "comparison of #{a.class} with #{b.class} failed" end compare end def self.destructure(args) %x{ if (args.length == 1) { return args[0]; } else if (args.$$is_array) { return args; } else { var args_ary = new Array(args.length); for(var i = 0, l = args_ary.length; i < l; i++) { args_ary[i] = args[i]; } return args_ary; } } end def self.respond_to?(obj, method, include_all = false) %x{ if (obj == null || !obj.$$class) { return false; } } obj.respond_to?(method, include_all) end def self.instance_variable_name!(name) name = ::Opal.coerce_to!(name, ::String, :to_str) unless `/^@[a-zA-Z_][a-zA-Z0-9_]*?$/.test(name)` ::Kernel.raise ::NameError.new("'#{name}' is not allowed as an instance variable name", name) end name end def self.class_variable_name!(name) name = ::Opal.coerce_to!(name, ::String, :to_str) if `name.length < 3 || name.slice(0,2) !== '@@'` ::Kernel.raise ::NameError.new("`#{name}' is not allowed as a class variable name", name) end name end def self.const_name?(const_name) %x{ if (typeof const_name !== 'string') { #{const_name = ::Opal.coerce_to!(const_name, ::String, :to_str)} } return #{const_name}[0] === #{const_name}[0].toUpperCase() } end def self.const_name!(const_name) const_name = ::Opal.coerce_to!(const_name, ::String, :to_str) if defined? ::String %x{ if (!const_name || const_name.length === 0 || const_name[0] != const_name[0].toUpperCase()) { #{raise ::NameError, "wrong constant name #{const_name}"} } } const_name end # @private # Mark some methods as pristine in order to apply optimizations when they # are still in their original form. This could probably be moved to # the `Opal.def()` JS API, but for now it will stay manual. # # @example # # Opal.pristine Array, :allocate, :copy_instance_variables, :initialize_dup # # class Array # def dup # %x{ # if ( # self.$allocate.$$pristine && # self.$copy_instance_variables.$$pristine && # self.$initialize_dup.$$pristine # ) return self.slice(0); # } # # super # end # end # # @param owner_class [Class] the class owning the methods # @param method_names [Array<Symbol>] the list of methods names to mark # @return [nil] def self.pristine(owner_class, *method_names) %x{ var method_name, method; for (var i = method_names.length - 1; i >= 0; i--) { method_name = method_names[i]; method = owner_class.$$prototype[Opal.jsid(method_name)]; if (method && !method.$$stub) { method.$$pristine = true; } } } nil end `var inspect_stack = []` # Performs a safe call to inspect for any value, whether # native or Opal-wrapped. # # @param value [Object] # @return [String] def self.inspect(value = undefined) # We use an `#inspect` name, but when someone calls just # `Opal.inspect` we should return "Opal". return 'Opal' if `arguments.length == 0` `var pushed = false` begin %x{ if (value === null) { // JS null value return 'null'; } else if (value === undefined) { // JS undefined value return 'undefined'; } else if (typeof value.$$class === 'undefined') { // JS object / other value that is not bridged return Object.prototype.toString.apply(value); } else if (typeof value.$inspect !== 'function' || value.$inspect.$$stub) { // BasicObject and friends return #{"#<#{`value.$$class`}:0x#{value.__id__.to_s(16)}>"} } else if (inspect_stack.indexOf(#{value.__id__}) !== -1) { // inspect recursing inside inspect to find out about the // same object return #{"#<#{`value.$$class`}:0x#{value.__id__.to_s(16)}>"} } else { // anything supporting Opal inspect_stack.push(#{value.__id__}); pushed = true; return value.$inspect(); } } nil rescue ::Exception => e # rubocop:disable Lint/RescueException "#<#{`value.$$class`}:0x#{value.__id__.to_s(16)}>" ensure `if (pushed) inspect_stack.pop()` end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/freeze.rb
opal/runtime/freeze.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: prop, raise, uid, return_val module ::Opal # Support for #freeze # ------------------- # Common #freeze runtime support def self.freeze(obj) %x{ $prop(obj, "$$frozen", true); // set $$id if (!obj.hasOwnProperty('$$id')) { $prop(obj, '$$id', $uid()); } if (obj.hasOwnProperty('$$meta')) { // freeze $$meta if it has already been set obj.$$meta.$freeze(); } else { // ensure $$meta can be set lazily, $$meta is frozen when set in runtime.js $prop(obj, '$$meta', null); } // $$comparable is used internally and set multiple times // defining it before sealing ensures it can be modified later on if (!obj.hasOwnProperty('$$comparable')) { $prop(obj, '$$comparable', null); } // seal the Object Object.seal(obj); return obj; } end # Freeze props, make setters of instance variables throw FrozenError def self.freeze_props(obj) %x{ var own_props = Object.keys(obj), own_props_length = own_props.length, i, prop, desc, dp_template = { get: null, set: function (_val) { Opal.deny_frozen_access(obj); }, enumerable: true }; for (i = 0; i < own_props_length; i++) { prop = own_props[i]; if (prop[0] === '$') continue; desc = Object.getOwnPropertyDescriptor(obj, prop); if (desc && desc.writable) { dp_template.get = $return_val(desc.value); Object.defineProperty(obj, prop, dp_template); } } } end # Helper that can be used from methods def self.deny_frozen_access(obj) %x{ if (obj.$$frozen) $raise(Opal.FrozenError, "can't modify frozen " + (obj.$class()) + ": " + (obj), new Map([["receiver", obj]])); } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/send.rb
opal/runtime/send.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: apply_blockopts, jsid, raise, prepend_ary, get_ancestors module ::Opal # Calls passed method on a ruby object with arguments and block: # # Can take a method or a method name. # # 1. When method name gets passed it invokes it by its name # and calls 'method_missing' when object doesn't have this method. # Used internally by Opal to invoke method that takes a block or a splat. # 2. When method (i.e. method body) gets passed, it doesn't trigger 'method_missing' # because it doesn't know the name of the actual method. # Used internally by Opal to invoke 'super'. # # @example # var my_array = [1, 2, 3, 4] # Opal.send(my_array, 'length') # => 4 # Opal.send(my_array, my_array.$length) # => 4 # # Opal.send(my_array, 'reverse!') # => [4, 3, 2, 1] # Opal.send(my_array, my_array['$reverse!']') # => [4, 3, 2, 1] # # @param recv [Object] ruby object # @param method [Function, String] method body or name of the method # @param args [Array] arguments that will be passed to the method call # @param block [Function] ruby block # @param blockopts [Object, Number] optional properties to set on the block # @return [Object] returning value of the method call def self.send(recv, method, args, block, blockopts) %x{ var body; if (typeof(method) === 'function') { body = method; method = null; } else if (typeof(method) === 'string') { body = recv[$jsid(method)]; } else { $raise(Opal.NameError, "Passed method should be a string or a function"); } return Opal.send2(recv, body, method, args, block, blockopts); } end def self.send2(recv, body, method, args, block, blockopts) %x{ if (body == null && method != null && recv.$method_missing) { body = recv.$method_missing; args = $prepend_ary(method, args); } $apply_blockopts(block, blockopts); if (typeof block === 'function') body.$$p = block; return body.apply(recv, args); } end def self.refined_send(refinement_groups, recv, method, args, block, blockopts) %x{ var i, j, k, ancestors, ancestor, refinements, refinement, refine_modules, refine_module, body; ancestors = $get_ancestors(recv); // For all ancestors that there are, starting from the closest to the furthest... for (i = 0; i < ancestors.length; i++) { ancestor = Opal.id(ancestors[i]); // For all refinement groups there are, starting from the closest scope to the furthest... for (j = 0; j < refinement_groups.length; j++) { refinements = refinement_groups[j]; // For all refinements there are, starting from the last `using` call to the furthest... for (k = refinements.length - 1; k >= 0; k--) { refinement = refinements[k]; if (typeof refinement.$$refine_modules === 'undefined') continue; // A single module being given as an argument of the `using` call contains multiple // refinement modules refine_modules = refinement.$$refine_modules; // Does this module refine a given call for a given ancestor module? if (typeof refine_modules[ancestor] === 'undefined') continue; refine_module = refine_modules[ancestor]; // Does this module define a method we want to call? if (typeof refine_module.$$prototype[$jsid(method)] !== 'undefined') { body = refine_module.$$prototype[$jsid(method)]; return Opal.send2(recv, body, method, args, block, blockopts); } } } } return Opal.send(recv, method, args, block, blockopts); } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/exception.rb
opal/runtime/exception.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: gvars, Kernel, slice, truthy module ::Opal # A helper function for raising things, that gracefully degrades if necessary # functionality is not yet loaded. def self.raise(klass, message) %x{ // Raise Exception, so we can know that something wrong is going on. if (!klass) klass = Opal.Exception || Error; if ($Kernel && $Kernel.$raise) { if (arguments.length > 2) { $Kernel.$raise(klass.$new.apply(klass, $slice(arguments, 1))); } else { $Kernel.$raise(klass, message); } } else if (!klass.$new) { throw new klass(message); } else { throw klass.$new(message); } } end `var $raise = Opal.raise` # keeps track of exceptions for $! `Opal.exceptions = []` # @private # Pops an exception from the stack and updates `$!`. def self.pop_exception(rescued_exception) %x{ var exception = Opal.exceptions.pop(); if (exception === rescued_exception) { // Current $! is raised in the rescue block, so we don't update it } else if (exception) { $gvars["!"] = exception; } else { $gvars["!"] = nil; } } end def self.type_error(object, type, method, coerced) %x{ object = object.$$class; if (coerced && method) { coerced = coerced.$$class; $raise(Opal.TypeError, "can't convert " + object + " into " + type + " (" + object + "#" + method + " gives " + coerced + ")" ) } else { $raise(Opal.TypeError, "no implicit conversion of " + object + " into " + type ) } } end `TypeError.$$super = Error` # Finds the corresponding exception match in candidates. Each candidate can # be a value, or an array of values. Returns null if not found. def self.rescue(exception, candidates) %x{ for (var i = 0; i < candidates.length; i++) { var candidate = candidates[i]; if (candidate.$$is_array) { var result = Opal.rescue(exception, candidate); if (result) { return result; } } else if ((Opal.Opal.Raw && candidate === Opal.Opal.Raw.Error) || candidate['$==='](exception)) { return candidate; } } return null; } end # Define a "$@" global variable, which would compute and return a backtrace on demand. %x{ Object.defineProperty($gvars, "@", { enumerable: true, configurable: true, get: function() { if ($truthy($gvars["!"])) return $gvars["!"].$backtrace(); return nil; }, set: function(bt) { if ($truthy($gvars["!"])) $gvars["!"].$set_backtrace(bt); else $raise(Opal.ArgumentError, "$! not set"); } }); } # Closures # -------- def self.thrower(type) %x{ var thrower = { $thrower_type: type, $throw: function(value, called_from_lambda) { if (value == null) value = nil; if (this.is_orphan && !called_from_lambda) { $raise(Opal.LocalJumpError, 'unexpected ' + type, value, type.$to_sym()); } this.$v = value; throw this; }, is_orphan: false } return thrower; } end `Opal.t_eval_return = Opal.thrower("return")` end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/class.rb
opal/runtime/class.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: raise, prop, Object, BasicObject, Class, Module, set_proto, allocate_class, const_get_name, const_set, has_own, ancestors, jsid module ::Opal def self.find_existing_class(scope, name) %x{ // Try to find the class in the current scope var klass = $const_get_name(scope, name); // If the class exists in the scope, then we must use that if (klass) { // Make sure the existing constant is a class, or raise error if (!klass.$$is_class) { $raise(Opal.TypeError, name + " is not a class"); } return klass; } } end def self.ensure_superclass_match(klass, superclass) %x{ if (klass.$$super !== superclass) { $raise(Opal.TypeError, "superclass mismatch for class " + klass.$$name); } } end def self.klass(scope, superclass, name) %x{ var bridged; if (scope == null || scope === '::') { // Global scope scope = $Object; } else if (!scope.$$is_class && !scope.$$is_module) { // Scope is an object, use its class scope = scope.$$class; } // If the superclass is not an Opal-generated class then we're bridging a native JS class if ( superclass != null && (!superclass.hasOwnProperty || ( superclass.hasOwnProperty && !superclass.hasOwnProperty('$$is_class') )) ) { if (superclass.constructor && superclass.constructor.name == "Function") { bridged = superclass; superclass = $Object; } else { $raise(Opal.TypeError, "superclass must be a Class (" + ( (superclass.constructor && (superclass.constructor.name || superclass.constructor.$$name)) || typeof(superclass) ) + " given)"); } } var klass = Opal.find_existing_class(scope, name); if (klass != null) { if (superclass) { // Make sure existing class has same superclass Opal.ensure_superclass_match(klass, superclass); } } else { // Class doesn't exist, create a new one with given superclass... // Not specifying a superclass means we can assume it to be Object if (superclass == null) { superclass = $Object; } // Create the class object (instance of Class) klass = $allocate_class(name, superclass); $const_set(scope, name, klass); // Call .inherited() hook with new class on the superclass if (superclass.$inherited) { superclass.$inherited(klass); } if (bridged) { Opal.bridge(bridged, klass); } } if (Opal.trace_class) { Opal.invoke_tracers_for('class', klass); } return klass; } end # Class variables # --------------- # Returns an object containing all pairs of names/values # for all class variables defined in provided +module+ # and its ancestors. # # @param module [Module] # @return [Object] def self.class_variables(mod) %x{ var ancestors = $ancestors(mod), i, length = ancestors.length, result = {}; for (i = length - 1; i >= 0; i--) { var ancestor = ancestors[i]; for (var cvar in ancestor.$$cvars) { result[cvar] = ancestor.$$cvars[cvar]; } } return result; } end # Sets class variable with specified +name+ to +value+ # in provided +module+ # # @param module [Module] # @param name [String] # @param value [Object] def self.class_variable_set(mod, name, value) %x{ var ancestors = $ancestors(mod), i, length = ancestors.length; for (i = length - 2; i >= 0; i--) { var ancestor = ancestors[i]; if ($has_own(ancestor.$$cvars, name)) { ancestor.$$cvars[name] = value; return value; } } mod.$$cvars[name] = value; return value; } end # Gets class variable with specified +name+ from provided +module+ # # @param module [Module] # @param name [String] def self.class_variable_get(mod, name, tolerant) %x{ if ($has_own(mod.$$cvars, name)) return mod.$$cvars[name]; var ancestors = $ancestors(mod), i, length = ancestors.length; for (i = 0; i < length; i++) { var ancestor = ancestors[i]; if ($has_own(ancestor.$$cvars, name)) { return ancestor.$$cvars[name]; } } if (!tolerant) $raise(Opal.NameError, 'uninitialized class variable '+name+' in '+mod.$name()); return nil; } end # Singleton classes # ----------------- # Return the singleton class for the passed object. # # If the given object alredy has a singleton class, then it will be stored on # the object as the `$$meta` property. If this exists, then it is simply # returned back. # # Otherwise, a new singleton object for the class or object is created, set on # the object at `$$meta` for future use, and then returned. # # @param object [Object] the ruby object # @return [Class] the singleton class for object def self.get_singleton_class(object) %x{ if (object.$$is_number) { $raise(Opal.TypeError, "can't define singleton"); } if (object.$$meta) { return object.$$meta; } if (object.hasOwnProperty('$$is_class')) { return Opal.build_class_singleton_class(object); } else if (object.hasOwnProperty('$$is_module')) { return Opal.build_module_singleton_class(object); } else { return Opal.build_object_singleton_class(object); } } end # Class definition helper used by the compiler # # Defines or fetches a class (like `Opal.klass`) and, if a body callback is # provided, evaluates the class body via that callback passing `self` and the # updated `$nesting` array. The return value of the callback becomes the # value of the class expression; when no callback is given the expression # evaluates to `nil` (to match Ruby semantics for `class X; end`). def self.klass_def(scope, superclass, name, body, parent_nesting) %x{ var klass = Opal.klass(scope, superclass, name); if (body != null) { var ret; if (body.length == 1) { ret = body(klass); } else { ret = body(klass, [klass].concat(parent_nesting)); } if (Opal.trace_end) { if (typeof Promise !== 'undefined' && ret && typeof ret.then === 'function') { return ret.then(function(value){ Opal.invoke_tracers_for('end', klass); return value; }); } else { Opal.invoke_tracers_for('end', klass); } } return ret; } else { if (Opal.trace_end) { Opal.invoke_tracers_for('end', klass); } } return nil; } end # Helper to set $$meta on klass, module or instance def self.set_meta(obj, meta) %x{ if (obj.hasOwnProperty('$$meta')) { obj.$$meta = meta; } else { $prop(obj, '$$meta', meta); } if (obj.$$frozen) { // If a object is frozen (sealed), freeze $$meta too. // No need to inject $$meta.$$prototype in the prototype chain, // as $$meta cannot be modified anyway. obj.$$meta.$freeze(); } else { $set_proto(obj, meta.$$prototype); } } end # Build the singleton class for an existing class. Class object are built # with their singleton class already in the prototype chain and inheriting # from their superclass object (up to `Class` itself). # # NOTE: Actually in MRI a class' singleton class inherits from its # superclass' singleton class which in turn inherits from Class. # # @param klass [Class] # @return [Class] def self.build_class_singleton_class(klass) %x{ if (klass.$$meta) { return klass.$$meta; } // The singleton_class superclass is the singleton_class of its superclass; // but BasicObject has no superclass (its `$$super` is null), thus we // fallback on `Class`. var superclass = klass === $BasicObject ? $Class : Opal.get_singleton_class(klass.$$super); var meta = $allocate_class(null, superclass, true); $prop(meta, '$$is_singleton', true); $prop(meta, '$$singleton_of', klass); Opal.set_meta(klass, meta); // Restoring ClassName.class $prop(klass, '$$class', $Class); return meta; } end def self.build_module_singleton_class(mod) %x{ if (mod.$$meta) { return mod.$$meta; } var meta = $allocate_class(null, $Module, true); $prop(meta, '$$is_singleton', true); $prop(meta, '$$singleton_of', mod); Opal.set_meta(mod, meta); // Restoring ModuleName.class $prop(mod, '$$class', $Module); return meta; } end # Build the singleton class for a Ruby (non class) Object. # # @param object [Object] # @return [Class] def self.build_object_singleton_class(object) %x{ var superclass = object.$$class, klass = $allocate_class(nil, superclass, true); $prop(klass, '$$is_singleton', true); $prop(klass, '$$singleton_of', object); delete klass.$$prototype.$$class; Opal.set_meta(object, klass); return klass; } end # Typechecking and typecasting # ---------------------------- def self.coerce_to(object, type, method, args) %x{ var body; if (method === 'to_int' && type === Opal.Integer && object.$$is_number) return object < 0 ? Math.ceil(object) : Math.floor(object); if (method === 'to_str' && type === Opal.String && object.$$is_string) return object; if (Opal.is_a(object, type)) return object; // Fast path for the most common situation if ((object['$respond_to?'].$$pristine && object.$method_missing.$$pristine) || object['$respond_to?'].$$stub) { body = object[$jsid(method)]; if (body == null || body.$$stub) Opal.type_error(object, type); return body.apply(object, args); } if (!object['$respond_to?'](method)) { Opal.type_error(object, type); } if (args == null) args = []; return Opal.send(object, method, args); } end def self.respond_to(obj, jsid, include_all) %x{ if (obj == null || !obj.$$class) return false; include_all = !!include_all; var body = obj[jsid]; if (obj['$respond_to?'].$$pristine) { if (typeof(body) === "function" && !body.$$stub) { return true; } if (!obj['$respond_to_missing?'].$$pristine) { return Opal.send(obj, obj['$respond_to_missing?'], [jsid.substr(1), include_all]); } } else { return Opal.send(obj, obj['$respond_to?'], [jsid.substr(1), include_all]); } } end # rubocop:disable Naming/PredicatePrefix def self.is_a(object, klass) %x{ if (klass != null && object.$$meta === klass || object.$$class === klass) { return true; } if (object.$$is_number && klass.$$is_number_class) { return (klass.$$is_integer_class) ? (object % 1) === 0 : true; } var ancestors = $ancestors(object.$$is_class ? Opal.get_singleton_class(object) : (object.$$meta || object.$$class)); return ancestors.indexOf(klass) !== -1; } end # rubocop:enable Naming/PredicatePrefix end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/string.rb
opal/runtime/string.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: raise, prop, Object module ::Opal # We use a helper to create new Strings, globally, so that it # will be easer to change that later on to a mutable string class. # Also this helper always sets a encoding. If encoding is not # provided, "UTF-8" will be used. # @returns a new String object with encoding set. def self.str(str = undefined, encoding = undefined) %x{ if (!encoding || encoding === nil) encoding = "UTF-8"; str = Opal.set_encoding(new String(str), encoding); str.internal_encoding = str.encoding; return str; } end # String#+ might be triggered early by a call $dstr below, so provide a solution until String class is fully loaded. `String.prototype["$+"] = function(other) { return this + other; }` # Helper for dynamic strings like "menu today: #{meal[:name]} for only #{meal[:price]}" def self.dstr %x{ let res = arguments[0]; if (arguments.length > 1) { for (let i = 1; i < arguments.length; i++) { res = res["$+"](arguments[i]); } } else if (typeof res === "string") { res = Opal.str(res); } return res; } end # Provide the encoding register with a default "UTF-8" encoding, because # its used from the start and will be raplaced by the real UTF-8 encoding # when 'corelib/string/encoding' is loaded. `Opal.encodings = { __proto__: null, "UTF-8": { name: "UTF-8" }}` # Sets the encoding on a string, will treat string literals as frozen strings # raising a FrozenError. # # @param str [String] the string on which the encoding should be set # @param name [String] the canonical name of the encoding # @param type [String] possible values are either `"encoding"`, `"internal_encoding"`, or `undefined def self.set_encoding(str = undefined, name = undefined, type = undefined) %x{ if (typeof type === "undefined") type = "encoding"; if (typeof str === 'string' || str.$$frozen === true) $raise(Opal.FrozenError, "can't modify frozen String"); let encoding = Opal.find_encoding(name); if (encoding === str[type]) { return str; } str[type] = encoding; return str; } end # Fetches the encoding for the given name or raises ArgumentError. def self.find_encoding(name = undefined) %x{ let register = Opal.encodings; let encoding = register[name] || register[name.toUpperCase()]; if (!encoding) $raise(Opal.ArgumentError, "unknown encoding name - " + name); return encoding; } end def self.fallback_to_s(obj = undefined) %x{`#<${obj.$$class.$to_s()}:0x${Opal.id(obj).toString(16)}>`} end def self.to_s(obj = undefined) %x{ // A case for someone calling Opal.to_s if (arguments.length == 0) return "Opal"; var stringified; if (obj == null) { return "`"+String(obj)+"`"; } else if (typeof obj === 'string' || (typeof obj === 'object' && obj.$$is_string)) { return obj; } else if (obj.$to_s != null && !obj.$to_s.$$stub) { stringified = obj.$to_s(); if (typeof stringified !== 'string' && !stringified.$$is_string) { stringified = Opal.fallback_to_s(obj); } return stringified; } else { return obj.toString(); } } end # Forward .toString() to #to_s %x{ $prop($Object.$$prototype, 'toString', function() { var to_s = this.$to_s(); if (to_s.$$is_string && typeof(to_s) === 'object') { // a string created using new String('string') return to_s.valueOf(); } else { return to_s; } }); } end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/op_helpers.rb
opal/runtime/op_helpers.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: truthy, deny_frozen_access # rubocop:disable Layout/EmptyLineBetweenDefs module ::Opal # Operator helpers # ---------------- %x{ function are_both_numbers(l,r) { return typeof(l) === 'number' && typeof(r) === 'number' } } def self.rb_plus(l, r) = `are_both_numbers(l,r) ? l + r : l['$+'](r)` def self.rb_minus(l, r) = `are_both_numbers(l,r) ? l - r : l['$-'](r)` def self.rb_times(l, r) = `are_both_numbers(l,r) ? l * r : l['$*'](r)` def self.rb_divide(l, r) = `are_both_numbers(l,r) ? l / r : l['$/'](r)` def self.rb_lt(l, r) = `are_both_numbers(l,r) ? l < r : l['$<'](r)` def self.rb_gt(l, r) = `are_both_numbers(l,r) ? l > r : l['$>'](r)` def self.rb_le(l, r) = `are_both_numbers(l,r) ? l <= r : l['$<='](r)` def self.rb_ge(l, r) = `are_both_numbers(l,r) ? l >= r : l['$>='](r)` # Optimized helpers for calls like $truthy((a)['$==='](b)) -> $eqeqeq(a, b) %x{ function are_both_numbers_or_strings(lhs, rhs) { return (typeof lhs === 'number' && typeof rhs === 'number') || (typeof lhs === 'string' && typeof rhs === 'string'); } } def self.eqeq(lhs, rhs) = `are_both_numbers_or_strings(lhs,rhs) ? lhs === rhs : $truthy((lhs)['$=='](rhs))` def self.eqeqeq(lhs, rhs) = `are_both_numbers_or_strings(lhs,rhs) ? lhs === rhs : $truthy((lhs)['$==='](rhs))` def self.neqeq(lhs, rhs) = `are_both_numbers_or_strings(lhs,rhs) ? lhs !== rhs : $truthy((lhs)['$!='](rhs))` def self.not(arg) %x{ if (undefined === arg || null === arg || false === arg || nil === arg) return true; if (true === arg || arg['$!'].$$pristine) return false; return $truthy(arg['$!']()); } end # Shortcuts - optimized function generators for simple kinds of functions def self.return_self = `this` def self.return_ivar(ivar) %x{ return function() { if (this[ivar] == null) { return nil; } return this[ivar]; } } end def self.assign_ivar(ivar) %x{ return function(val) { $deny_frozen_access(this); return this[ivar] = val; } } end def self.assign_ivar_val(ivar, static_val) %x{ return function() { $deny_frozen_access(this); return this[ivar] = static_val; } } end # Arrays of size > 32 elements that contain only strings, # symbols, integers and nils are compiled as a self-extracting # string. def self.large_array_unpack(str) %x{ var array = str.split(","), length = array.length, i; for (i = 0; i < length; i++) { switch(array[i][0]) { case undefined: array[i] = nil break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': array[i] = +array[i]; } } return array; } end end ::Opal # rubocop:enable Layout/EmptyLineBetweenDefs
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/misc.rb
opal/runtime/misc.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: return_val, Object, gvars module ::Opal # Create a new range instance with first and last values, and whether the # range excludes the last value. def self.range(first, last, exc) %x{ var range = new Opal.Range(); range.begin = first; range.end = last; range.excl = exc; return range; } end # Exit function, this should be replaced by platform specific implementation # (See nodejs and chrome for examples) def self.exit(status) %x{ if ($gvars.DEBUG) console.log('Exited with status '+status); } end # top is the main object. It is a `self` in a top level of a Ruby program %x{ Opal.top.$to_s = Opal.top.$inspect = $return_val('main'); Opal.top.$define_method = top_define_method; // Foward calls to define_method on the top object to Object function top_define_method() { var block = top_define_method.$$p; top_define_method.$$p = null; return Opal.send($Object, 'define_method', arguments, block) }; } end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/runtime.rb
opal/runtime/runtime.rb
require 'runtime/boot' require 'runtime/variables' require 'runtime/exception' require 'runtime/freeze' require 'runtime/op_helpers' require 'runtime/method_missing' require 'runtime/const' require 'runtime/module' require 'runtime/class' require 'runtime/method' require 'runtime/proc' require 'runtime/send' require 'runtime/array' require 'runtime/hash' require 'runtime/string' require 'runtime/regexp' require 'runtime/bridge' require 'runtime/misc' require 'runtime/helpers'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/regexp.rb
opal/runtime/regexp.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true module ::Opal # Escape Regexp special chars letting the resulting string be used to build # a new Regexp. def self.escape_regexp(str) `Opal.escape_metacharacters(str.replace(/([-[\]\/{}()*+?.^$\\| ])/g, '\\$1'))` end def self.escape_metacharacters(str) %x{ return str.replace(/[\n]/g, '\\n') .replace(/[\r]/g, '\\r') .replace(/[\f]/g, '\\f') .replace(/[\t]/g, '\\t'); } end # Create a global Regexp from a RegExp object and cache the result # on the object itself ($$g attribute). def self.global_regexp(pattern) %x{ if (pattern.global) { return pattern; // RegExp already has the global flag } if (pattern.$$g == null) { pattern.$$g = new RegExp(pattern.source, 'g' + pattern.flags); } else { pattern.$$g.lastIndex = null; // reset lastIndex property } return pattern.$$g; } end # Transform a regular expression from Ruby syntax to JS syntax. def self.transform_regexp(regexp, flags) Opal::RegexpTranspiler.transform_regexp(regexp, flags) end # Combine multiple regexp parts together def self.regexp(parts, flags) %x{ var part; if (flags == null) flags = ''; var ignoreCase = flags.includes('i'); for (var i = 0, ii = parts.length; i < ii; i++) { part = parts[i]; if (part instanceof RegExp) { if (part.ignoreCase !== ignoreCase) Opal.Kernel.$warn( "ignore case doesn't match for " + part.source.$inspect(), new Map([['uplevel', 1]]) ) part = part.$$source != null ? part.$$source : part.source; } if (part == '') part = '(?:)'; parts[i] = part; } parts = parts.join(''); parts = Opal.escape_metacharacters(parts); var output = Opal.transform_regexp(parts, flags); var regexp = new RegExp(output[0], output[1]); if (parts != output[0]) regexp.$$source = parts if (flags != output[1]) regexp.$$options = flags; return regexp; } end # Regexp has been transformed, so let's annotate the original regexp def self.annotate_regexp(regexp, source, options) %x{ regexp.$$source = source; regexp.$$options = options; return regexp; } end # Annotated empty regexp def self.empty_regexp(flags) `Opal.annotate_regexp(new RegExp(/(?:)/, flags), '')` end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/module.rb
opal/runtime/module.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: prop, raise, Object, allocate_module, const_get_name, const_lookup_ancestors, ancestors, const_set, set_proto, has_own module ::Opal %x{ // TracePoint support // ------------------ // // Support for `TracePoint.trace(:class) do ... end` and `:end` Opal.trace_class = false; Opal.tracers_for_class = []; Opal.trace_end = false; Opal.tracers_for_end = []; } # Unified tracer invoker for TracePoint events backed by Opal.tracers_for_<event> # @param event [String,Symbol] e.g., 'class' or 'end' # @param klass_or_module [Module,Class] def self.invoke_tracers_for(event, klass_or_module) %x{ var key = 'tracers_for_' + event, list = Opal[key] || [], i, ii, tracer; for(i = 0, ii = list.length; i < ii; i++) { tracer = list[i]; // annotate current event for the callback tracer.trace_object = klass_or_module; tracer.block.$call(tracer); } } end # Module definition helper used by the compiler # # Defines or fetches a module (like `Opal.module`) and, if a body callback is # provided, evaluates the module body via that callback passing `self` and the # updated `$nesting` array. The return value of the callback becomes the # value of the module expression; when no callback is given the expression # evaluates to `nil`. def self.module_def(scope, name, body, parent_nesting) %x{ var module = Opal.module(scope, name); if (body != null) { var ret; if (body.length == 1) { ret = body(module); } else { ret = body(module, [module].concat(parent_nesting)); } if (Opal.trace_end) { if (typeof Promise !== 'undefined' && ret && typeof ret.then === 'function') { return ret.then(function(value){ Opal.invoke_tracers_for('end', module); return value; }); } else { Opal.invoke_tracers_for('end', module); } } return ret; } else { if (Opal.trace_end) { Opal.invoke_tracers_for('end', module); } } return nil; } end def self.find_existing_module(scope, name) %x{ var module = $const_get_name(scope, name); if (module == null && scope === $Object) module = $const_lookup_ancestors($Object, name); if (module) { if (!module.$$is_module && module !== $Object) { $raise(Opal.TypeError, name + " is not a module"); } } return module; } end def self.module(scope, name) %x{ var module; if (scope == null || scope === '::') { // Global scope scope = $Object; } else if (!scope.$$is_class && !scope.$$is_module) { // Scope is an object, use its class scope = scope.$$class; } module = Opal.find_existing_module(scope, name); if (module == null) { // Module doesnt exist, create a new one... module = $allocate_module(name); $const_set(scope, name, module); } if (Opal.trace_class) { Opal.invoke_tracers_for('class', module); } return module; } end # Include & Prepend # ----------------- def self.is_root(proto) `proto.hasOwnProperty('$$iclass') && proto.hasOwnProperty('$$root')` end def self.own_included_modules(mod) %x{ var result = [], module, proto; if ($has_own(mod.$$prototype, '$$dummy')) { proto = Object.getPrototypeOf(mod.$$prototype.$$define_methods_on); } else { proto = Object.getPrototypeOf(mod.$$prototype); } while (proto) { if (proto.hasOwnProperty('$$class')) { // superclass break; } module = Opal.proto_to_module(proto); if (module) { result.push(module); } proto = Object.getPrototypeOf(proto); } return result; } end def self.own_prepended_modules(mod) %x{ var result = [], module, proto = Object.getPrototypeOf(mod.$$prototype); if (mod.$$prototype.hasOwnProperty('$$dummy')) { while (proto) { if (proto === mod.$$prototype.$$define_methods_on) { break; } module = Opal.proto_to_module(proto); if (module) { result.push(module); } proto = Object.getPrototypeOf(proto); } } return result; } end # The actual inclusion of a module into a class. # # ## Class `$$parent` and `iclass` # # To handle `super` calls, every class has a `$$parent`. This parent is # used to resolve the next class for a super call. A normal class would # have this point to its superclass. However, if a class includes a module # then this would need to take into account the module. The module would # also have to then point its `$$parent` to the actual superclass. We # cannot modify modules like this, because it might be included in more # then one class. To fix this, we actually insert an `iclass` as the class' # `$$parent` which can then point to the superclass. The `iclass` acts as # a proxy to the actual module, so the `super` chain can then search it for # the required method. # # @param module [Module] the module to include # @param includer [Module] the target class to include module into # @return [null] def self.append_features(mod, includer) %x{ var module_ancestors = $ancestors(mod); var iclasses = []; if (module_ancestors.indexOf(includer) !== -1) { $raise(Opal.ArgumentError, 'cyclic include detected'); } for (var i = 0, length = module_ancestors.length; i < length; i++) { var ancestor = module_ancestors[i], iclass = Opal.create_iclass(ancestor); $prop(iclass, '$$included', true); iclasses.push(iclass); } var includer_ancestors = $ancestors(includer), chain = Opal.chain_iclasses(iclasses), start_chain_after, end_chain_on; if (includer_ancestors.indexOf(mod) === -1) { // first time include // includer -> chain.first -> ...chain... -> chain.last -> includer.parent start_chain_after = includer.$$prototype; if ($has_own(start_chain_after, '$$dummy')) { start_chain_after = start_chain_after.$$define_methods_on; } end_chain_on = Object.getPrototypeOf(start_chain_after); } else { // The module has been already included, // we don't need to put it into the ancestors chain again, // but this module may have new included modules. // If it's true we need to copy them. // // The simplest way is to replace ancestors chain from // parent // | // `module` iclass (has a $$root flag) // | // ...previos chain of module.included_modules ... // | // "next ancestor" (has a $$root flag or is a real class) // // to // parent // | // `module` iclass (has a $$root flag) // | // ...regenerated chain of module.included_modules // | // "next ancestor" (has a $$root flag or is a real class) // // because there are no intermediate classes between `parent` and `next ancestor`. // It doesn't break any prototypes of other objects as we don't change class references. var parent = includer.$$prototype, module_iclass = Object.getPrototypeOf(parent); while (module_iclass != null) { if (module_iclass.$$module === mod && Opal.is_root(module_iclass)) { break; } parent = module_iclass; module_iclass = Object.getPrototypeOf(module_iclass); } if (module_iclass) { // module has been directly included var next_ancestor = Object.getPrototypeOf(module_iclass); // skip non-root iclasses (that were recursively included) while (next_ancestor.hasOwnProperty('$$iclass') && !Opal.is_root(next_ancestor)) { next_ancestor = Object.getPrototypeOf(next_ancestor); } start_chain_after = parent; end_chain_on = next_ancestor; } else { // module has not been directly included but was in ancestor chain because it was included by another module // include it directly start_chain_after = includer.$$prototype; end_chain_on = Object.getPrototypeOf(includer.$$prototype); } } $set_proto(start_chain_after, chain.first); $set_proto(chain.last, end_chain_on); // recalculate own_included_modules cache includer.$$own_included_modules = Opal.own_included_modules(includer); Opal.const_cache_version++; } end def self.prepend_features(mod, prepender) %x{ function flush_methods_in(mod) { var proto = mod.$$prototype, props = Object.getOwnPropertyNames(proto); for (var i = 0; i < props.length; i++) { var prop = props[i]; if (Opal.is_method(prop)) { delete proto[prop]; } } } // Here we change the ancestors chain from // // prepender // | // parent // // to: // // dummy(prepender) // | // iclass(module) // | // iclass(prepender) // | // parent var module_ancestors = $ancestors(mod); var iclasses = []; if (module_ancestors.indexOf(prepender) !== -1) { $raise(Opal.ArgumentError, 'cyclic prepend detected'); } for (var i = 0, length = module_ancestors.length; i < length; i++) { var ancestor = module_ancestors[i], iclass = Opal.create_iclass(ancestor); $prop(iclass, '$$prepended', true); iclasses.push(iclass); } var chain = Opal.chain_iclasses(iclasses), dummy_prepender = prepender.$$prototype, previous_parent = Object.getPrototypeOf(dummy_prepender), prepender_iclass, start_chain_after, end_chain_on; if (dummy_prepender.hasOwnProperty('$$dummy')) { // The module already has some prepended modules // which means that we don't need to make it "dummy" prepender_iclass = dummy_prepender.$$define_methods_on; } else { // Making the module "dummy" prepender_iclass = Opal.create_dummy_iclass(prepender); flush_methods_in(prepender); $prop(dummy_prepender, '$$dummy', true); $prop(dummy_prepender, '$$define_methods_on', prepender_iclass); // Converting // dummy(prepender) -> previous_parent // to // dummy(prepender) -> iclass(prepender) -> previous_parent $set_proto(dummy_prepender, prepender_iclass); $set_proto(prepender_iclass, previous_parent); } var prepender_ancestors = $ancestors(prepender); if (prepender_ancestors.indexOf(mod) === -1) { // first time prepend start_chain_after = dummy_prepender; // next $$root or prepender_iclass or non-$$iclass end_chain_on = Object.getPrototypeOf(dummy_prepender); while (end_chain_on != null) { if ( end_chain_on.hasOwnProperty('$$root') || end_chain_on === prepender_iclass || !end_chain_on.hasOwnProperty('$$iclass') ) { break; } end_chain_on = Object.getPrototypeOf(end_chain_on); } } else { $raise(Opal.RuntimeError, "Prepending a module multiple times is not supported"); } $set_proto(start_chain_after, chain.first); $set_proto(chain.last, end_chain_on); // recalculate own_prepended_modules cache prepender.$$own_prepended_modules = Opal.own_prepended_modules(prepender); Opal.const_cache_version++; } end # iclasses are JavaScript classes that are injected into # the prototype chain, carrying all module methods. def self.create_iclass(mod) %x{ var iclass = Opal.create_dummy_iclass(mod); if (mod.$$is_module) { mod.$$iclasses.push(iclass); } return iclass; } end # Dummy iclass doesn't receive updates when the module gets a new method. def self.create_dummy_iclass(mod) %x{ var iclass = {}, proto = mod.$$prototype; if (proto.hasOwnProperty('$$dummy')) { proto = proto.$$define_methods_on; } var props = Object.getOwnPropertyNames(proto), length = props.length, i; for (i = 0; i < length; i++) { var prop = props[i]; $prop(iclass, prop, proto[prop]); } $prop(iclass, '$$iclass', true); $prop(iclass, '$$module', mod); return iclass; } end def self.chain_iclasses(iclasses) %x{ var length = iclasses.length, first = iclasses[0]; $prop(first, '$$root', true); if (length === 1) { return { first: first, last: first }; } var previous = first; for (var i = 1; i < length; i++) { var current = iclasses[i]; $set_proto(previous, current); previous = current; } return { first: iclasses[0], last: iclasses[length - 1] }; } end def self.proto_to_module(proto) %x{ if (proto.hasOwnProperty('$$dummy')) { return; } else if (proto.hasOwnProperty('$$iclass')) { return proto.$$module; } else if (proto.hasOwnProperty('$$class')) { return proto.$$class; } } end def self.included_modules(main_module) %x{ var result = [], mod = null, proto = Object.getPrototypeOf(main_module.$$prototype); for (; proto && Object.getPrototypeOf(proto); proto = Object.getPrototypeOf(proto)) { mod = Opal.proto_to_module(proto); if (mod && mod.$$is_module && proto.$$iclass && proto.$$included) { result.push(mod); } } return result; } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/method_missing.rb
opal/runtime/method_missing.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: BasicObject, jsid, prop, prepend_ary module ::Opal # Method Missing # -------------- # Methods stubs are used to facilitate method_missing in opal. A stub is a # placeholder function which just calls `method_missing` on the receiver. # If no method with the given name is actually defined on an object, then it # is obvious to say that the stub will be called instead, and then in turn # method_missing will be called. # # When a file in ruby gets compiled to javascript, it includes a call to # this function which adds stubs for every method name in the compiled file. # It should then be safe to assume that method_missing will work for any # method call detected. # # Method stubs are added to the BasicObject prototype, which every other # ruby object inherits, so all objects should handle method missing. A stub # is only added if the given property name (method name) is not already # defined. # # Note: all ruby methods have a `$` prefix in javascript, so all stubs will # have this prefix as well (to make this method more performant). # # Opal.add_stubs("foo,bar,baz="); # # All stub functions will have a private `$$stub` property set to true so # that other internal methods can detect if a method is just a stub or not. # `Kernel#respond_to?` uses this property to detect a methods presence. # # @param stubs [Array] an array of method stubs to add # @return [undefined] def self.add_stubs(stubs) %x{ var proto = $BasicObject.$$prototype; var stub, existing_method; stubs = stubs.split(','); for (var i = 0, length = stubs.length; i < length; i++) { stub = $jsid(stubs[i]), existing_method = proto[stub]; if (existing_method == null || existing_method.$$stub) { Opal.add_stub_for(proto, stub); } } } end # Add a method_missing stub function to the given prototype for the # given name. # # @param prototype [Prototype] the target prototype # @param stub [String] stub name to add (e.g. "$foo") # @return [undefined] def self.add_stub_for(prototype, stub) # Opal.stub_for(stub) is the method_missing_stub `$prop(prototype, stub, Opal.stub_for(stub))` end # Generate the method_missing stub for a given method name. # # @param method_name [String] The js-name of the method to stub (e.g. "$foo") # @return [undefined] def self.stub_for(method_name) %x{ function method_missing_stub() { // Copy any given block onto the method_missing dispatcher this.$method_missing.$$p = method_missing_stub.$$p; // Set block property to null ready for the next call (stop false-positives) method_missing_stub.$$p = null; // call method missing with correct args (remove '$' prefix on method name) return this.$method_missing.apply(this, $prepend_ary(method_name.slice(1), arguments)); }; method_missing_stub.$$stub = true; return method_missing_stub; } end `Opal.add_stubs("require,autoload")` end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/runtime/hash.rb
opal/runtime/hash.rb
# backtick_javascript: true # use_strict: true # opal_runtime_mode: true # helpers: raise, slice, splice, has_own module ::Opal # Hashes # ------ # Experiments have shown, that using new Map([[1,2]]) inline is rather slow # compared to using new Map() in combination with .set(1,2), because the former # creates a new Array for each pair and then discards it. Using .set though # would increase the size of the generated code. So lets use a compromise and # use a helper function, which allows the compiler to generate compact code # and at the same time provides the performance improvement of using .set # with a overall smaller overhead than creating arrays for each pair. # For primitive keys: def self.hash_new %x{ let h = new Map(); for (let i = 0; i < arguments.length; i += 2) { h.set(arguments[i], arguments[i + 1]); } return h; } end # The same as above, except for complex keys: def self.hash_new2 %x{ let h = new Map(); for (let i = 0; i < arguments.length; i += 2) { Opal.hash_put(h, arguments[i], arguments[i + 1]); } return h; } end def self.hash_init(_hash) %x{ console.warn("DEPRECATION: Opal.hash_init is deprecated and is now a no-op.") } end def self.hash_clone(from_hash, to_hash) %x{ to_hash.$$none = from_hash.$$none; to_hash.$$proc = from_hash.$$proc; return Opal.hash_each(from_hash, to_hash, function(key, value) { Opal.hash_put(to_hash, key, value); return [false, to_hash]; }); } end def self.hash_put(hash, key, value) %x{ var type = typeof key; if (type === "string" || type === "symbol" || type === "number" || type === "boolean" || type === "bigint") { hash.set(key, value) } else if (key.$$is_string) { hash.set(key.valueOf(), value); } else { if (!hash.$$keys) hash.$$keys = new Map(); var key_hash = key.$$is_string ? key.valueOf() : (hash.$$by_identity ? Opal.id(key) : key.$hash()), keys = hash.$$keys; if (!keys.has(key_hash)) { keys.set(key_hash, [key]); hash.set(key, value); return; } var objects = keys.get(key_hash), object; for (var i=0; i<objects.length; i++) { object = objects[i]; if (key === object || key['$eql?'](object)) { hash.set(object, value); return; } } objects.push(key); hash.set(key, value); } } end def self.hash_get(hash, key) %x{ var type = typeof key; if (type === "string" || type === "symbol" || type === "number" || type === "boolean" || type === "bigint") { return hash.get(key) } else if (hash.$$keys) { var key_hash = key.$$is_string ? key.valueOf() : (hash.$$by_identity ? Opal.id(key) : key.$hash()), objects = hash.$$keys.get(key_hash), object; if (objects !== undefined) { for (var i=0; i<objects.length; i++) { object = objects[i]; if (key === object || key['$eql?'](object)) return hash.get(object); } } else if (key.$$is_string) { return hash.get(key_hash); } } else if (key.$$is_string) { return hash.get(key.valueOf()); } } end def self.hash_delete_stage2(hash, key) %x{ var value = hash.get(key); hash.delete(key); return value; } end def self.hash_delete(hash, key) %x{ var type = typeof key if (type === "string" || type === "symbol" || type === "number" || type === "boolean" || type === "bigint") { return Opal.hash_delete_stage2(hash, key); } else if (hash.$$keys) { var key_hash = key.$$is_string ? key.valueOf() : (hash.$$by_identity ? Opal.id(key) : key.$hash()), objects = hash.$$keys.get(key_hash), object; if (objects !== undefined) { for (var i=0; i<objects.length; i++) { object = objects[i]; if (key === object || key['$eql?'](object)) { objects.splice(i, 1); if (objects.length === 0) hash.$$keys.delete(key_hash); return Opal.hash_delete_stage2(hash, object); } } } else if (key.$$is_string) { return Opal.hash_delete_stage2(hash, key_hash); } } else if (key.$$is_string) { return Opal.hash_delete_stage2(hash, key.valueOf()); } } end def self.hash_rehash(hash) %x{ var keys = hash.$$keys; if (keys) keys.clear(); Opal.hash_each(hash, false, function(key, value) { var type = typeof key; if (type === "string" || type === "symbol" || type === "number" || type === "boolean" || type === "bigint") return [false, false]; // nothing to rehash var key_hash = key.$$is_string ? key.valueOf() : (hash.$$by_identity ? Opal.id(key) : key.$hash()); if (!keys) hash.$$keys = keys = new Map(); if (!keys.has(key_hash)) { keys.set(key_hash, [key]); return [false, false]; } var objects = keys.get(key_hash), objects_copy = (objects.length === 1) ? objects : $slice(objects), object; for (var i=0; i<objects_copy.length; i++) { object = objects_copy[i]; if (key === object || key['$eql?'](object)) { // got a duplicate, remove it objects.splice(objects.indexOf(object), 1); hash.delete(object); } } objects.push(key); return [false, false] }); return hash; } end def self.hash %x{ var arguments_length = arguments.length, args, hash, i, length, key, value; if (arguments_length === 1 && arguments[0].$$is_hash) { return arguments[0]; } hash = new Map(); if (arguments_length === 1) { args = arguments[0]; if (arguments[0].$$is_array) { length = args.length; for (i = 0; i < length; i++) { if (args[i].length !== 2) { $raise(Opal.ArgumentError, 'value not of length 2: ' + args[i].$inspect()); } key = args[i][0]; value = args[i][1]; Opal.hash_put(hash, key, value); } return hash; } else { args = arguments[0]; for (key in args) { if ($has_own(args, key)) { value = args[key]; Opal.hash_put(hash, key, value); } } return hash; } } if (arguments_length % 2 !== 0) { $raise(Opal.ArgumentError, 'odd number of arguments for Hash'); } for (i = 0; i < arguments_length; i += 2) { key = arguments[i]; value = arguments[i + 1]; Opal.hash_put(hash, key, value); } return hash; } end # A faster Hash creator for hashes that just use symbols and # strings as keys. The map and keys array can be constructed at # compile time, so they are just added here by the constructor # function. def self.hash2(keys, smap) %x{ console.warn("DEPRECATION: `Opal.hash2` is deprecated and will be removed in Opal 2.0. Use $hash_new for primitive keys or $hash_new2 for complex keys instead."); var hash = new Map(); for (var i = 0, max = keys.length; i < max; i++) { hash.set(keys[i], smap[keys[i]]); } return hash; } end def self.hash_each(hash, dres, fun) %x{ // dres = default result, returned if hash is empty // fun is called as fun(key, value) and must return a array with [break, result] // if break is true, iteration stops and result is returned // if break is false, iteration continues and eventually the last result is returned var res; for (var i = 0, entry, entries = Array.from(hash.entries()), l = entries.length; i < l; i++) { entry = entries[i]; res = fun(entry[0], entry[1]); if (res[0]) return res[1]; } return res ? res[1] : dres; } end # Primitives for handling parameters def self.ensure_kwargs(kwargs) %x{ if (kwargs == null) { return new Map(); } else if (kwargs.$$is_hash) { return kwargs; } else { $raise(Opal.ArgumentError, 'expected kwargs'); } } end def self.get_kwarg(kwargs, key) %x{ var kwarg = Opal.hash_get(kwargs, key); if (kwarg === undefined) { $raise(Opal.ArgumentError, 'missing keyword: '+key); } return kwarg; } end # Used for extracting keyword arguments from arguments passed to # JS function. # # @param parameters [Array] # @return [Hash] or undefined def self.extract_kwargs(parameters) %x{ var kwargs = parameters[parameters.length - 1]; if (kwargs != null && Opal.respond_to(kwargs, '$to_hash', true)) { $splice(parameters, parameters.length - 1); return kwargs; } } end # Used to get a list of rest keyword arguments. Method takes the given # keyword args, i.e. the hash literal passed to the method containing all # keyword arguments passed to method, as well as the used args which are # the names of required and optional arguments defined. This method then # just returns all key/value pairs which have not been used, in a new # hash literal. # # @param given_args [Hash] all kwargs given to method # @param used_args [Object<String: true>] all keys used as named kwargs # @return [Hash] def self.kwrestargs(given_args, used_args) %x{ var map = new Map(); Opal.hash_each(given_args, false, function(key, value) { if (!used_args[key]) { Opal.hash_put(map, key, value); } return [false, false]; }); return map; } end # Helpers for extracting kwsplats # Used for: { **h } def self.to_hash(value) %x{ if (value.$$is_hash) { return value; } else if (value['$respond_to?']('to_hash', true)) { var hash = value.$to_hash(); if (hash.$$is_hash) { return hash; } else { $raise(Opal.TypeError, "Can't convert " + value.$$class + " to Hash (" + value.$$class + "#to_hash gives " + hash.$$class + ")"); } } else { $raise(Opal.TypeError, "no implicit conversion of " + value.$$class + " into Hash"); } } end # Opal32-checksum algorithm for #hash # ----------------------------------- def self.opal32_init = 0x4f70616c %x{ function $opal32_ror(n, d) { return (n << d)|(n >>> (32 - d)); }; } def self.opal32_add(hash, next_value) %x{ hash ^= next_value; hash = $opal32_ror(hash, 1); return hash; } end end ::Opal
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_slice_or_not.rb
benchmark-ips/bm_slice_or_not.rb
%x{ // Minify common function calls var $call = Function.prototype.call; var $bind = Function.prototype.bind; var $has_own = Object.hasOwn || $call.bind(Object.prototype.hasOwnProperty); var $set_proto = Object.setPrototypeOf; var $slice = $call.bind(Array.prototype.slice); var $splice = $call.bind(Array.prototype.splice); var cnt = 0; var fun = function(a,b,c) { cnt += a + b + c; } } Benchmark.ips do |x| ary = [1,2,3] obj = `{0: 1, 1: 2, 2: 3, length: 3}` x.report('Array.from(array)') do `fun.apply(null, Array.from(ary))` end x.report('Array.from(obj)') do `fun.apply(null, Array.from(obj))` end x.report('$slice(array)') do `fun.apply(null, $slice(ary))` end x.report('$slice(obj)') do `fun.apply(null, $slice(obj))` end x.report('array') do `fun.apply(null, ary)` end x.report('obj') do `fun.apply(null, obj)` end x.report('$slice?(array)') do `fun.apply(null, ary.$$is_array ? ary : $slice(ary))` end x.report('$slice?(obj)') do `fun.apply(null, obj.$$is_array ? obj : $slice(obj))` end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_js_symbols_vs_strings.rb
benchmark-ips/bm_js_symbols_vs_strings.rb
Benchmark.ips do |x| %x{ const c_foo = 'foo' const v_foo = 'foo' const cfoo = Symbol('foo') var vfoo = Symbol('foo') const cgfoo = Symbol.for('foo') var vgfoo = Symbol.for('foo') var o = {} o[cfoo] = 1 o[cgfoo] = 1 o[c_foo] = 1 o[vfoo] = 1 let a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0, a6 = 0, a7 = 0, a8 = 0 } x.report('const string ref') do `a1 += o[c_foo]` end x.report('var string ref') do `a2 += o[v_foo]` end x.report('live global symbol') do `a3 += o[Symbol.for('foo')]` end x.report('const global symbol') do `a4 += o[cgfoo]` end x.report('var global symbol') do `a5 += o[vgfoo]` end x.report('const symbol') do `a6 += o[cfoo]` end x.report('var symbol') do `a6 += o[vfoo]` end x.report('ident') do `a7 += o.foo` end x.report('live string') do `a8 += o['foo']` end x.time = 10 x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/class_shovel_vs_singleton_class.rb
benchmark-ips/class_shovel_vs_singleton_class.rb
o = nil Benchmark.ips do |x| x.report('shovel') do o = Object.new class << o attr_accessor :foo end end x.report('singleton_class') do o2 = Object.new o2.singleton_class.attr_accessor :foo end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_u_string.rb
benchmark-ips/bm_u_string.rb
# helpers: coerce_to, opal32_init, opal32_add # backtick_javascript: true require 'benchmark/ips' class String %x{ function find_index(str, search_s, search_l, search) { let search_f = search_s[0]; return str.findIndex((c, i, s) => { return (c === search_f && (search_l === 1 || s.slice(i, i + search_l).join('') == search)) ? true : false; }); } } def slice_orig(index, length = undefined) %x{ var size = self.length, exclude, range; if (index.$$is_range) { exclude = index.excl; range = index; length = index.end === nil ? -1 : $coerce_to(index.end, #{::Integer}, 'to_int'); index = index.begin === nil ? 0 : $coerce_to(index.begin, #{::Integer}, 'to_int'); if (Math.abs(index) > size) { return nil; } if (index < 0) { index += size; } if (length < 0) { length += size; } if (!exclude || range.end === nil) { length += 1; } length = length - index; if (length < 0) { length = 0; } return self.substr(index, length); } if (index.$$is_string) { if (length != null) { #{::Kernel.raise ::TypeError} } return self.indexOf(index) !== -1 ? index : nil; } if (index.$$is_regexp) { var match = self.match(index); if (match === null) { #{$~ = nil} return nil; } #{$~ = ::MatchData.new(`index`, `match`)} if (length == null) { return match[0]; } length = $coerce_to(length, #{::Integer}, 'to_int'); if (length < 0 && -length < match.length) { return match[length += match.length]; } if (length >= 0 && length < match.length) { return match[length]; } return nil; } index = $coerce_to(index, #{::Integer}, 'to_int'); if (index < 0) { index += size; } if (length == null) { if (index >= size || index < 0) { return nil; } return self.substr(index, 1); } length = $coerce_to(length, #{::Integer}, 'to_int'); if (length < 0) { return nil; } if (index > size || index < 0) { return nil; } return self.substr(index, length); } end def size_orig `self.length` end def center_orig(width, padstr = ' ') width = `$coerce_to(#{width}, #{::Integer}, 'to_int')` padstr = `$coerce_to(#{padstr}, #{::String}, 'to_str')`.to_s if padstr.empty? ::Kernel.raise ::ArgumentError, 'zero width padding' end return self if `width <= self.length` %x{ var ljustified = #{ljust_orig ((width + `self.length`) / 2).ceil, padstr}, rjustified = #{rjust_orig ((width + `self.length`) / 2).floor, padstr}; return rjustified + ljustified.slice(self.length); } end def ljust_orig(width, padstr = ' ') width = `$coerce_to(#{width}, #{::Integer}, 'to_int')` padstr = `$coerce_to(#{padstr}, #{::String}, 'to_str')`.to_s if padstr.empty? ::Kernel.raise ::ArgumentError, 'zero width padding' end return self if `width <= self.length` %x{ var index = -1, result = ""; width -= self.length; while (++index < width) { result += padstr; } return self + result.slice(0, width); } end def rjust_orig(width, padstr = ' ') width = `$coerce_to(#{width}, #{::Integer}, 'to_int')` padstr = `$coerce_to(#{padstr}, #{::String}, 'to_str')`.to_s if padstr.empty? ::Kernel.raise ::ArgumentError, 'zero width padding' end return self if `width <= self.length` %x{ var chars = Math.floor(width - self.length), patterns = Math.floor(chars / padstr.length), result = Array(patterns + 1).join(padstr), remaining = chars - result.length; return result + padstr.slice(0, remaining) + self; } end def delete_prefix_orig(prefix) %x{ if (!prefix.$$is_string) { prefix = $coerce_to(prefix, #{::String}, 'to_str'); } if (self.slice(0, prefix.length) === prefix) { return self.slice(prefix.length); } else { return self; } } end def delete_suffix_orig(suffix) %x{ if (!suffix.$$is_string) { suffix = $coerce_to(suffix, #{::String}, 'to_str'); } if (self.slice(self.length - suffix.length) === suffix) { return self.slice(0, self.length - suffix.length); } else { return self; } } end def start_with_orig?(*prefixes) %x{ for (var i = 0, length = prefixes.length; i < length; i++) { if (prefixes[i].$$is_regexp) { var regexp = prefixes[i]; var match = regexp.exec(self); if (match != null && match.index === 0) { #{$~ = ::MatchData.new(`regexp`, `match`)}; return true; } else { #{$~ = nil} } } else { var prefix = $coerce_to(prefixes[i], #{::String}, 'to_str').$to_s(); if (self.length >= prefix.length && self.startsWith(prefix)) { return true; } } } return false; } end def end_with_orig?(*suffixes) %x{ for (var i = 0, length = suffixes.length; i < length; i++) { var suffix = $coerce_to(suffixes[i], #{::String}, 'to_str').$to_s(); if (self.length >= suffix.length && self.substr(self.length - suffix.length, suffix.length) == suffix) { return true; } } } false end def index_orig(search, offset = undefined) %x{ var index, match, regex; if (offset === undefined) { offset = 0; } else { offset = $coerce_to(offset, #{::Integer}, 'to_int'); if (offset < 0) { offset += self.length; if (offset < 0) { return nil; } } } if (search.$$is_regexp) { regex = $global_regexp(search); while (true) { match = regex.exec(self); if (match === null) { #{$~ = nil}; index = -1; break; } if (match.index >= offset) { #{$~ = ::MatchData.new(`regex`, `match`)} index = match.index; break; } regex.lastIndex = match.index + 1; } } else { search = $coerce_to(search, #{::String}, 'to_str'); if (search.length === 0 && offset > self.length) { index = -1; } else { index = self.indexOf(search, offset); } } return index === -1 ? nil : index; } end def next_orig %x{ var i = self.length; if (i === 0) { return ''; } var result = self; var first_alphanum_char_index = self.search(/[a-zA-Z0-9]/); var carry = false; var code; while (i--) { code = self.charCodeAt(i); if ((code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122)) { switch (code) { case 57: carry = true; code = 48; break; case 90: carry = true; code = 65; break; case 122: carry = true; code = 97; break; default: carry = false; code += 1; } } else { if (first_alphanum_char_index === -1) { if (code === 255) { carry = true; code = 0; } else { carry = false; code += 1; } } else { carry = true; } } result = result.slice(0, i) + String.fromCharCode(code) + result.slice(i + 1); if (carry && (i === 0 || i === first_alphanum_char_index)) { switch (code) { case 65: break; case 97: break; default: code += 1; } if (i === 0) { result = String.fromCharCode(code) + result; } else { result = result.slice(0, i) + String.fromCharCode(code) + result.slice(i); } carry = false; } if (!carry) { break; } } return result; } end def partition_orig(sep) %x{ var i, m; if (sep.$$is_regexp) { m = sep.exec(self); if (m === null) { i = -1; } else { #{::MatchData.new `sep`, `m`}; sep = m[0]; i = m.index; } } else { sep = $coerce_to(sep, #{::String}, 'to_str'); i = self.indexOf(sep); } if (i === -1) { return [self, '', '']; } return [ self.slice(0, i), self.slice(i, i + sep.length), self.slice(i + sep.length) ]; } end def reverse_orig `self.split('').reverse().join('')` end def rindex_orig(search, offset = undefined) %x{ var i, m, r, _m; if (offset === undefined) { offset = self.length; } else { offset = $coerce_to(offset, #{::Integer}, 'to_int'); if (offset < 0) { offset += self.length; if (offset < 0) { return nil; } } } if (search.$$is_regexp) { m = null; r = $global_regexp(search); while (true) { _m = r.exec(self); if (_m === null || _m.index > offset) { break; } m = _m; r.lastIndex = m.index + 1; } if (m === null) { #{$~ = nil} i = -1; } else { #{::MatchData.new `r`, `m`}; i = m.index; } } else { search = $coerce_to(search, #{::String}, 'to_str'); i = self.lastIndexOf(search, offset); } return i === -1 ? nil : i; } end def rpartition_orig(sep) %x{ var i, m, r, _m; if (sep.$$is_regexp) { m = null; r = $global_regexp(sep); while (true) { _m = r.exec(self); if (_m === null) { break; } m = _m; r.lastIndex = m.index + 1; } if (m === null) { i = -1; } else { #{::MatchData.new `r`, `m`}; sep = m[0]; i = m.index; } } else { sep = $coerce_to(sep, #{::String}, 'to_str'); i = self.lastIndexOf(sep); } if (i === -1) { return ['', '', self]; } return [ self.slice(0, i), self.slice(i, i + sep.length), self.slice(i + sep.length) ]; } end def tr_orig(from, to) %x{ from = $coerce_to(from, #{::String}, 'to_str').$to_s(); to = $coerce_to(to, #{::String}, 'to_str').$to_s(); if (from.length == 0 || from === to) { return self; } var i, in_range, c, ch, start, end, length; var subs = {}; var from_chars = from.split(''); var from_length = from_chars.length; var to_chars = to.split(''); var to_length = to_chars.length; var inverse = false; var global_sub = null; if (from_chars[0] === '^' && from_chars.length > 1) { inverse = true; from_chars.shift(); global_sub = to_chars[to_length - 1] from_length -= 1; } var from_chars_expanded = []; var last_from = null; in_range = false; for (i = 0; i < from_length; i++) { ch = from_chars[i]; if (last_from == null) { last_from = ch; from_chars_expanded.push(ch); } else if (ch === '-') { if (last_from === '-') { from_chars_expanded.push('-'); from_chars_expanded.push('-'); } else if (i == from_length - 1) { from_chars_expanded.push('-'); } else { in_range = true; } } else if (in_range) { start = last_from.charCodeAt(0); end = ch.charCodeAt(0); if (start > end) { #{::Kernel.raise ::ArgumentError, "invalid range \"#{`String.fromCharCode(start)`}-#{`String.fromCharCode(end)`}\" in string transliteration"} } for (c = start + 1; c < end; c++) { from_chars_expanded.push(String.fromCharCode(c)); } from_chars_expanded.push(ch); in_range = null; last_from = null; } else { from_chars_expanded.push(ch); } } from_chars = from_chars_expanded; from_length = from_chars.length; if (inverse) { for (i = 0; i < from_length; i++) { subs[from_chars[i]] = true; } } else { if (to_length > 0) { var to_chars_expanded = []; var last_to = null; in_range = false; for (i = 0; i < to_length; i++) { ch = to_chars[i]; if (last_to == null) { last_to = ch; to_chars_expanded.push(ch); } else if (ch === '-') { if (last_to === '-') { to_chars_expanded.push('-'); to_chars_expanded.push('-'); } else if (i == to_length - 1) { to_chars_expanded.push('-'); } else { in_range = true; } } else if (in_range) { start = last_to.charCodeAt(0); end = ch.charCodeAt(0); if (start > end) { #{::Kernel.raise ::ArgumentError, "invalid range \"#{`String.fromCharCode(start)`}-#{`String.fromCharCode(end)`}\" in string transliteration"} } for (c = start + 1; c < end; c++) { to_chars_expanded.push(String.fromCharCode(c)); } to_chars_expanded.push(ch); in_range = null; last_to = null; } else { to_chars_expanded.push(ch); } } to_chars = to_chars_expanded; to_length = to_chars.length; } var length_diff = from_length - to_length; if (length_diff > 0) { var pad_char = (to_length > 0 ? to_chars[to_length - 1] : ''); for (i = 0; i < length_diff; i++) { to_chars.push(pad_char); } } for (i = 0; i < from_length; i++) { subs[from_chars[i]] = to_chars[i]; } } var new_str = '' for (i = 0, length = self.length; i < length; i++) { ch = self.charAt(i); var sub = subs[ch]; if (inverse) { new_str += (sub == null ? global_sub : ch); } else { new_str += (sub != null ? sub : ch); } } return new_str; } end def split_orig(pattern = undefined, limit = undefined) %x{ if (self.length === 0) { return []; } if (limit === undefined) { limit = 0; } else { limit = #{::Opal.coerce_to!(limit, ::Integer, :to_int)}; if (limit === 1) { return [self]; } } if (pattern === undefined || pattern === nil) { pattern = #{$; || ' '}; } var result = [], string = self.toString(), index = 0, match, match_count = 0, valid_result_length = 0, i, max; if (pattern.$$is_regexp) { pattern = $global_regexp(pattern); } else { pattern = $coerce_to(pattern, #{::String}, 'to_str').$to_s(); if (pattern === ' ') { pattern = /\s+/gm; string = string.replace(/^\s+/, ''); } } result = string.split(pattern); if (result.length === 1 && result[0] === string) { return [result[0]]; } while ((i = result.indexOf(undefined)) !== -1) { result.splice(i, 1); } if (limit === 0) { while (result[result.length - 1] === '') { result.pop(); } return result; } if (!pattern.$$is_regexp) { pattern = Opal.escape_regexp(pattern) pattern = new RegExp(pattern, 'gm'); } match = pattern.exec(string); if (limit < 0) { if (match !== null && match[0] === '' && pattern.source.indexOf('(?=') === -1) { for (i = 0, max = match.length; i < max; i++) { result.push(''); } } return result; } if (match !== null && match[0] === '') { valid_result_length = (match.length - 1) * (limit - 1) + limit result.splice(valid_result_length - 1, result.length - 1, result.slice(valid_result_length - 1).join('')); return result; } if (limit >= result.length) { return result; } while (match !== null) { match_count++; index = pattern.lastIndex; valid_result_length += match.length if (match_count + 1 === limit) { break; } match = pattern.exec(string); } result.splice(valid_result_length, result.length - 1, string.slice(index)); return result; } end def capitalize_orig `self.charAt(0).toUpperCase() + self.substr(1).toLowerCase()` end def chomp_orig(separator = $/) return self if `separator === nil || self.length === 0` separator = ::Opal.coerce_to!(separator, ::String, :to_str).to_s %x{ var result; if (separator === "\n") { result = self.replace(/\r?\n?$/, ''); } else if (separator === "") { result = self.replace(/(\r?\n)+$/, ''); } else if (self.length >= separator.length) { var tail = self.substr(self.length - separator.length, separator.length); if (tail === separator) { result = self.substr(0, self.length - separator.length); } } if (result != null) { return result; } } self end def chop_orig %x{ var length = self.length, result; if (length <= 1) { result = ""; } else if (self.charAt(length - 1) === "\n" && self.charAt(length - 2) === "\r") { result = self.substr(0, length - 2); } else { result = self.substr(0, length - 1); } return result; } end %x{ function char_class_from_char_sets(sets) { function explode_sequences_in_character_set(set) { var result = '', i, len = set.length, curr_char, skip_next_dash, char_code_from, char_code_upto, char_code; for (i = 0; i < len; i++) { curr_char = set.charAt(i); if (curr_char === '-' && i > 0 && i < (len - 1) && !skip_next_dash) { char_code_from = set.charCodeAt(i - 1); char_code_upto = set.charCodeAt(i + 1); if (char_code_from > char_code_upto) { #{::Kernel.raise ::ArgumentError, "invalid range \"#{`char_code_from`}-#{`char_code_upto`}\" in string transliteration"} } for (char_code = char_code_from + 1; char_code < char_code_upto + 1; char_code++) { result += String.fromCharCode(char_code); } skip_next_dash = true; i++; } else { skip_next_dash = (curr_char === '\\'); result += curr_char; } } return result; } function intersection(setA, setB) { if (setA.length === 0) { return setB; } var result = '', i, len = setA.length, chr; for (i = 0; i < len; i++) { chr = setA.charAt(i); if (setB.indexOf(chr) !== -1) { result += chr; } } return result; } var i, len, set, neg, chr, tmp, pos_intersection = '', neg_intersection = ''; for (i = 0, len = sets.length; i < len; i++) { set = $coerce_to(sets[i], #{::String}, 'to_str'); neg = (set.charAt(0) === '^' && set.length > 1); set = explode_sequences_in_character_set(neg ? set.slice(1) : set); if (neg) { neg_intersection = intersection(neg_intersection, set); } else { pos_intersection = intersection(pos_intersection, set); } } if (pos_intersection.length > 0 && neg_intersection.length > 0) { tmp = ''; for (i = 0, len = pos_intersection.length; i < len; i++) { chr = pos_intersection.charAt(i); if (neg_intersection.indexOf(chr) === -1) { tmp += chr; } } pos_intersection = tmp; neg_intersection = ''; } if (pos_intersection.length > 0) { return '[' + #{::Regexp.escape(`pos_intersection`)} + ']'; } if (neg_intersection.length > 0) { return '[^' + #{::Regexp.escape(`neg_intersection`)} + ']'; } return null; } } def count_orig(*sets) %x{ if (sets.length === 0) { #{::Kernel.raise ::ArgumentError, 'ArgumentError: wrong number of arguments (0 for 1+)'} } var char_class = char_class_from_char_sets(sets); if (char_class === null) { return 0; } return self.length - self.replace(new RegExp(char_class, 'g'), '').length; } end def delete_orig(*sets) %x{ if (sets.length === 0) { #{::Kernel.raise ::ArgumentError, 'ArgumentError: wrong number of arguments (0 for 1+)'} } var char_class = char_class_from_char_sets(sets); if (char_class === null) { return self; } return self.replace(new RegExp(char_class, 'g'), ''); } end end s = "𝌆a𝌆" c = "𝌆a𝌆 𝌆a𝌆" # string for centering short_string = "𝌆" medi_string = s * 10 mi = medi_string.size - 2 long_string = s * 13108 # just a few bytes beyond 64k bytes li = long_string.size - 2 ni = -2 r1 = (30..100) r2 = ((li-100)..(li-30)) r3 = (-100..-30) def sep puts puts '#' * 79 puts end sep Benchmark.ips do |x| x.report("orig short size") { short_string.size_orig } x.report("current short size") { short_string.size } x.compare! end sep Benchmark.ips do |x| x.report("orig medi size") { medi_string.size_orig } x.report("current medi size") { medi_string.size } x.compare! end sep Benchmark.ips do |x| x.report("orig long size") { long_string.size_orig } x.report("current long size") { long_string.size } x.compare! end sep Benchmark.ips do |x| x.report("orig [] short") { short_string.slice_orig(0) } x.report("current [] short") { short_string[0] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] medi+") { medi_string.slice_orig(mi) } x.report("current [] medi+") { medi_string[mi] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] medi-") { medi_string.slice_orig(-mi) } x.report("current [] medi-") { medi_string[-mi] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] long+") { long_string.slice_orig(li) } x.report("current [] long+") { long_string[li] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] long- bc") { long_string.slice_orig(ni) } x.report("current [] long- bc") { long_string[ni] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] long- wc") { long_string.slice_orig(-li) } x.report("current [] long- wc") { long_string[-li] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] range 1") { long_string.slice_orig(r1) } x.report("current [] range 1") { long_string[r1] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] range 2") { long_string.slice_orig(r2) } x.report("current [] range 2") { long_string[r2] } x.compare! end sep Benchmark.ips do |x| x.report("orig [] range 3") { long_string.slice_orig(r3) } x.report("current [] range 3") { long_string[r3] } x.compare! end sep Benchmark.ips do |x| x.report("orig ljust") { c.ljust_orig(80) } x.report("current ljust") { c.ljust(80) } x.compare! end Benchmark.ips do |x| x.report("orig ljust u") { c.ljust_orig(80, '𝌆') } x.report("current ljust u") { c.ljust(80, '𝌆') } x.compare! end Benchmark.ips do |x| x.report("orig ljust u3") { c.ljust_orig(80, '𝌆𝌆𝌆') } x.report("current ljust u3") { c.ljust(80, '𝌆𝌆𝌆') } x.compare! end sep Benchmark.ips do |x| x.report("orig rjust") { c.rjust_orig(80) } x.report("current rjust") { c.rjust(80) } x.compare! end Benchmark.ips do |x| x.report("orig rjust u") { c.rjust_orig(80, '𝌆') } x.report("current rjust u") { c.rjust(80, '𝌆') } x.compare! end Benchmark.ips do |x| x.report("orig rjust u3") { c.rjust_orig(80, '𝌆𝌆𝌆') } x.report("current rjust u3") { c.rjust(80, '𝌆𝌆𝌆') } x.compare! end sep Benchmark.ips do |x| x.report("orig center") { c.center_orig(80) } x.report("current center") { c.center(80) } x.compare! end sep Benchmark.ips do |x| x.report("orig del_pref") { medi_string.delete_prefix_orig(s) } x.report("current del_pref") { medi_string.delete_prefix(s) } x.compare! end Benchmark.ips do |x| x.report("orig del_suff") { medi_string.delete_suffix_orig(s) } x.report("current del_suff") { medi_string.delete_suffix(s) } x.compare! end sep Benchmark.ips do |x| x.report("orig start_w") { medi_string.start_with_orig?(s) } x.report("current start_w") { medi_string.start_with?(s) } x.compare! end Benchmark.ips do |x| x.report("orig end_w") { medi_string.end_with_orig?(s) } x.report("current end_w") { medi_string.end_with?(s) } x.compare! end sep Benchmark.ips do |x| x.report("orig index") { c.index_orig(' ') } x.report("current index") { c.index(' ') } x.compare! end Benchmark.ips do |x| x.report("orig index multi") { c.index_orig(' 𝌆') } x.report("current index multi") { c.index(' 𝌆') } x.compare! end sep Benchmark.ips do |x| x.report("orig next") { c.next_orig } x.report("current next") { c.next } x.compare! end sep Benchmark.ips do |x| x.report("orig partition") { c.partition_orig(' ') } x.report("current partition") { c.partition(' ') } x.compare! end sep Benchmark.ips do |x| x.report("orig reverse medi") { medi_string.reverse_orig } x.report("current reverse medi") { medi_string.reverse } x.compare! end Benchmark.ips do |x| x.report("orig reverse long") { long_string.reverse_orig } x.report("current reverse long") { long_string.reverse } x.compare! end sep Benchmark.ips do |x| x.report("orig rindex") { c.rindex_orig(' ') } x.report("current rindex") { c.rindex(' ') } x.compare! end sep Benchmark.ips do |x| x.report("orig rpartition") { c.rpartition_orig(' ') } x.report("current rpartition") { c.rpartition(' ') } x.compare! end sep Benchmark.ips do |x| x.report("orig tr") { long_string.tr_orig('a', '𝌆') } x.report("current tr") { long_string.tr('a', '𝌆') } x.compare! end sep Benchmark.ips do |x| x.report("orig split e") { medi_string.split_orig('') } x.report("current split e") { medi_string.split('') } x.compare! end Benchmark.ips do |x| x.report("orig split sp") { medi_string.split_orig(' ') } x.report("current split sp") { medi_string.split(' ') } x.compare! end Benchmark.ips do |x| x.report("orig split uc") { medi_string.split_orig('𝌆') } x.report("current split uc") { medi_string.split('𝌆') } x.compare! end sep Benchmark.ips do |x| x.report("orig capitalize") { medi_string.capitalize_orig } x.report("current capitalize") { medi_string.capitalize } x.compare! end sep Benchmark.ips do |x| x.report("orig chomp") { medi_string.chomp_orig('𝌆') } x.report("current chomp") { medi_string.chomp('𝌆') } x.compare! end sep Benchmark.ips do |x| x.report("orig chop") { medi_string.chop_orig } x.report("current chop") { medi_string.chop } x.compare! end sep Benchmark.ips do |x| x.report("orig count") { medi_string.count_orig('a𝌆') } x.report("current count") { medi_string.count('a𝌆') } x.compare! end Benchmark.ips do |x| x.report("orig delete") { medi_string.delete_orig('𝌆') } x.report("current delete") { medi_string.delete('𝌆') } x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_case.rb
benchmark-ips/bm_case.rb
Benchmark.ips do |x| obj = Object.new x.report("numeric statement") do case 1 when 4 then 4 when 3 then 3 when 2 then 2 when 1 then 1 end nil end x.report("statement") do case 1 when 4 then 4 when 3 then 3 when 2 then 2 when obj then :obj when 1 then 1 end nil end x.report("expression") do case 1 when 4 then 4 when 3 then 3 when 2 then 2 when obj then :obj when 1 then 1 end end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_symbol_to_proc.rb
benchmark-ips/bm_symbol_to_proc.rb
# https://github.com/opal/opal/issues/1659#issuecomment-298222232 Benchmark.ips do |x| a = [] 50.times do |i| a << %(#{i}\n) end x.report('map block') do a.map {|it| it.chomp } end x.report('map symbol') do a.map(&:chomp) end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_block_vs_yield.rb
benchmark-ips/bm_block_vs_yield.rb
module BmBlockVsYield def self._block(&block) block.call end def self._yield yield end end Benchmark.ips do |x| x.warmup = 10 x.time = 60 x.report('block') do BmBlockVsYield._block { 1+1 } end x.report('yield') do BmBlockVsYield._yield { 1+1 } end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_array_pop_1.rb
benchmark-ips/bm_array_pop_1.rb
Benchmark.ips do |x| x.report('pop(1)') do a = ['4768', '4964', '4266', '4872', '4231', '4017', '4565', '4793', '4298', '4135', '4639', '4780', '4237', '4548', '4655', '4153', '4654', '4922', '4563', '4042', '4329', '4699', '4352', '4127', '4544', '4906', '4814', '4948', '4977', '4830', '4405', '4642', '4666', '4402', '4679', '4465', '4401', '4155', '4767', '4510', '4747', '4993', '4508', '4697', '4758', '4133', '4348', '4200', '4442', '4970', '4452', '4041', '4103', '4567', '4937', '4047', '4933', '4121', '4860', '4659', '4221', '4312', '4583', '4473', '4973', '4262', '4630', '4123', '4139', '4289', '4147', '4222', '4050', '4019', '4454', '4253', '4552', '4947', '4725', '4457', '4929', '4021', '4502', '4307', '4576', '4124', '4586', '4610', '4027', '4572', '4926', '4753', '4185', '4382', '4394', '4923', '4186', '4254', '4012', '4417', '4556', '4349', '4550', '4330', '4938', '4985', '4778', '4716', '4924', '4045', '4358', '4189', '4591', '4213', '4851', '4825', '4260', '4198', '4342', '4824', '4333', '4244', '4752', '4994', '4488', '4532', '4082', '4595', '4098', '4436', '4540', '4267', '4407', '4998', '4751', '4535', '4861', '4819', '4419', '4031', '4029', '4453', '4698', '4965', '4450', '4668', '4036', '4300', '4519', '4281', '4981', '4818', '4939', '4378', '4140', '4841', '4249', '4290', '4388', '4878', '4884', '4235', '4515', '4638', '4410', '4054', '4383', '4238', '4870', '4295', '4804', '4308', '4614', '4105', '4053', '4446', '4757', '4971', '4637', '4831', '4193', '4912', '4000', '4187', '4606', '4566', '4169', '4641', '4749', '4729', '4928', '4601', '4949', '4210', '4313', '4647', '4495', '4460', '4621', '4605', '4694', '4317', '4226', '4263', '4016', '4997', '4940', '4715', '4907', '4620', '4934', '4996', '4955', '4688', '4304', '4220', '4882', '4772', '4536', '4815', '4693', '4469', '4276', '4409', '4071', '4224', '4020', '4629', '4865', '4813', '4366', '4622', '4129', '4533', '4634', '4564', '4087', '4386', '4161', '4265', '4711', '4009', '4376', '4781', '4837', '4112', '4915', '4592', '4658', '4025', '4987', '4291', '4477', '4503', '4437', '4111', '4707', '4879', '4611', '4549', '4078', '4044', '4853', '4835', '4463', '4577', '4008', '4233', '4741', '4384', '4225', '4024', '4726', '4743', '4160', '4180', '4722', '4609', '4114', '4834', '4742', '4662', '4984', '4299', '4060', '4498', '4755', '4320', '4874', '4528', '4216', '4852', '4951', '4958', '4283', '4239', '4476', '4644', '4143', '4104', '4455', '4126', '4950', '4663', '4013', '4931', '4850', '4242', '4130', '4623', '4871', '4014', '4854', '4293', '4512', '4166', '4740', '4735', '4150', '4651', '4172', '4836', '4530', '4664', '4429', '4511', '4558', '4676', '4085', '4074', '4580', '4794', '4379', '4310', '4817', '4966', '4848', '4202', '4336', '4608', '4351', '4396', '4652', '4033', '4188', '4431', '4916', '4259', '4607', '4816', '4810', '4627', '4527', '4560', '4728', '4589', '4274', '4809', '4790', '4398', '4414', '4516', '4581', '4919', '4665', '4331', '4978', '4543', '4877', '4974', '4284', '4004', '4177', '4466', '4116', '4217', '4901', '4372', '4137', '4806', '4264', '4497', '4294', '4787', '4212', '4215', '4115', '4782', '4739', '4821', '4125', '4505', '4230', '4399', '4395', '4079', '4867', '4381', '4706', '4695', '4404', '4691', '4075', '4353', '4301', '4876', '4731', '4523', '4246', '4529', '4412', '4784', '4449', '4229', '4616', '4158', '4002', '4318', '4377', '4205', '4911', '4777', '4792', '4271', '4763', '4141', '4287', '4890', '4279', '4829', '4646', '4840', '4089', '4880', '4067', '4918', '4059', '4109', '4164', '4863', '4883', '4909', '4361', '4174', '4960', '4302', '4003', '4236', '4846', '4034', '4324', '4513', '4765', '4596', '4900', '4007', '4603', '4474', '4439', '4805', '4015', '4496', '4953', '4363', '4551', '4459', '4063', '4983', '4881', '4365', '4604', '4587', '4798', '4005', '4163', '4421', '4471', '4826', '4144', '4635', '4600', '4913', '4640', '4247', '4766', '4779', '4280', '4391', '4891', '4636', '4546', '4683', '4181', '4081', '4862', '4458', '4037', '4321', '4786', '4717', '4628', '4154', '4326', '4032', '4873', '4151', '4905', '4270', '4156', '4733', '4980', '4866', '4325', '4055', '4467', '4480', '4286', '4191', '4762', '4322', '4574', '4022', '4056', '4770', '4451', '4448', '4845', '4341', '4433', '4245', '4684', '4671', '4093', '4920', '4272', '4745', '4799', '4761', '4250', '4578', '4347', '4499', '4526', '4369', '4162', '4537', '4434', '4893', '4120', '4962', '4667', '4525', '4091', '4462', '4182', '4738', '4935', '4173', '4490', '4571', '4424', '4894', '4051', '4214', '4823', '4096', '4206', '4598', '4943', '4701', '4649', '4807', '4107', '4435', '4456', '4083', '4612', '4721', '4472', '4146', '4925', '4340', '4789', '4277', '4375', '4211', '4427', '4547', '4690', '4613', '4727', '4006', '4203', '4430', '4223', '4039', '4932', '4296', '4108', '4278', '4832', '4422', '4917', '4470', '4183', '4887', '4076', '4485', '4597', '4443', '4257', '4991', '4944', '4196', '4672', '4397', '4097', '4119', '4077', '4773', '4602', '4538', '4479', '4968', '4159', '4539', '4956', '4710', '4812', '4902', '4569', '4954', '4385', '4128', '4936', '4416', '4148', '4632', '4759', '4117', '4896', '4392', '4864', '4316', '4132', '4319', '4969', '4175', '4484', '4903', '4910', '4350', '4332', '4952', '4176', '4594', '4709', '4509', '4178', '4167', '4545', '4857', '4617', '4501', '4859', '4207', '4275', '4687', '4049', '4579', '4046', '4921', '4113', '4898', '4681', '4052', '4415', '4064', '4184', '4895', '4744', '4685', '4084', '4305', '4899', '4559', '4208', '4057', '4507', '4258', '4355', '4086', '4373', '4323', '4541', '4297', '4483', '4889', '4531', '4327', '4441', '4914', '4303', '4677', '4445', '4802', '4343', '4585', '4338', '4524', '4590', '4624', '4288', '4704', '4134', '4043', '4720', '4058', '4328', '4095', '4026', '4423', '4657', '4118', '4633', '4487', '4822', '4904', '4255', '4001', '4387', '4500', '4190', '4686', '4995', '4661', '4783', '4992', '4165', '4065', '4927', '4306', '4856', '4292', '4420', '4963', '4468', '4240', '4724', '4432', '4447', '4518', '4028', '4670', '4339', '4771', '4018', '4489', '4110', '4708', '4945', '4136', '4492', '4930', '4090', '4734', '4886', '4542', '4227', '4486', '4491', '4713', '4986', '4068', '4048', '4975', '4570', '4842', '4475', '4131', '4555', '4428', '4776', '4101', '4273', '4811', '4345', '5000', '4653', '4256', '4209', '4769', '4946', '4561', '4080', '4461', '4820', '4311', '4959', '4750', '4795', '4748', '4368', '4506', '4335', '4346', '4568', '4675', '4692', '4774', '4413', '4370', '4723', '4521', '4885', '4678', '4897', '4066', '4674', '4106', '4626', '4389', '4204', '4839', '4023', '4712', '4145', '4035', '4357', '4756', '4648', '4972', '4157', '4406', '4615', '4061', '4219', '4791', '4660', '4073', '4356', '4072', '4599', '4359', '4094', '4673', '4696', '4796', '4282', '4714', '4522', '4736', '4775', '4760', '4400', '4847', '4228', '4803', '4908', '4732', '4645', '4122', '4218', '4478', '4941', '4892', '4364', '4403', '4152', '4444', '4360', '4354', '4241', '4494', '4367', '4808', '4261', '4088', '4573', '4554', '4248', '4371', '4393', '4268', '4201', '4038', '4788', '4593', '4040', '4801', '4582', '4309', '4976', '4374', '4869', '4380', '4514', '4243', '4362', '4849', '4680', '4888', '4764', '4618', '4838', '4828', '4643', '4010', '4827', '4957', '4099', '4875', '4843', '4737', '4102', '4979', '4011', '4504', '4440', '4746', '4557', '4426', '4553', '4656', '4868', '4689', '4988', '4703', '4967', '4069', '4619', '4334', '4669', '4785', '4464', '4562', '4961', '4625', '4754', '4797', '4481', '4705', '4199', '4337', '4062', '4138', '4702', '4534', '4168', '4418', '4092', '4682', '4520', '4030', '4171', '4650', '4858', '4411', '4999', '4252', '4197', '4170', '4942', '4631', '4990', '4179', '4285', '4700', '4482', '4575', '4800', '4070', '4251', '4344', '4982', '4719', '4390', '4149', '4100', '4194', '4269', '4855', '4314', '4718', '4232', '4730', '4438', '4588', '4195', '4192', '4493', '4517', '4833', '4234', '4989', '4315', '4844', '4142', '4408', '4584', '4425'] a.pop(1) end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_array_shift.rb
benchmark-ips/bm_array_shift.rb
Benchmark.ips do |x| x.report("shift no arg") do a = ['4768', '4964', '4266', '4872', '4231', '4017', '4565', '4793', '4298', '4135', '4639', '4780', '4237', '4548', '4655', '4153', '4654', '4922', '4563', '4042', '4329', '4699', '4352', '4127', '4544', '4906', '4814', '4948', '4977', '4830', '4405', '4642', '4666', '4402', '4679', '4465', '4401', '4155', '4767', '4510', '4747', '4993', '4508', '4697', '4758', '4133', '4348', '4200', '4442', '4970', '4452', '4041', '4103', '4567', '4937', '4047', '4933', '4121', '4860', '4659', '4221', '4312', '4583', '4473', '4973', '4262', '4630', '4123', '4139', '4289', '4147', '4222', '4050', '4019', '4454', '4253', '4552', '4947', '4725', '4457', '4929', '4021', '4502', '4307', '4576', '4124', '4586', '4610', '4027', '4572', '4926', '4753', '4185', '4382', '4394', '4923', '4186', '4254', '4012', '4417', '4556', '4349', '4550', '4330', '4938', '4985', '4778', '4716', '4924', '4045', '4358', '4189', '4591', '4213', '4851', '4825', '4260', '4198', '4342', '4824', '4333', '4244', '4752', '4994', '4488', '4532', '4082', '4595', '4098', '4436', '4540', '4267', '4407', '4998', '4751', '4535', '4861', '4819', '4419', '4031', '4029', '4453', '4698', '4965', '4450', '4668', '4036', '4300', '4519', '4281', '4981', '4818', '4939', '4378', '4140', '4841', '4249', '4290', '4388', '4878', '4884', '4235', '4515', '4638', '4410', '4054', '4383', '4238', '4870', '4295', '4804', '4308', '4614', '4105', '4053', '4446', '4757', '4971', '4637', '4831', '4193', '4912', '4000', '4187', '4606', '4566', '4169', '4641', '4749', '4729', '4928', '4601', '4949', '4210', '4313', '4647', '4495', '4460', '4621', '4605', '4694', '4317', '4226', '4263', '4016', '4997', '4940', '4715', '4907', '4620', '4934', '4996', '4955', '4688', '4304', '4220', '4882', '4772', '4536', '4815', '4693', '4469', '4276', '4409', '4071', '4224', '4020', '4629', '4865', '4813', '4366', '4622', '4129', '4533', '4634', '4564', '4087', '4386', '4161', '4265', '4711', '4009', '4376', '4781', '4837', '4112', '4915', '4592', '4658', '4025', '4987', '4291', '4477', '4503', '4437', '4111', '4707', '4879', '4611', '4549', '4078', '4044', '4853', '4835', '4463', '4577', '4008', '4233', '4741', '4384', '4225', '4024', '4726', '4743', '4160', '4180', '4722', '4609', '4114', '4834', '4742', '4662', '4984', '4299', '4060', '4498', '4755', '4320', '4874', '4528', '4216', '4852', '4951', '4958', '4283', '4239', '4476', '4644', '4143', '4104', '4455', '4126', '4950', '4663', '4013', '4931', '4850', '4242', '4130', '4623', '4871', '4014', '4854', '4293', '4512', '4166', '4740', '4735', '4150', '4651', '4172', '4836', '4530', '4664', '4429', '4511', '4558', '4676', '4085', '4074', '4580', '4794', '4379', '4310', '4817', '4966', '4848', '4202', '4336', '4608', '4351', '4396', '4652', '4033', '4188', '4431', '4916', '4259', '4607', '4816', '4810', '4627', '4527', '4560', '4728', '4589', '4274', '4809', '4790', '4398', '4414', '4516', '4581', '4919', '4665', '4331', '4978', '4543', '4877', '4974', '4284', '4004', '4177', '4466', '4116', '4217', '4901', '4372', '4137', '4806', '4264', '4497', '4294', '4787', '4212', '4215', '4115', '4782', '4739', '4821', '4125', '4505', '4230', '4399', '4395', '4079', '4867', '4381', '4706', '4695', '4404', '4691', '4075', '4353', '4301', '4876', '4731', '4523', '4246', '4529', '4412', '4784', '4449', '4229', '4616', '4158', '4002', '4318', '4377', '4205', '4911', '4777', '4792', '4271', '4763', '4141', '4287', '4890', '4279', '4829', '4646', '4840', '4089', '4880', '4067', '4918', '4059', '4109', '4164', '4863', '4883', '4909', '4361', '4174', '4960', '4302', '4003', '4236', '4846', '4034', '4324', '4513', '4765', '4596', '4900', '4007', '4603', '4474', '4439', '4805', '4015', '4496', '4953', '4363', '4551', '4459', '4063', '4983', '4881', '4365', '4604', '4587', '4798', '4005', '4163', '4421', '4471', '4826', '4144', '4635', '4600', '4913', '4640', '4247', '4766', '4779', '4280', '4391', '4891', '4636', '4546', '4683', '4181', '4081', '4862', '4458', '4037', '4321', '4786', '4717', '4628', '4154', '4326', '4032', '4873', '4151', '4905', '4270', '4156', '4733', '4980', '4866', '4325', '4055', '4467', '4480', '4286', '4191', '4762', '4322', '4574', '4022', '4056', '4770', '4451', '4448', '4845', '4341', '4433', '4245', '4684', '4671', '4093', '4920', '4272', '4745', '4799', '4761', '4250', '4578', '4347', '4499', '4526', '4369', '4162', '4537', '4434', '4893', '4120', '4962', '4667', '4525', '4091', '4462', '4182', '4738', '4935', '4173', '4490', '4571', '4424', '4894', '4051', '4214', '4823', '4096', '4206', '4598', '4943', '4701', '4649', '4807', '4107', '4435', '4456', '4083', '4612', '4721', '4472', '4146', '4925', '4340', '4789', '4277', '4375', '4211', '4427', '4547', '4690', '4613', '4727', '4006', '4203', '4430', '4223', '4039', '4932', '4296', '4108', '4278', '4832', '4422', '4917', '4470', '4183', '4887', '4076', '4485', '4597', '4443', '4257', '4991', '4944', '4196', '4672', '4397', '4097', '4119', '4077', '4773', '4602', '4538', '4479', '4968', '4159', '4539', '4956', '4710', '4812', '4902', '4569', '4954', '4385', '4128', '4936', '4416', '4148', '4632', '4759', '4117', '4896', '4392', '4864', '4316', '4132', '4319', '4969', '4175', '4484', '4903', '4910', '4350', '4332', '4952', '4176', '4594', '4709', '4509', '4178', '4167', '4545', '4857', '4617', '4501', '4859', '4207', '4275', '4687', '4049', '4579', '4046', '4921', '4113', '4898', '4681', '4052', '4415', '4064', '4184', '4895', '4744', '4685', '4084', '4305', '4899', '4559', '4208', '4057', '4507', '4258', '4355', '4086', '4373', '4323', '4541', '4297', '4483', '4889', '4531', '4327', '4441', '4914', '4303', '4677', '4445', '4802', '4343', '4585', '4338', '4524', '4590', '4624', '4288', '4704', '4134', '4043', '4720', '4058', '4328', '4095', '4026', '4423', '4657', '4118', '4633', '4487', '4822', '4904', '4255', '4001', '4387', '4500', '4190', '4686', '4995', '4661', '4783', '4992', '4165', '4065', '4927', '4306', '4856', '4292', '4420', '4963', '4468', '4240', '4724', '4432', '4447', '4518', '4028', '4670', '4339', '4771', '4018', '4489', '4110', '4708', '4945', '4136', '4492', '4930', '4090', '4734', '4886', '4542', '4227', '4486', '4491', '4713', '4986', '4068', '4048', '4975', '4570', '4842', '4475', '4131', '4555', '4428', '4776', '4101', '4273', '4811', '4345', '5000', '4653', '4256', '4209', '4769', '4946', '4561', '4080', '4461', '4820', '4311', '4959', '4750', '4795', '4748', '4368', '4506', '4335', '4346', '4568', '4675', '4692', '4774', '4413', '4370', '4723', '4521', '4885', '4678', '4897', '4066', '4674', '4106', '4626', '4389', '4204', '4839', '4023', '4712', '4145', '4035', '4357', '4756', '4648', '4972', '4157', '4406', '4615', '4061', '4219', '4791', '4660', '4073', '4356', '4072', '4599', '4359', '4094', '4673', '4696', '4796', '4282', '4714', '4522', '4736', '4775', '4760', '4400', '4847', '4228', '4803', '4908', '4732', '4645', '4122', '4218', '4478', '4941', '4892', '4364', '4403', '4152', '4444', '4360', '4354', '4241', '4494', '4367', '4808', '4261', '4088', '4573', '4554', '4248', '4371', '4393', '4268', '4201', '4038', '4788', '4593', '4040', '4801', '4582', '4309', '4976', '4374', '4869', '4380', '4514', '4243', '4362', '4849', '4680', '4888', '4764', '4618', '4838', '4828', '4643', '4010', '4827', '4957', '4099', '4875', '4843', '4737', '4102', '4979', '4011', '4504', '4440', '4746', '4557', '4426', '4553', '4656', '4868', '4689', '4988', '4703', '4967', '4069', '4619', '4334', '4669', '4785', '4464', '4562', '4961', '4625', '4754', '4797', '4481', '4705', '4199', '4337', '4062', '4138', '4702', '4534', '4168', '4418', '4092', '4682', '4520', '4030', '4171', '4650', '4858', '4411', '4999', '4252', '4197', '4170', '4942', '4631', '4990', '4179', '4285', '4700', '4482', '4575', '4800', '4070', '4251', '4344', '4982', '4719', '4390', '4149', '4100', '4194', '4269', '4855', '4314', '4718', '4232', '4730', '4438', '4588', '4195', '4192', '4493', '4517', '4833', '4234', '4989', '4315', '4844', '4142', '4408', '4584', '4425'] a.shift end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_array_unshift.rb
benchmark-ips/bm_array_unshift.rb
Benchmark.ips do |x| x.report("unshift") do a = ['4768', '4964', '4266', '4872', '4231', '4017', '4565', '4793', '4298', '4135', '4639', '4780', '4237', '4548', '4655', '4153', '4654', '4922', '4563', '4042', '4329', '4699', '4352', '4127', '4544', '4906', '4814', '4948', '4977', '4830', '4405', '4642', '4666', '4402', '4679', '4465', '4401', '4155', '4767', '4510', '4747', '4993', '4508', '4697', '4758', '4133', '4348', '4200', '4442', '4970', '4452', '4041', '4103', '4567', '4937', '4047', '4933', '4121', '4860', '4659', '4221', '4312', '4583', '4473', '4973', '4262', '4630', '4123', '4139', '4289', '4147', '4222', '4050', '4019', '4454', '4253', '4552', '4947', '4725', '4457', '4929', '4021', '4502', '4307', '4576', '4124', '4586', '4610', '4027', '4572', '4926', '4753', '4185', '4382', '4394', '4923', '4186', '4254', '4012', '4417', '4556', '4349', '4550', '4330', '4938', '4985', '4778', '4716', '4924', '4045', '4358', '4189', '4591', '4213', '4851', '4825', '4260', '4198', '4342', '4824', '4333', '4244', '4752', '4994', '4488', '4532', '4082', '4595', '4098', '4436', '4540', '4267', '4407', '4998', '4751', '4535', '4861', '4819', '4419', '4031', '4029', '4453', '4698', '4965', '4450', '4668', '4036', '4300', '4519', '4281', '4981', '4818', '4939', '4378', '4140', '4841', '4249', '4290', '4388', '4878', '4884', '4235', '4515', '4638', '4410', '4054', '4383', '4238', '4870', '4295', '4804', '4308', '4614', '4105', '4053', '4446', '4757', '4971', '4637', '4831', '4193', '4912', '4000', '4187', '4606', '4566', '4169', '4641', '4749', '4729', '4928', '4601', '4949', '4210', '4313', '4647', '4495', '4460', '4621', '4605', '4694', '4317', '4226', '4263', '4016', '4997', '4940', '4715', '4907', '4620', '4934', '4996', '4955', '4688', '4304', '4220', '4882', '4772', '4536', '4815', '4693', '4469', '4276', '4409', '4071', '4224', '4020', '4629', '4865', '4813', '4366', '4622', '4129', '4533', '4634', '4564', '4087', '4386', '4161', '4265', '4711', '4009', '4376', '4781', '4837', '4112', '4915', '4592', '4658', '4025', '4987', '4291', '4477', '4503', '4437', '4111', '4707', '4879', '4611', '4549', '4078', '4044', '4853', '4835', '4463', '4577', '4008', '4233', '4741', '4384', '4225', '4024', '4726', '4743', '4160', '4180', '4722', '4609', '4114', '4834', '4742', '4662', '4984', '4299', '4060', '4498', '4755', '4320', '4874', '4528', '4216', '4852', '4951', '4958', '4283', '4239', '4476', '4644', '4143', '4104', '4455', '4126', '4950', '4663', '4013', '4931', '4850', '4242', '4130', '4623', '4871', '4014', '4854', '4293', '4512', '4166', '4740', '4735', '4150', '4651', '4172', '4836', '4530', '4664', '4429', '4511', '4558', '4676', '4085', '4074', '4580', '4794', '4379', '4310', '4817', '4966', '4848', '4202', '4336', '4608', '4351', '4396', '4652', '4033', '4188', '4431', '4916', '4259', '4607', '4816', '4810', '4627', '4527', '4560', '4728', '4589', '4274', '4809', '4790', '4398', '4414', '4516', '4581', '4919', '4665', '4331', '4978', '4543', '4877', '4974', '4284', '4004', '4177', '4466', '4116', '4217', '4901', '4372', '4137', '4806', '4264', '4497', '4294', '4787', '4212', '4215', '4115', '4782', '4739', '4821', '4125', '4505', '4230', '4399', '4395', '4079', '4867', '4381', '4706', '4695', '4404', '4691', '4075', '4353', '4301', '4876', '4731', '4523', '4246', '4529', '4412', '4784', '4449', '4229', '4616', '4158', '4002', '4318', '4377', '4205', '4911', '4777', '4792', '4271', '4763', '4141', '4287', '4890', '4279', '4829', '4646', '4840', '4089', '4880', '4067', '4918', '4059', '4109', '4164', '4863', '4883', '4909', '4361', '4174', '4960', '4302', '4003', '4236', '4846', '4034', '4324', '4513', '4765', '4596', '4900', '4007', '4603', '4474', '4439', '4805', '4015', '4496', '4953', '4363', '4551', '4459', '4063', '4983', '4881', '4365', '4604', '4587', '4798', '4005', '4163', '4421', '4471', '4826', '4144', '4635', '4600', '4913', '4640', '4247', '4766', '4779', '4280', '4391', '4891', '4636', '4546', '4683', '4181', '4081', '4862', '4458', '4037', '4321', '4786', '4717', '4628', '4154', '4326', '4032', '4873', '4151', '4905', '4270', '4156', '4733', '4980', '4866', '4325', '4055', '4467', '4480', '4286', '4191', '4762', '4322', '4574', '4022', '4056', '4770', '4451', '4448', '4845', '4341', '4433', '4245', '4684', '4671', '4093', '4920', '4272', '4745', '4799', '4761', '4250', '4578', '4347', '4499', '4526', '4369', '4162', '4537', '4434', '4893', '4120', '4962', '4667', '4525', '4091', '4462', '4182', '4738', '4935', '4173', '4490', '4571', '4424', '4894', '4051', '4214', '4823', '4096', '4206', '4598', '4943', '4701', '4649', '4807', '4107', '4435', '4456', '4083', '4612', '4721', '4472', '4146', '4925', '4340', '4789', '4277', '4375', '4211', '4427', '4547', '4690', '4613', '4727', '4006', '4203', '4430', '4223', '4039', '4932', '4296', '4108', '4278', '4832', '4422', '4917', '4470', '4183', '4887', '4076', '4485', '4597', '4443', '4257', '4991', '4944', '4196', '4672', '4397', '4097', '4119', '4077', '4773', '4602', '4538', '4479', '4968', '4159', '4539', '4956', '4710', '4812', '4902', '4569', '4954', '4385', '4128', '4936', '4416', '4148', '4632', '4759', '4117', '4896', '4392', '4864', '4316', '4132', '4319', '4969', '4175', '4484', '4903', '4910', '4350', '4332', '4952', '4176', '4594', '4709', '4509', '4178', '4167', '4545', '4857', '4617', '4501', '4859', '4207', '4275', '4687', '4049', '4579', '4046', '4921', '4113', '4898', '4681', '4052', '4415', '4064', '4184', '4895', '4744', '4685', '4084', '4305', '4899', '4559', '4208', '4057', '4507', '4258', '4355', '4086', '4373', '4323', '4541', '4297', '4483', '4889', '4531', '4327', '4441', '4914', '4303', '4677', '4445', '4802', '4343', '4585', '4338', '4524', '4590', '4624', '4288', '4704', '4134', '4043', '4720', '4058', '4328', '4095', '4026', '4423', '4657', '4118', '4633', '4487', '4822', '4904', '4255', '4001', '4387', '4500', '4190', '4686', '4995', '4661', '4783', '4992', '4165', '4065', '4927', '4306', '4856', '4292', '4420', '4963', '4468', '4240', '4724', '4432', '4447', '4518', '4028', '4670', '4339', '4771', '4018', '4489', '4110', '4708', '4945', '4136', '4492', '4930', '4090', '4734', '4886', '4542', '4227', '4486', '4491', '4713', '4986', '4068', '4048', '4975', '4570', '4842', '4475', '4131', '4555', '4428', '4776', '4101', '4273', '4811', '4345', '5000', '4653', '4256', '4209', '4769', '4946', '4561', '4080', '4461', '4820', '4311', '4959', '4750', '4795', '4748', '4368', '4506', '4335', '4346', '4568', '4675', '4692', '4774', '4413', '4370', '4723', '4521', '4885', '4678', '4897', '4066', '4674', '4106', '4626', '4389', '4204', '4839', '4023', '4712', '4145', '4035', '4357', '4756', '4648', '4972', '4157', '4406', '4615', '4061', '4219', '4791', '4660', '4073', '4356', '4072', '4599', '4359', '4094', '4673', '4696', '4796', '4282', '4714', '4522', '4736', '4775', '4760', '4400', '4847', '4228', '4803', '4908', '4732', '4645', '4122', '4218', '4478', '4941', '4892', '4364', '4403', '4152', '4444', '4360', '4354', '4241', '4494', '4367', '4808', '4261', '4088', '4573', '4554', '4248', '4371', '4393', '4268', '4201', '4038', '4788', '4593', '4040', '4801', '4582', '4309', '4976', '4374', '4869', '4380', '4514', '4243', '4362', '4849', '4680', '4888', '4764', '4618', '4838', '4828', '4643', '4010', '4827', '4957', '4099', '4875', '4843', '4737', '4102', '4979', '4011', '4504', '4440', '4746', '4557', '4426', '4553', '4656', '4868', '4689', '4988', '4703', '4967', '4069', '4619', '4334', '4669', '4785', '4464', '4562', '4961', '4625', '4754', '4797', '4481', '4705', '4199', '4337', '4062', '4138', '4702', '4534', '4168', '4418', '4092', '4682', '4520', '4030', '4171', '4650', '4858', '4411', '4999', '4252', '4197', '4170', '4942', '4631', '4990', '4179', '4285', '4700', '4482', '4575', '4800', '4070', '4251', '4344', '4982', '4719', '4390', '4149', '4100', '4194', '4269', '4855', '4314', '4718', '4232', '4730', '4438', '4588', '4195', '4192', '4493', '4517', '4833', '4234', '4989', '4315', '4844', '4142', '4408', '4584', '4425'] a.unshift('aaa', 'bbb', 'ccc') end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_is_number.rb
benchmark-ips/bm_is_number.rb
# Why .$$is_number is better than isNaN: # # # Warming up -------------------------------------- # .$$is_number 106.722k i/100ms # isNaN() 105.040k i/100ms # obj.$$is_number 106.864k i/100ms # isNaN(obj) 89.287k i/100ms # Calculating ------------------------------------- # .$$is_number 12.052M (± 6.6%) i/s - 59.978M in 5.002614s # isNaN() 12.338M (± 5.4%) i/s - 61.448M in 4.997957s # obj.$$is_number 12.514M (± 6.8%) i/s - 62.302M in 5.005715s # isNaN(obj) 4.211M (± 5.9%) i/s - 20.982M in 5.001643s # # Comparison: # obj.$$is_number: 12513664.2 i/s # isNaN(): 12338259.3 i/s - same-ish: difference falls within error # .$$is_number: 12051756.8 i/s - same-ish: difference falls within error # isNaN(obj): 4211175.7 i/s - 2.97x slower # Benchmark.ips do |x| number = 123 number_obj = 123.itself x.report(".$$is_number") { number.JS['$$is_number'] } x.report("isNaN()") { `!isNaN(number)` } x.report("obj.$$is_number") { number_obj.JS['$$is_number'] } x.report("isNaN(obj)") { `!isNaN(number_obj)` } x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_constants_lookup.rb
benchmark-ips/bm_constants_lookup.rb
module A module B module C Benchmark.ips do |x| x.report("Kernel") { Kernel } x.report("::Kernel") { ::Kernel } x.report("B") { B } x.report("B::C") { B::C } x.compare! end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_while_true_vs_loop.rb
benchmark-ips/bm_while_true_vs_loop.rb
Benchmark.ips do |x| x.report('while true') do n = 0 while true n += 1 break if n == 10000 end end x.report('loop') do n = 0 loop do n += 1 break if n == 10000 end end x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark-ips/bm_truthy.rb
benchmark-ips/bm_truthy.rb
Benchmark.ips do |x| %x{ // Old version truthy logic var old_version = function(x) { return x !== nil && x != null && (!x.$$is_boolean || x == true); } // New version truthy logic var new_version_1 = function(val) { return undefined !== val && null !== val && false !== val && nil !== val && (!(val instanceof Boolean) || true === val.valueOf()); } // Alternative new version truthy logic var new_version_2 = function(val) { return undefined !== val && null !== val && false !== val && nil !== val && !(val instanceof Boolean && false === val.valueOf()); } // Alternative new version, nil&false first var new_version_3 = function(val) { return false !== val && nil !== val && undefined !== val && null !== val && !(val instanceof Boolean && false === val.valueOf()); } // Alternative new version truthy logic that unsupports boxed booleans var new_unboxed = function(val) { return undefined !== val && null !== val && false !== val && nil !== val; } } values = [123,243,35,"sd",false,nil,123413234,120412,0,1234.1234,0.34,false,false,true,"sadfasf","","0",13,123,nil,Object.new,[]] x.time = 32 x.report('old_version') { values.map(&`old_version`) } x.report('new_version_1') { values.map(&`new_version_1`) } x.report('new_version_2') { values.map(&`new_version_2`) } x.report('new_version_3') { values.map(&`new_version_3`) } x.report('new_unboxed') { values.map(&`new_unboxed`) } x.compare! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_hash_has_key_string.rb
benchmark/bm_hash_has_key_string.rb
h = {} 10_000.times do |i| h[i.to_s] = nil end 10_000.times do |i| h.has_key?(i.to_s) end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_hash_has_value_object.rb
benchmark/bm_hash_has_value_object.rb
h = {} 10_000.times do |i| h[Object.new] = i * 2 end 1_000.times do |i| h.has_value?(i * 2) end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_array_uniq_bang_numbers.rb
benchmark/bm_array_uniq_bang_numbers.rb
a = [4768, 4964, 4266, 4872, 4231, 4017, 4565, 4793, 4298, 4135, 4639, 4780, 4237, 4548, 4655, 4153, 4654, 4922, 4563, 4042, 4329, 4699, 4352, 4127, 4544, 4906, 4814, 4948, 4977, 4830, 4405, 4642, 4666, 4402, 4679, 4465, 4401, 4155, 4767, 4510, 4747, 4993, 4508, 4697, 4758, 4133, 4348, 4200, 4442, 4970, 4452, 4041, 4103, 4567, 4937, 4047, 4933, 4121, 4860, 4659, 4221, 4312, 4583, 4473, 4973, 4262, 4630, 4123, 4139, 4289, 4147, 4222, 4050, 4019, 4454, 4253, 4552, 4947, 4725, 4457, 4929, 4021, 4502, 4307, 4576, 4124, 4586, 4610, 4027, 4572, 4926, 4753, 4185, 4382, 4394, 4923, 4186, 4254, 4012, 4417, 4556, 4349, 4550, 4330, 4938, 4985, 4778, 4716, 4924, 4045, 4358, 4189, 4591, 4213, 4851, 4825, 4260, 4198, 4342, 4824, 4333, 4244, 4752, 4994, 4488, 4532, 4082, 4595, 4098, 4436, 4540, 4267, 4407, 4998, 4751, 4535, 4861, 4819, 4419, 4031, 4029, 4453, 4698, 4965, 4450, 4668, 4036, 4300, 4519, 4281, 4981, 4818, 4939, 4378, 4140, 4841, 4249, 4290, 4388, 4878, 4884, 4235, 4515, 4638, 4410, 4054, 4383, 4238, 4870, 4295, 4804, 4308, 4614, 4105, 4053, 4446, 4757, 4971, 4637, 4831, 4193, 4912, 4000, 4187, 4606, 4566, 4169, 4641, 4749, 4729, 4928, 4601, 4949, 4210, 4313, 4647, 4495, 4460, 4621, 4605, 4694, 4317, 4226, 4263, 4016, 4997, 4940, 4715, 4907, 4620, 4934, 4996, 4955, 4688, 4304, 4220, 4882, 4772, 4536, 4815, 4693, 4469, 4276, 4409, 4071, 4224, 4020, 4629, 4865, 4813, 4366, 4622, 4129, 4533, 4634, 4564, 4087, 4386, 4161, 4265, 4711, 4009, 4376, 4781, 4837, 4112, 4915, 4592, 4658, 4025, 4987, 4291, 4477, 4503, 4437, 4111, 4707, 4879, 4611, 4549, 4078, 4044, 4853, 4835, 4463, 4577, 4008, 4233, 4741, 4384, 4225, 4024, 4726, 4743, 4160, 4180, 4722, 4609, 4114, 4834, 4742, 4662, 4984, 4299, 4060, 4498, 4755, 4320, 4874, 4528, 4216, 4852, 4951, 4958, 4283, 4239, 4476, 4644, 4143, 4104, 4455, 4126, 4950, 4663, 4013, 4931, 4850, 4242, 4130, 4623, 4871, 4014, 4854, 4293, 4512, 4166, 4740, 4735, 4150, 4651, 4172, 4836, 4530, 4664, 4429, 4511, 4558, 4676, 4085, 4074, 4580, 4794, 4379, 4310, 4817, 4966, 4848, 4202, 4336, 4608, 4351, 4396, 4652, 4033, 4188, 4431, 4916, 4259, 4607, 4816, 4810, 4627, 4527, 4560, 4728, 4589, 4274, 4809, 4790, 4398, 4414, 4516, 4581, 4919, 4665, 4331, 4978, 4543, 4877, 4974, 4284, 4004, 4177, 4466, 4116, 4217, 4901, 4372, 4137, 4806, 4264, 4497, 4294, 4787, 4212, 4215, 4115, 4782, 4739, 4821, 4125, 4505, 4230, 4399, 4395, 4079, 4867, 4381, 4706, 4695, 4404, 4691, 4075, 4353, 4301, 4876, 4731, 4523, 4246, 4529, 4412, 4784, 4449, 4229, 4616, 4158, 4002, 4318, 4377, 4205, 4911, 4777, 4792, 4271, 4763, 4141, 4287, 4890, 4279, 4829, 4646, 4840, 4089, 4880, 4067, 4918, 4059, 4109, 4164, 4863, 4883, 4909, 4361, 4174, 4960, 4302, 4003, 4236, 4846, 4034, 4324, 4513, 4765, 4596, 4900, 4007, 4603, 4474, 4439, 4805, 4015, 4496, 4953, 4363, 4551, 4459, 4063, 4983, 4881, 4365, 4604, 4587, 4798, 4005, 4163, 4421, 4471, 4826, 4144, 4635, 4600, 4913, 4640, 4247, 4766, 4779, 4280, 4391, 4891, 4636, 4546, 4683, 4181, 4081, 4862, 4458, 4037, 4321, 4786, 4717, 4628, 4154, 4326, 4032, 4873, 4151, 4905, 4270, 4156, 4733, 4980, 4866, 4325, 4055, 4467, 4480, 4286, 4191, 4762, 4322, 4574, 4022, 4056, 4770, 4451, 4448, 4845, 4341, 4433, 4245, 4684, 4671, 4093, 4920, 4272, 4745, 4799, 4761, 4250, 4578, 4347, 4499, 4526, 4369, 4162, 4537, 4434, 4893, 4120, 4962, 4667, 4525, 4091, 4462, 4182, 4738, 4935, 4173, 4490, 4571, 4424, 4894, 4051, 4214, 4823, 4096, 4206, 4598, 4943, 4701, 4649, 4807, 4107, 4435, 4456, 4083, 4612, 4721, 4472, 4146, 4925, 4340, 4789, 4277, 4375, 4211, 4427, 4547, 4690, 4613, 4727, 4006, 4203, 4430, 4223, 4039, 4932, 4296, 4108, 4278, 4832, 4422, 4917, 4470, 4183, 4887, 4076, 4485, 4597, 4443, 4257, 4991, 4944, 4196, 4672, 4397, 4097, 4119, 4077, 4773, 4602, 4538, 4479, 4968, 4159, 4539, 4956, 4710, 4812, 4902, 4569, 4954, 4385, 4128, 4936, 4416, 4148, 4632, 4759, 4117, 4896, 4392, 4864, 4316, 4132, 4319, 4969, 4175, 4484, 4903, 4910, 4350, 4332, 4952, 4176, 4594, 4709, 4509, 4178, 4167, 4545, 4857, 4617, 4501, 4859, 4207, 4275, 4687, 4049, 4579, 4046, 4921, 4113, 4898, 4681, 4052, 4415, 4064, 4184, 4895, 4744, 4685, 4084, 4305, 4899, 4559, 4208, 4057, 4507, 4258, 4355, 4086, 4373, 4323, 4541, 4297, 4483, 4889, 4531, 4327, 4441, 4914, 4303, 4677, 4445, 4802, 4343, 4585, 4338, 4524, 4590, 4624, 4288, 4704, 4134, 4043, 4720, 4058, 4328, 4095, 4026, 4423, 4657, 4118, 4633, 4487, 4822, 4904, 4255, 4001, 4387, 4500, 4190, 4686, 4995, 4661, 4783, 4992, 4165, 4065, 4927, 4306, 4856, 4292, 4420, 4963, 4468, 4240, 4724, 4432, 4447, 4518, 4028, 4670, 4339, 4771, 4018, 4489, 4110, 4708, 4945, 4136, 4492, 4930, 4090, 4734, 4886, 4542, 4227, 4486, 4491, 4713, 4986, 4068, 4048, 4975, 4570, 4842, 4475, 4131, 4555, 4428, 4776, 4101, 4273, 4811, 4345, 5000, 4653, 4256, 4209, 4769, 4946, 4561, 4080, 4461, 4820, 4311, 4959, 4750, 4795, 4748, 4368, 4506, 4335, 4346, 4568, 4675, 4692, 4774, 4413, 4370, 4723, 4521, 4885, 4678, 4897, 4066, 4674, 4106, 4626, 4389, 4204, 4839, 4023, 4712, 4145, 4035, 4357, 4756, 4648, 4972, 4157, 4406, 4615, 4061, 4219, 4791, 4660, 4073, 4356, 4072, 4599, 4359, 4094, 4673, 4696, 4796, 4282, 4714, 4522, 4736, 4775, 4760, 4400, 4847, 4228, 4803, 4908, 4732, 4645, 4122, 4218, 4478, 4941, 4892, 4364, 4403, 4152, 4444, 4360, 4354, 4241, 4494, 4367, 4808, 4261, 4088, 4573, 4554, 4248, 4371, 4393, 4268, 4201, 4038, 4788, 4593, 4040, 4801, 4582, 4309, 4976, 4374, 4869, 4380, 4514, 4243, 4362, 4849, 4680, 4888, 4764, 4618, 4838, 4828, 4643, 4010, 4827, 4957, 4099, 4875, 4843, 4737, 4102, 4979, 4011, 4504, 4440, 4746, 4557, 4426, 4553, 4656, 4868, 4689, 4988, 4703, 4967, 4069, 4619, 4334, 4669, 4785, 4464, 4562, 4961, 4625, 4754, 4797, 4481, 4705, 4199, 4337, 4062, 4138, 4702, 4534, 4168, 4418, 4092, 4682, 4520, 4030, 4171, 4650, 4858, 4411, 4999, 4252, 4197, 4170, 4942, 4631, 4990, 4179, 4285, 4700, 4482, 4575, 4800, 4070, 4251, 4344, 4982, 4719, 4390, 4149, 4100, 4194, 4269, 4855, 4314, 4718, 4232, 4730, 4438, 4588, 4195, 4192, 4493, 4517, 4833, 4234, 4989, 4315, 4844, 4142, 4408, 4584, 4425] 1000.times do a.uniq! end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_hash_assoc_object.rb
benchmark/bm_hash_assoc_object.rb
h = {} a = [] 10_000.times do |i| a[i] = Object.new h[a[i]] = nil end 10_000.times do |i| k, v = h.assoc(a[i]) end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_hash_reject_bang_object.rb
benchmark/bm_hash_reject_bang_object.rb
h = {} 10_000.times do |i| h[Object.new] = i end 10_000.times do |i| h.reject!{|k, v| v <= i} end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_hash_shift_object.rb
benchmark/bm_hash_shift_object.rb
h = {} 10_000.times do |i| h[Object.new] = nil end 1_000_000.times do k, v = h.shift h[k] = v end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_hash_literal_string_small.rb
benchmark/bm_hash_literal_string_small.rb
100_000.times do h = {'a' => 'b', 'c' => 'd', 'e' => 'f', 'g' => 'h', 'i' => 'j', 'k' => 'l', 'm' => 'n', 'o' => 'p'} end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/benchmark/bm_hash_has_key_object.rb
benchmark/bm_hash_has_key_object.rb
h = {} a = [] 10_000.times do |i| a[i] = Object.new h[a[i]] = nil end 10_000.times do |i| h.has_key?(a[i]) end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false