* lib: revert r31635-r31638 and untabify with expand(1).

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@31641 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
nobu 2011-05-19 00:07:25 +00:00
parent 1fae66fca2
commit d371e3583e
59 changed files with 1971 additions and 1967 deletions

View File

@ -1,3 +1,7 @@
Thu May 19 09:07:08 2011 Nobuyoshi Nakada <nobu@ruby-lang.org>
* lib: revert r31635-r31638 and untabify with expand(1).
Thu May 19 07:47:26 2011 Martin Bosslet <Martin.Bosslet@googlemail.com> Thu May 19 07:47:26 2011 Martin Bosslet <Martin.Bosslet@googlemail.com>
* test/openssl/test_pkey_rsa.rb: Add tests for sign/verify. * test/openssl/test_pkey_rsa.rb: Add tests for sign/verify.

View File

@ -520,14 +520,14 @@ module Benchmark
cutime.__send__(op, x.cutime), cutime.__send__(op, x.cutime),
cstime.__send__(op, x.cstime), cstime.__send__(op, x.cstime),
real.__send__(op, x.real) real.__send__(op, x.real)
) )
else else
Benchmark::Tms.new(utime.__send__(op, x), Benchmark::Tms.new(utime.__send__(op, x),
stime.__send__(op, x), stime.__send__(op, x),
cutime.__send__(op, x), cutime.__send__(op, x),
cstime.__send__(op, x), cstime.__send__(op, x),
real.__send__(op, x) real.__send__(op, x)
) )
end end
end end
end end
@ -548,13 +548,13 @@ if __FILE__ == $0
x.report("for:") {for _ in 1..n; _ = "1"; end} # Benchmark.measure x.report("for:") {for _ in 1..n; _ = "1"; end} # Benchmark.measure
x.report("times:") {n.times do ; _ = "1"; end} x.report("times:") {n.times do ; _ = "1"; end}
x.report("upto:") {1.upto(n) do ; _ = "1"; end} x.report("upto:") {1.upto(n) do ; _ = "1"; end}
end end
benchmark do benchmark do
[ [
measure{for _ in 1..n; _ = "1"; end}, # Benchmark.measure measure{for _ in 1..n; _ = "1"; end}, # Benchmark.measure
measure{n.times do ; _ = "1"; end}, measure{n.times do ; _ = "1"; end},
measure{1.upto(n) do ; _ = "1"; end} measure{1.upto(n) do ; _ = "1"; end}
] ]
end end
end end

View File

@ -82,12 +82,12 @@ class DEBUGGER__
def check_suspend def check_suspend
while MUTEX.synchronize { while MUTEX.synchronize {
if @suspend_next if @suspend_next
DEBUGGER__.waiting.push Thread.current DEBUGGER__.waiting.push Thread.current
@suspend_next = false @suspend_next = false
true true
end end
} }
end end
end end
@ -261,11 +261,11 @@ class DEBUGGER__
set_trace false set_trace false
end end
end end
if trace? if trace?
stdout.print "Trace on.\n" stdout.print "Trace on.\n"
else else
stdout.print "Trace off.\n" stdout.print "Trace off.\n"
end end
when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/ when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/
pos = $2 pos = $2
@ -304,22 +304,22 @@ class DEBUGGER__
n += 1 n += 1
end end
end end
if break_points.find{|b| b[1] == 1} if break_points.find{|b| b[1] == 1}
n = 1 n = 1
stdout.print "\n" stdout.print "\n"
stdout.print "Watchpoints:\n" stdout.print "Watchpoints:\n"
for b in break_points for b in break_points
if b[0] and b[1] == 1 if b[0] and b[1] == 1
stdout.printf " %d %s\n", n, b[2] stdout.printf " %d %s\n", n, b[2]
end
n += 1
end end
n += 1
end end
end if break_points.size == 0
if break_points.size == 0 stdout.print "No breakpoints\n"
stdout.print "No breakpoints\n" else
else stdout.print "\n"
stdout.print "\n" end
end
when /^\s*del(?:ete)?(?:\s+(\d+))?$/ when /^\s*del(?:ete)?(?:\s+(\d+))?$/
pos = $1 pos = $1
@ -375,8 +375,8 @@ class DEBUGGER__
else else
lev = 1 lev = 1
end end
@stop_next = lev @stop_next = lev
prompt = false prompt = false
when /^\s*n(?:ext)?(?:\s+(\d+))?$/ when /^\s*n(?:ext)?(?:\s+(\d+))?$/
if $1 if $1
@ -384,9 +384,9 @@ class DEBUGGER__
else else
lev = 1 lev = 1
end end
@stop_next = lev @stop_next = lev
@no_step = @frames.size - frame_pos @no_step = @frames.size - frame_pos
prompt = false prompt = false
when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/ when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/
display_frames(frame_pos) display_frames(frame_pos)
@ -408,8 +408,8 @@ class DEBUGGER__
e = b + 9 e = b + 9
end end
end end
previous_line = b previous_line = b
display_list(b, e, binding_file, binding_line) display_list(b, e, binding_file, binding_line)
when /^\s*up(?:\s+(\d+))?$/ when /^\s*up(?:\s+(\d+))?$/
previous_line = nil previous_line = nil
@ -549,359 +549,359 @@ Commands
h[elp] print this help h[elp] print this help
<everything else> evaluate <everything else> evaluate
EOHELP EOHELP
end end
def display_expressions(binding) def display_expressions(binding)
n = 1 n = 1
for d in display for d in display
if d[0] if d[0]
stdout.printf "%d: ", n stdout.printf "%d: ", n
display_expression(d[1], binding) display_expression(d[1], binding)
end
n += 1
end end
n += 1
end end
end
def display_expression(exp, binding) def display_expression(exp, binding)
stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s
end
def frame_set_pos(file, line)
if @frames[0]
@frames[0][1] = file
@frames[0][2] = line
end end
end
def display_frames(pos) def frame_set_pos(file, line)
0.upto(@frames.size - 1) do |n| if @frames[0]
if n == pos @frames[0][1] = file
stdout.print "--> " @frames[0][2] = line
end
end
def display_frames(pos)
0.upto(@frames.size - 1) do |n|
if n == pos
stdout.print "--> "
else
stdout.print " "
end
stdout.print format_frame(n)
end
end
def format_frame(pos)
_, file, line, id = @frames[pos]
sprintf "#%d %s:%s%s\n", pos + 1, file, line,
(id ? ":in `#{id.id2name}'" : "")
end
def display_list(b, e, file, line)
stdout.printf "[%d, %d] in %s\n", b, e, file
if lines = SCRIPT_LINES__[file] and lines != true
b.upto(e) do |n|
if n > 0 && lines[n-1]
if n == line
stdout.printf "=> %d %s\n", n, lines[n-1].chomp
else
stdout.printf " %d %s\n", n, lines[n-1].chomp
end
end
end
else else
stdout.print " " stdout.printf "No sourcefile available for %s\n", file
end end
stdout.print format_frame(n)
end end
end
def format_frame(pos) def line_at(file, line)
_, file, line, id = @frames[pos] lines = SCRIPT_LINES__[file]
sprintf "#%d %s:%s%s\n", pos + 1, file, line, if lines
(id ? ":in `#{id.id2name}'" : "") return "\n" if lines == true
end line = lines[line-1]
return "\n" unless line
def display_list(b, e, file, line) return line
stdout.printf "[%d, %d] in %s\n", b, e, file
if lines = SCRIPT_LINES__[file] and lines != true
b.upto(e) do |n|
if n > 0 && lines[n-1]
if n == line
stdout.printf "=> %d %s\n", n, lines[n-1].chomp
else
stdout.printf " %d %s\n", n, lines[n-1].chomp
end
end
end end
else return "\n"
stdout.printf "No sourcefile available for %s\n", file
end
end
def line_at(file, line)
lines = SCRIPT_LINES__[file]
if lines
return "\n" if lines == true
line = lines[line-1]
return "\n" unless line
return line
end
return "\n"
end
def debug_funcname(id)
if id.nil?
"toplevel"
else
id.id2name
end
end
def check_break_points(file, klass, pos, binding, id)
return false if break_points.empty?
n = 1
for b in break_points
if b[0] # valid
if b[1] == 0 # breakpoint
if (b[2] == file and b[3] == pos) or
(klass and b[2] == klass and b[3] == pos)
stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
return true
end
elsif b[1] == 1 # watchpoint
if debug_silent_eval(b[2], binding)
stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
return true
end
end
end
n += 1
end
return false
end
def excn_handle(file, line, id, binding)
if $!.class <= SystemExit
set_trace_func nil
exit
end end
if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch }) def debug_funcname(id)
stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class if id.nil?
fs = @frames.size "toplevel"
tb = caller(0)[-fs..-1]
if tb
for i in tb
stdout.printf "\tfrom %s\n", i
end
end
suspend_all
debug_command(file, line, id, binding)
end
end
def trace_func(event, file, line, id, binding, klass)
Tracer.trace_func(event, file, line, id, binding, klass) if trace?
context(Thread.current).check_suspend
@file = file
@line = line
case event
when 'line'
frame_set_pos(file, line)
if !@no_step or @frames.size == @no_step
@stop_next -= 1
@stop_next = -1 if @stop_next < 0
elsif @frames.size < @no_step
@stop_next = 0 # break here before leaving...
else else
# nothing to do. skipped. id.id2name
end
if @stop_next == 0 or check_break_points(file, nil, line, binding, id)
@no_step = nil
suspend_all
debug_command(file, line, id, binding)
end
when 'call'
@frames.unshift [binding, file, line, id]
if check_break_points(file, klass, id.id2name, binding, id)
suspend_all
debug_command(file, line, id, binding)
end
when 'c-call'
frame_set_pos(file, line)
when 'class'
@frames.unshift [binding, file, line, id]
when 'return', 'end'
if @frames.size == @finish_pos
@stop_next = 1
@finish_pos = 0
end
@frames.shift
when 'raise'
excn_handle(file, line, id, binding)
end
@last_file = file
end
end
trap("INT") { DEBUGGER__.interrupt }
@last_thread = Thread::main
@max_thread = 1
@thread_list = {Thread::main => 1}
@break_points = []
@display = []
@waiting = []
@stdout = STDOUT
class << DEBUGGER__
def stdout
@stdout
end
def stdout=(s)
@stdout = s
end
def display
@display
end
def break_points
@break_points
end
def waiting
@waiting
end
def set_trace( arg )
MUTEX.synchronize do
make_thread_list
for th, in @thread_list
context(th).set_trace arg
end end
end end
arg
end
def set_last_thread(th) def check_break_points(file, klass, pos, binding, id)
@last_thread = th return false if break_points.empty?
end n = 1
for b in break_points
if b[0] # valid
if b[1] == 0 # breakpoint
if (b[2] == file and b[3] == pos) or
(klass and b[2] == klass and b[3] == pos)
stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
return true
end
elsif b[1] == 1 # watchpoint
if debug_silent_eval(b[2], binding)
stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
return true
end
end
end
n += 1
end
return false
end
def suspend def excn_handle(file, line, id, binding)
MUTEX.synchronize do if $!.class <= SystemExit
make_thread_list set_trace_func nil
for th, in @thread_list exit
next if th == Thread.current end
context(th).set_suspend
if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch })
stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class
fs = @frames.size
tb = caller(0)[-fs..-1]
if tb
for i in tb
stdout.printf "\tfrom %s\n", i
end
end
suspend_all
debug_command(file, line, id, binding)
end end
end end
# Schedule other threads to suspend as soon as possible.
Thread.pass
end
def resume def trace_func(event, file, line, id, binding, klass)
MUTEX.synchronize do Tracer.trace_func(event, file, line, id, binding, klass) if trace?
make_thread_list context(Thread.current).check_suspend
@thread_list.each do |th,| @file = file
next if th == Thread.current @line = line
context(th).clear_suspend case event
when 'line'
frame_set_pos(file, line)
if !@no_step or @frames.size == @no_step
@stop_next -= 1
@stop_next = -1 if @stop_next < 0
elsif @frames.size < @no_step
@stop_next = 0 # break here before leaving...
else
# nothing to do. skipped.
end
if @stop_next == 0 or check_break_points(file, nil, line, binding, id)
@no_step = nil
suspend_all
debug_command(file, line, id, binding)
end
when 'call'
@frames.unshift [binding, file, line, id]
if check_break_points(file, klass, id.id2name, binding, id)
suspend_all
debug_command(file, line, id, binding)
end
when 'c-call'
frame_set_pos(file, line)
when 'class'
@frames.unshift [binding, file, line, id]
when 'return', 'end'
if @frames.size == @finish_pos
@stop_next = 1
@finish_pos = 0
end
@frames.shift
when 'raise'
excn_handle(file, line, id, binding)
end end
waiting.each do |th| @last_file = file
th.run end
end
trap("INT") { DEBUGGER__.interrupt }
@last_thread = Thread::main
@max_thread = 1
@thread_list = {Thread::main => 1}
@break_points = []
@display = []
@waiting = []
@stdout = STDOUT
class << DEBUGGER__
def stdout
@stdout
end
def stdout=(s)
@stdout = s
end
def display
@display
end
def break_points
@break_points
end
def waiting
@waiting
end
def set_trace( arg )
MUTEX.synchronize do
make_thread_list
for th, in @thread_list
context(th).set_trace arg
end
end end
waiting.clear arg
end end
# Schedule other threads to restart as soon as possible.
Thread.pass
end
def context(thread=Thread.current) def set_last_thread(th)
c = thread[:__debugger_data__] @last_thread = th
unless c
thread[:__debugger_data__] = c = Context.new
end end
c
end
def interrupt def suspend
context(@last_thread).stop_next MUTEX.synchronize do
end make_thread_list
for th, in @thread_list
def get_thread(num) next if th == Thread.current
th = @thread_list.key(num) context(th).set_suspend
unless th end
@stdout.print "No thread ##{num}\n"
throw :debug_error
end
th
end
def thread_list(num)
th = get_thread(num)
if th == Thread.current
@stdout.print "+"
else
@stdout.print " "
end
@stdout.printf "%d ", num
@stdout.print th.inspect, "\t"
file = context(th).instance_eval{@file}
if file
@stdout.print file,":",context(th).instance_eval{@line}
end
@stdout.print "\n"
end
def thread_list_all
for th in @thread_list.values.sort
thread_list(th)
end
end
def make_thread_list
hash = {}
for th in Thread::list
if @thread_list.key? th
hash[th] = @thread_list[th]
else
@max_thread += 1
hash[th] = @max_thread
end end
# Schedule other threads to suspend as soon as possible.
Thread.pass
end end
@thread_list = hash
end
def debug_thread_info(input, binding) def resume
case input MUTEX.synchronize do
when /^l(?:ist)?/ make_thread_list
make_thread_list @thread_list.each do |th,|
thread_list_all next if th == Thread.current
context(th).clear_suspend
end
waiting.each do |th|
th.run
end
waiting.clear
end
# Schedule other threads to restart as soon as possible.
Thread.pass
end
when /^c(?:ur(?:rent)?)?$/ def context(thread=Thread.current)
make_thread_list c = thread[:__debugger_data__]
thread_list(@thread_list[Thread.current]) unless c
thread[:__debugger_data__] = c = Context.new
end
c
end
when /^(?:sw(?:itch)?\s+)?(\d+)/ def interrupt
make_thread_list context(@last_thread).stop_next
th = get_thread($1.to_i) end
def get_thread(num)
th = @thread_list.key(num)
unless th
@stdout.print "No thread ##{num}\n"
throw :debug_error
end
th
end
def thread_list(num)
th = get_thread(num)
if th == Thread.current if th == Thread.current
@stdout.print "It's the current thread.\n" @stdout.print "+"
else else
thread_list(@thread_list[th]) @stdout.print " "
context(th).stop_next
th.run
return :cont
end end
@stdout.printf "%d ", num
when /^stop\s+(\d+)/ @stdout.print th.inspect, "\t"
make_thread_list file = context(th).instance_eval{@file}
th = get_thread($1.to_i) if file
if th == Thread.current @stdout.print file,":",context(th).instance_eval{@line}
@stdout.print "It's the current thread.\n"
elsif th.stop?
@stdout.print "Already stopped.\n"
else
thread_list(@thread_list[th])
context(th).suspend
end end
@stdout.print "\n"
end
when /^resume\s+(\d+)/ def thread_list_all
make_thread_list for th in @thread_list.values.sort
th = get_thread($1.to_i) thread_list(th)
if th == Thread.current end
@stdout.print "It's the current thread.\n" end
elsif !th.stop?
@stdout.print "Already running." def make_thread_list
else hash = {}
thread_list(@thread_list[th]) for th in Thread::list
th.run if @thread_list.key? th
hash[th] = @thread_list[th]
else
@max_thread += 1
hash[th] = @max_thread
end
end
@thread_list = hash
end
def debug_thread_info(input, binding)
case input
when /^l(?:ist)?/
make_thread_list
thread_list_all
when /^c(?:ur(?:rent)?)?$/
make_thread_list
thread_list(@thread_list[Thread.current])
when /^(?:sw(?:itch)?\s+)?(\d+)/
make_thread_list
th = get_thread($1.to_i)
if th == Thread.current
@stdout.print "It's the current thread.\n"
else
thread_list(@thread_list[th])
context(th).stop_next
th.run
return :cont
end
when /^stop\s+(\d+)/
make_thread_list
th = get_thread($1.to_i)
if th == Thread.current
@stdout.print "It's the current thread.\n"
elsif th.stop?
@stdout.print "Already stopped.\n"
else
thread_list(@thread_list[th])
context(th).suspend
end
when /^resume\s+(\d+)/
make_thread_list
th = get_thread($1.to_i)
if th == Thread.current
@stdout.print "It's the current thread.\n"
elsif !th.stop?
@stdout.print "Already running."
else
thread_list(@thread_list[th])
th.run
end
end end
end end
end end
end
stdout.printf "Debug.rb\n" stdout.printf "Debug.rb\n"
stdout.printf "Emacs support available.\n\n" stdout.printf "Emacs support available.\n\n"
RubyVM::InstructionSequence.compile_option = { RubyVM::InstructionSequence.compile_option = {
trace_instruction: true trace_instruction: true
} }
set_trace_func proc { |event, file, line, id, binding, klass, *rest| set_trace_func proc { |event, file, line, id, binding, klass, *rest|
DEBUGGER__.context.trace_func event, file, line, id, binding, klass DEBUGGER__.context.trace_func event, file, line, id, binding, klass
} }
end end

View File

@ -330,12 +330,12 @@ end
# :stopdoc: # :stopdoc:
def Delegator.delegating_block(mid) def Delegator.delegating_block(mid)
lambda do |*args, &block| lambda do |*args, &block|
target = self.__getobj__ target = self.__getobj__
begin begin
target.__send__(mid, *args, &block) target.__send__(mid, *args, &block)
ensure ensure
$@.delete_if {|t| /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/o =~ t} if $@ $@.delete_if {|t| /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/o =~ t} if $@
end end
end end
end end
# :startdoc: # :startdoc:
@ -368,10 +368,10 @@ def DelegateClass(superclass)
end end
end end
klass.define_singleton_method :public_instance_methods do |all=true| klass.define_singleton_method :public_instance_methods do |all=true|
super(all) - superclass.protected_instance_methods super(all) - superclass.protected_instance_methods
end end
klass.define_singleton_method :protected_instance_methods do |all=true| klass.define_singleton_method :protected_instance_methods do |all=true|
super(all) | superclass.protected_instance_methods super(all) | superclass.protected_instance_methods
end end
return klass return klass
end end
@ -405,7 +405,7 @@ if __FILE__ == $0
foo2 = SimpleDelegator.new(foo) foo2 = SimpleDelegator.new(foo)
p foo2 p foo2
foo2.instance_eval{print "foo\n"} foo2.instance_eval{print "foo\n"}
p foo.test == foo2.test # => true p foo.test == foo2.test # => true
p foo2.iter{[55,true]} # => true p foo2.iter{[55,true]} # => true
foo2.error # raise error! foo2.error # raise error!
end end

View File

@ -234,17 +234,17 @@ end
if __FILE__ == $0 if __FILE__ == $0
# example # example
list = %w(deny all list = %w(deny all
allow 192.168.1.1 allow 192.168.1.1
allow ::ffff:192.168.1.2 allow ::ffff:192.168.1.2
allow 192.168.1.3 allow 192.168.1.3
) )
addr = ["AF_INET", 10, "lc630", "192.168.1.3"] addr = ["AF_INET", 10, "lc630", "192.168.1.3"]
acl = ACL.new acl = ACL.new
p acl.allow_addr?(addr) p acl.allow_addr?(addr)
acl = ACL.new(list, ACL::DENY_ALLOW) acl = ACL.new(list, ACL::DENY_ALLOW)
p acl.allow_addr?(addr) p acl.allow_addr?(addr)
end end

View File

@ -563,7 +563,7 @@ module DRb
def load(soc) # :nodoc: def load(soc) # :nodoc:
begin begin
sz = soc.read(4) # sizeof (N) sz = soc.read(4) # sizeof (N)
rescue rescue
raise(DRbConnError, $!.message, $!.backtrace) raise(DRbConnError, $!.message, $!.backtrace)
end end
@ -812,7 +812,7 @@ module DRb
[host, port, option] [host, port, option]
else else
raise(DRbBadScheme, uri) unless uri =~ /^druby:/ raise(DRbBadScheme, uri) unless uri =~ /^druby:/
raise(DRbBadURI, 'can\'t parse uri:' + uri) raise(DRbBadURI, 'can\'t parse uri:' + uri)
end end
end end
@ -1117,7 +1117,7 @@ module DRb
result.backtrace.each do |x| result.backtrace.each do |x|
break if /`__send__'$/ =~ x break if /`__send__'$/ =~ x
if /^\(druby:\/\// =~ x if /^\(druby:\/\// =~ x
bt.push(x) bt.push(x)
else else
bt.push(prefix + x) bt.push(prefix + x)
end end
@ -1584,7 +1584,7 @@ module DRb
Thread.start(@protocol.accept) do |client| Thread.start(@protocol.accept) do |client|
@grp.add Thread.current @grp.add Thread.current
Thread.current['DRb'] = { 'client' => client , Thread.current['DRb'] = { 'client' => client ,
'server' => self } 'server' => self }
loop do loop do
begin begin
succ = false succ = false

View File

@ -1,6 +1,6 @@
=begin =begin
external service external service
Copyright (c) 2000,2002 Masatoshi SEKI Copyright (c) 2000,2002 Masatoshi SEKI
=end =end
require 'drb/drb' require 'drb/drb'

View File

@ -1,6 +1,6 @@
=begin =begin
external service manager external service manager
Copyright (c) 2000 Masatoshi SEKI Copyright (c) 2000 Masatoshi SEKI
=end =end
require 'drb/drb' require 'drb/drb'

View File

@ -60,10 +60,10 @@ module DRb
when 0; $stderr.putc "." # BN_generate_prime when 0; $stderr.putc "." # BN_generate_prime
when 1; $stderr.putc "+" # BN_generate_prime when 1; $stderr.putc "+" # BN_generate_prime
when 2; $stderr.putc "*" # searching good prime, when 2; $stderr.putc "*" # searching good prime,
# n = #of try, # n = #of try,
# but also data from BN_generate_prime # but also data from BN_generate_prime
when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q, when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
# but also data from BN_generate_prime # but also data from BN_generate_prime
else; $stderr.putc "*" # BN_generate_prime else; $stderr.putc "*" # BN_generate_prime
end end
} }
@ -82,16 +82,16 @@ module DRb
cert.extensions = [ cert.extensions = [
ef.create_extension("basicConstraints","CA:FALSE"), ef.create_extension("basicConstraints","CA:FALSE"),
ef.create_extension("subjectKeyIdentifier", "hash") ] ef.create_extension("subjectKeyIdentifier", "hash") ]
ef.issuer_certificate = cert ef.issuer_certificate = cert
cert.add_extension(ef.create_extension("authorityKeyIdentifier", cert.add_extension(ef.create_extension("authorityKeyIdentifier",
"keyid:always,issuer:always")) "keyid:always,issuer:always"))
if comment = self[:SSLCertComment] if comment = self[:SSLCertComment]
cert.add_extension(ef.create_extension("nsComment", comment)) cert.add_extension(ef.create_extension("nsComment", comment))
end end
cert.sign(rsa, OpenSSL::Digest::SHA1.new) cert.sign(rsa, OpenSSL::Digest::SHA1.new)
@cert = cert @cert = cert
@pkey = rsa @pkey = rsa
end end
def setup_ssl_context def setup_ssl_context
@ -117,7 +117,7 @@ module DRb
[host, port, option] [host, port, option]
else else
raise(DRbBadScheme, uri) unless uri =~ /^drbssl:/ raise(DRbBadScheme, uri) unless uri =~ /^drbssl:/
raise(DRbBadURI, 'can\'t parse uri:' + uri) raise(DRbBadURI, 'can\'t parse uri:' + uri)
end end
end end
@ -172,13 +172,13 @@ module DRb
def accept def accept
begin begin
while true while true
soc = @socket.accept soc = @socket.accept
break if (@acl ? @acl.allow_socket?(soc) : true) break if (@acl ? @acl.allow_socket?(soc) : true)
soc.close soc.close
end end
ssl = @config.accept(soc) ssl = @config.accept(soc)
self.class.new(uri, ssl, @config, true) self.class.new(uri, ssl, @config, true)
rescue OpenSSL::SSL::SSLError rescue OpenSSL::SSL::SSLError
warn("#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})") if @config[:verbose] warn("#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})") if @config[:verbose]
retry retry

View File

@ -14,7 +14,7 @@ module DRb
[filename, option] [filename, option]
else else
raise(DRbBadScheme, uri) unless uri =~ /^drbunix:/ raise(DRbBadScheme, uri) unless uri =~ /^drbunix:/
raise(DRbBadURI, 'can\'t parse uri:' + uri) raise(DRbBadURI, 'can\'t parse uri:' + uri)
end end
end end

View File

@ -1,8 +1,8 @@
# #
# e2mmap.rb - for ruby 1.1 # e2mmap.rb - for ruby 1.1
# $Release Version: 2.0$ # $Release Version: 2.0$
# $Revision: 1.10 $ # $Revision: 1.10 $
# by Keiju ISHITSUKA # by Keiju ISHITSUKA
# #
# -- # --
# Usage: # Usage:
@ -60,19 +60,19 @@ module Exception2MessageMapper
def bind(cl) def bind(cl)
self.module_eval %[ self.module_eval %[
def Raise(err = nil, *rest) def Raise(err = nil, *rest)
Exception2MessageMapper.Raise(self.class, err, *rest) Exception2MessageMapper.Raise(self.class, err, *rest)
end end
alias Fail Raise alias Fail Raise
def self.included(mod) def self.included(mod)
mod.extend Exception2MessageMapper mod.extend Exception2MessageMapper
end end
] ]
end end
# Fail(err, *rest) # Fail(err, *rest)
# err: exception # err: exception
# rest: message arguments # rest: message arguments
# #
def Raise(err = nil, *rest) def Raise(err = nil, *rest)
E2MM.Raise(self, err, *rest) E2MM.Raise(self, err, *rest)
@ -81,19 +81,19 @@ module Exception2MessageMapper
alias fail Raise alias fail Raise
# def_e2message(c, m) # def_e2message(c, m)
# c: exception # c: exception
# m: message_form # m: message_form
# define exception c with message m. # define exception c with message m.
# #
def def_e2message(c, m) def def_e2message(c, m)
E2MM.def_e2message(self, c, m) E2MM.def_e2message(self, c, m)
end end
# def_exception(n, m, s) # def_exception(n, m, s)
# n: exception_name # n: exception_name
# m: message_form # m: message_form
# s: superclass(default: StandardError) # s: superclass(default: StandardError)
# define exception named ``c'' with message m. # define exception named ``c'' with message m.
# #
def def_exception(n, m, s = StandardError) def def_exception(n, m, s = StandardError)
E2MM.def_exception(self, n, m, s) E2MM.def_exception(self, n, m, s)
@ -106,10 +106,10 @@ module Exception2MessageMapper
@MessageMap = {} @MessageMap = {}
# E2MM.def_e2message(k, e, m) # E2MM.def_e2message(k, e, m)
# k: class to define exception under. # k: class to define exception under.
# e: exception # e: exception
# m: message_form # m: message_form
# define exception c with message m. # define exception c with message m.
# #
def E2MM.def_e2message(k, c, m) def E2MM.def_e2message(k, c, m)
E2MM.instance_eval{@MessageMap[[k, c]] = m} E2MM.instance_eval{@MessageMap[[k, c]] = m}
@ -117,11 +117,11 @@ module Exception2MessageMapper
end end
# E2MM.def_exception(k, n, m, s) # E2MM.def_exception(k, n, m, s)
# k: class to define exception under. # k: class to define exception under.
# n: exception_name # n: exception_name
# m: message_form # m: message_form
# s: superclass(default: StandardError) # s: superclass(default: StandardError)
# define exception named ``c'' with message m. # define exception named ``c'' with message m.
# #
def E2MM.def_exception(k, n, m, s = StandardError) def E2MM.def_exception(k, n, m, s = StandardError)
n = n.id2name if n.kind_of?(Fixnum) n = n.id2name if n.kind_of?(Fixnum)
@ -131,9 +131,9 @@ module Exception2MessageMapper
end end
# Fail(klass, err, *rest) # Fail(klass, err, *rest)
# klass: class to define exception under. # klass: class to define exception under.
# err: exception # err: exception
# rest: message arguments # rest: message arguments
# #
def E2MM.Raise(klass = E2MM, err = nil, *rest) def E2MM.Raise(klass = E2MM, err = nil, *rest)
if form = e2mm_message(klass, err) if form = e2mm_message(klass, err)
@ -141,7 +141,7 @@ module Exception2MessageMapper
#p $@ #p $@
#p __FILE__ #p __FILE__
b.shift if b[0] =~ /^#{Regexp.quote(__FILE__)}:/ b.shift if b[0] =~ /^#{Regexp.quote(__FILE__)}:/
raise err, sprintf(form, *rest), b raise err, sprintf(form, *rest), b
else else
E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect
end end

View File

@ -254,7 +254,7 @@
# Rails, the web application framework, uses ERB to create views. # Rails, the web application framework, uses ERB to create views.
# #
class ERB class ERB
Revision = '$Date:: $' #' Revision = '$Date:: $' #'
# Returns revision information for the erb.rb module. # Returns revision information for the erb.rb module.
def self.version def self.version
@ -726,9 +726,9 @@ class ERB
# If _trim_mode_ is passed a String containing one or more of the following # If _trim_mode_ is passed a String containing one or more of the following
# modifiers, ERB will adjust its code generation as listed: # modifiers, ERB will adjust its code generation as listed:
# #
# % enables Ruby code processing for lines beginning with % # % enables Ruby code processing for lines beginning with %
# <> omit newline for lines starting with <% and ending in %> # <> omit newline for lines starting with <% and ending in %>
# > omit newline for lines ending in %> # > omit newline for lines ending in %>
# #
# _eoutvar_ can be used to set the name of the variable ERB will build up # _eoutvar_ can be used to set the name of the variable ERB will build up
# its output in. This is useful when you need to run multiple ERB # its output in. This is useful when you need to run multiple ERB
@ -971,7 +971,7 @@ class ERB
# #
module DefMethod module DefMethod
public public
# define _methodname_ as instance method of current module, using ERB object or eRuby file # define _methodname_ as instance method of current module, using ERB object or eRuby file
def def_erb_method(methodname, erb_or_fname) def def_erb_method(methodname, erb_or_fname)
if erb_or_fname.kind_of? String if erb_or_fname.kind_of? String
fname = erb_or_fname fname = erb_or_fname

View File

@ -1,9 +1,9 @@
# #
# forwardable.rb - # forwardable.rb -
# $Release Version: 1.1$ # $Release Version: 1.1$
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ishitsuka.com) # by Keiju ISHITSUKA(keiju@ishitsuka.com)
# original definition by delegator.rb # original definition by delegator.rb
# Revised by Daniel J. Berger with suggestions from Florian Gross. # Revised by Daniel J. Berger with suggestions from Florian Gross.
# #
# Documentation by James Edward Gray II and Gavin Sinclair # Documentation by James Edward Gray II and Gavin Sinclair
@ -84,7 +84,7 @@
# def_delegator :Implementation, :service # def_delegator :Implementation, :service
# #
# class Implementation # class Implementation
# def service... # def service...
# end # end
# end # end
# #
@ -178,12 +178,12 @@ module Forwardable
def def_instance_delegator(accessor, method, ali = method) def def_instance_delegator(accessor, method, ali = method)
line_no = __LINE__; str = %{ line_no = __LINE__; str = %{
def #{ali}(*args, &block) def #{ali}(*args, &block)
begin begin
#{accessor}.__send__(:#{method}, *args, &block) #{accessor}.__send__(:#{method}, *args, &block)
rescue Exception rescue Exception
$@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug $@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug
::Kernel::raise ::Kernel::raise
end end
end end
} }
# If it's not a class or module, it's an instance # If it's not a class or module, it's an instance
@ -248,12 +248,12 @@ module SingleForwardable
def def_single_delegator(accessor, method, ali = method) def def_single_delegator(accessor, method, ali = method)
str = %{ str = %{
def #{ali}(*args, &block) def #{ali}(*args, &block)
begin begin
#{accessor}.__send__(:#{method}, *args, &block) #{accessor}.__send__(:#{method}, *args, &block)
rescue Exception rescue Exception
$@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug $@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug
::Kernel::raise ::Kernel::raise
end end
end end
} }

View File

@ -284,7 +284,7 @@ class GetoptLong
arguments.each do |arg| arguments.each do |arg|
if !arg.is_a?(Array) if !arg.is_a?(Array)
raise ArgumentError, "the option list contains non-Array argument" raise ArgumentError, "the option list contains non-Array argument"
end end
# #

View File

@ -72,17 +72,17 @@ end
# #
# ipaddr1 = IPAddr.new "3ffe:505:2::1" # ipaddr1 = IPAddr.new "3ffe:505:2::1"
# #
# p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff> # p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
# #
# p ipaddr1.to_s #=> "3ffe:505:2::1" # p ipaddr1.to_s #=> "3ffe:505:2::1"
# #
# ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000> # ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>
# #
# p ipaddr2.to_s #=> "3ffe:505:2::" # p ipaddr2.to_s #=> "3ffe:505:2::"
# #
# ipaddr3 = IPAddr.new "192.168.2.0/24" # ipaddr3 = IPAddr.new "192.168.2.0/24"
# #
# p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0> # p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>
class IPAddr class IPAddr
@ -157,8 +157,8 @@ class IPAddr
# net1 = IPAddr.new("192.168.2.0/24") # net1 = IPAddr.new("192.168.2.0/24")
# net2 = IPAddr.new("192.168.2.100") # net2 = IPAddr.new("192.168.2.100")
# net3 = IPAddr.new("192.168.3.0") # net3 = IPAddr.new("192.168.3.0")
# p net1.include?(net2) #=> true # p net1.include?(net2) #=> true
# p net1.include?(net3) #=> false # p net1.include?(net3) #=> false
def include?(other) def include?(other)
other = coerce_other(other) other = coerce_other(other)
if ipv4_mapped? if ipv4_mapped?
@ -473,9 +473,9 @@ class IPAddr
end end
# It seems AI_NUMERICHOST doesn't do the job. # It seems AI_NUMERICHOST doesn't do the job.
#Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil, #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
# Socket::AI_NUMERICHOST) # Socket::AI_NUMERICHOST)
begin begin
IPSocket.getaddress(prefix) # test if address is valid IPSocket.getaddress(prefix) # test if address is valid
rescue rescue
raise ArgumentError, "invalid address" raise ArgumentError, "invalid address"
end end
@ -514,8 +514,8 @@ class IPAddr
def in_addr(addr) def in_addr(addr)
if addr =~ /^\d+\.\d+\.\d+\.\d+$/ if addr =~ /^\d+\.\d+\.\d+\.\d+$/
return addr.split('.').inject(0) { |i, s| return addr.split('.').inject(0) { |i, s|
i << 8 | s.to_i i << 8 | s.to_i
} }
end end
return nil return nil
end end

View File

@ -1,8 +1,8 @@
# #
# irb.rb - irb main module # irb.rb - irb main module
# $Release Version: 0.9.6 $ # $Release Version: 0.9.6 $
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #
@ -72,7 +72,7 @@ module IRB
ensure ensure
irb_at_exit irb_at_exit
end end
# print "\n" # print "\n"
end end
def IRB.irb_at_exit def IRB.irb_at_exit
@ -167,7 +167,7 @@ module IRB
if exc if exc
print exc.class, ": ", exc, "\n" print exc.class, ": ", exc, "\n"
if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ && if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ &&
!(SyntaxError === exc) !(SyntaxError === exc)
irb_bug = true irb_bug = true
else else
irb_bug = false irb_bug = false

View File

@ -263,9 +263,9 @@ class Logger
alias sev_threshold level alias sev_threshold level
alias sev_threshold= level= alias sev_threshold= level=
# Returns +true+ iff the current severity level allows for the printing of # Returns +true+ iff the current severity level allows for the printing of
# +DEBUG+ messages. # +DEBUG+ messages.
def debug?; @level <= DEBUG; end def debug?; @level <= DEBUG; end
# Returns +true+ iff the current severity level allows for the printing of # Returns +true+ iff the current severity level allows for the printing of
# +INFO+ messages. # +INFO+ messages.
@ -312,7 +312,7 @@ class Logger
@logdev = nil @logdev = nil
if logdev if logdev
@logdev = LogDevice.new(logdev, :shift_age => shift_age, @logdev = LogDevice.new(logdev, :shift_age => shift_age,
:shift_size => shift_size) :shift_size => shift_size)
end end
end end
@ -376,7 +376,7 @@ class Logger
end end
@logdev.write( @logdev.write(
format_message(format_severity(severity), Time.now, progname, message)) format_message(format_severity(severity), Time.now, progname, message))
true true
end end
alias log add alias log add
@ -478,7 +478,7 @@ class Logger
@logdev.close if @logdev @logdev.close if @logdev
end end
private private
# Severity label for logging. (max 5 char) # Severity label for logging. (max 5 char)
SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY) SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)
@ -507,7 +507,7 @@ class Logger
msg2str(msg)] msg2str(msg)]
end end
private private
def format_datetime(time) def format_datetime(time)
if @datetime_format.nil? if @datetime_format.nil?
@ -523,7 +523,7 @@ class Logger
msg msg
when ::Exception when ::Exception
"#{ msg.message } (#{ msg.class })\n" << "#{ msg.message } (#{ msg.class })\n" <<
(msg.backtrace || []).join("\n") (msg.backtrace || []).join("\n")
else else
msg.inspect msg.inspect
end end
@ -585,7 +585,7 @@ class Logger
end end
end end
private private
def open_logfile(filename) def open_logfile(filename)
if (FileTest.exist?(filename)) if (FileTest.exist?(filename))
@ -791,7 +791,7 @@ class Logger
@log.add(severity, message, @appname, &block) if @log @log.add(severity, message, @appname, &block) if @log
end end
private private
def run def run
# TODO: should be an NotImplementedError # TODO: should be an NotImplementedError

View File

@ -299,11 +299,11 @@ end
def xsystem command, opts = nil def xsystem command, opts = nil
varpat = /\$\((\w+)\)|\$\{(\w+)\}/ varpat = /\$\((\w+)\)|\$\{(\w+)\}/
if varpat =~ command if varpat =~ command
vars = Hash.new {|h, k| h[k] = ''; ENV[k]} vars = Hash.new {|h, k| h[k] = ''; ENV[k]}
command = command.dup command = command.dup
nil while command.gsub!(varpat) {vars[$1||$2]} nil while command.gsub!(varpat) {vars[$1||$2]}
end end
Logging::open do Logging::open do
puts command.quote puts command.quote
if opts and opts[:werror] if opts and opts[:werror]
@ -410,7 +410,7 @@ def cc_command(opt="")
'arch_hdrdir' => "#$arch_hdrdir", 'arch_hdrdir' => "#$arch_hdrdir",
'top_srcdir' => $top_srcdir.quote) 'top_srcdir' => $top_srcdir.quote)
RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}", RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
conf) conf)
end end
def cpp_command(outfile, opt="") def cpp_command(outfile, opt="")
@ -418,7 +418,7 @@ def cpp_command(outfile, opt="")
'arch_hdrdir' => "#$arch_hdrdir", 'arch_hdrdir' => "#$arch_hdrdir",
'top_srcdir' => $top_srcdir.quote) 'top_srcdir' => $top_srcdir.quote)
RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}", RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
conf) conf)
end end
def libpathflag(libpath=$DEFLIBPATH|$LIBPATH) def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
@ -547,7 +547,7 @@ end
def try_static_assert(expr, headers = nil, opt = "", &b) def try_static_assert(expr, headers = nil, opt = "", &b)
headers = cpp_include(headers) headers = cpp_include(headers)
try_compile(<<SRC, opt, &b) try_compile(<<SRC, opt, &b)
#{headers} #{headers}
/*top*/ /*top*/
int conftest_const[(#{expr}) ? 1 : -1]; int conftest_const[(#{expr}) ? 1 : -1];
SRC SRC
@ -616,15 +616,15 @@ def try_func(func, libs, headers = nil, &b)
decltype = proc {|x| "void ((*#{x})())"} decltype = proc {|x| "void ((*#{x})())"}
end end
try_link(<<"SRC", libs, &b) or try_link(<<"SRC", libs, &b) or
#{headers} #{headers}
/*top*/ /*top*/
#{MAIN_DOES_NOTHING} #{MAIN_DOES_NOTHING}
int t() { #{decltype["volatile p"]}; p = (#{decltype[]})#{func}; return 0; } int t() { #{decltype["volatile p"]}; p = (#{decltype[]})#{func}; return 0; }
SRC SRC
call && try_link(<<"SRC", libs, &b) call && try_link(<<"SRC", libs, &b)
#{headers} #{headers}
/*top*/ /*top*/
#{MAIN_DOES_NOTHING} #{MAIN_DOES_NOTHING}
int t() { #{func}(); return 0; } int t() { #{func}(); return 0; }
SRC SRC
end end
@ -633,9 +633,9 @@ end
def try_var(var, headers = nil, &b) def try_var(var, headers = nil, &b)
headers = cpp_include(headers) headers = cpp_include(headers)
try_compile(<<"SRC", &b) try_compile(<<"SRC", &b)
#{headers} #{headers}
/*top*/ /*top*/
#{MAIN_DOES_NOTHING} #{MAIN_DOES_NOTHING}
int t() { const volatile void *volatile p; p = &(&#{var})[0]; return 0; } int t() { const volatile void *volatile p; p = &(&#{var})[0]; return 0; }
SRC SRC
end end
@ -659,18 +659,18 @@ def egrep_cpp(pat, src, opt = "", &b)
if Regexp === pat if Regexp === pat
puts(" ruby -ne 'print if #{pat.inspect}'") puts(" ruby -ne 'print if #{pat.inspect}'")
f.grep(pat) {|l| f.grep(pat) {|l|
puts "#{f.lineno}: #{l}" puts "#{f.lineno}: #{l}"
return true return true
} }
false false
else else
puts(" egrep '#{pat}'") puts(" egrep '#{pat}'")
begin begin
stdin = $stdin.dup stdin = $stdin.dup
$stdin.reopen(f) $stdin.reopen(f)
system("egrep", pat) system("egrep", pat)
ensure ensure
$stdin.reopen(stdin) $stdin.reopen(stdin)
end end
end end
end end
@ -867,11 +867,11 @@ def find_library(lib, func, *paths, &b)
libs = append_library($libs, lib) libs = append_library($libs, lib)
begin begin
until r = try_func(func, libs, &b) or paths.empty? until r = try_func(func, libs, &b) or paths.empty?
$LIBPATH = libpath | [paths.shift] $LIBPATH = libpath | [paths.shift]
end end
if r if r
$libs = libs $libs = libs
libpath = nil libpath = nil
end end
ensure ensure
$LIBPATH = libpath if libpath $LIBPATH = libpath if libpath
@ -999,9 +999,9 @@ end
def have_struct_member(type, member, headers = nil, &b) def have_struct_member(type, member, headers = nil, &b)
checking_for checking_message("#{type}.#{member}", headers) do checking_for checking_message("#{type}.#{member}", headers) do
if try_compile(<<"SRC", &b) if try_compile(<<"SRC", &b)
#{cpp_include(headers)} #{cpp_include(headers)}
/*top*/ /*top*/
#{MAIN_DOES_NOTHING} #{MAIN_DOES_NOTHING}
int s = (char *)&((#{type}*)0)->#{member} - (char *)0; int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
SRC SRC
$defs.push(format("-DHAVE_%s_%s", type.tr_cpp, member.tr_cpp)) $defs.push(format("-DHAVE_%s_%s", type.tr_cpp, member.tr_cpp))
@ -1019,7 +1019,7 @@ end
# #
def try_type(type, headers = nil, opt = "", &b) def try_type(type, headers = nil, opt = "", &b)
if try_compile(<<"SRC", opt, &b) if try_compile(<<"SRC", opt, &b)
#{cpp_include(headers)} #{cpp_include(headers)}
/*top*/ /*top*/
typedef #{type} conftest_type; typedef #{type} conftest_type;
int conftestval[sizeof(conftest_type)?1:-1]; int conftestval[sizeof(conftest_type)?1:-1];
@ -1077,7 +1077,7 @@ end
def try_const(const, headers = nil, opt = "", &b) def try_const(const, headers = nil, opt = "", &b)
const, type = *const const, type = *const
if try_compile(<<"SRC", opt, &b) if try_compile(<<"SRC", opt, &b)
#{cpp_include(headers)} #{cpp_include(headers)}
/*top*/ /*top*/
typedef #{type || 'int'} conftest_type; typedef #{type || 'int'} conftest_type;
conftest_type conftestval = #{type ? '' : '(int)'}#{const}; conftest_type conftestval = #{type ? '' : '(int)'}#{const};
@ -1217,18 +1217,18 @@ def convertible_int(type, headers = nil, opts = nil, &b)
u = "unsigned " if signed > 0 u = "unsigned " if signed > 0
prelude << "extern rbcv_typedef_ foo();" prelude << "extern rbcv_typedef_ foo();"
compat = UNIVERSAL_INTS.find {|t| compat = UNIVERSAL_INTS.find {|t|
try_compile([prelude, "extern #{u}#{t} foo();"].join("\n"), opts, :werror=>true, &b) try_compile([prelude, "extern #{u}#{t} foo();"].join("\n"), opts, :werror=>true, &b)
} }
if compat if compat
macname ||= type.sub(/_(?=t\z)/, '').tr_cpp macname ||= type.sub(/_(?=t\z)/, '').tr_cpp
conv = (compat == "long long" ? "LL" : compat.upcase) conv = (compat == "long long" ? "LL" : compat.upcase)
compat = "#{u}#{compat}" compat = "#{u}#{compat}"
$defs.push(format("-DTYPEOF_%s=%s", type.tr_cpp, compat.quote)) $defs.push(format("-DTYPEOF_%s=%s", type.tr_cpp, compat.quote))
$defs.push(format("-DPRI_%s_PREFIX=PRI_%s_PREFIX", macname, conv)) $defs.push(format("-DPRI_%s_PREFIX=PRI_%s_PREFIX", macname, conv))
conv = (u ? "U" : "") + conv conv = (u ? "U" : "") + conv
$defs.push(format("-D%s2NUM=%s2NUM", macname, conv)) $defs.push(format("-D%s2NUM=%s2NUM", macname, conv))
$defs.push(format("-DNUM2%s=NUM2%s", macname, conv)) $defs.push(format("-DNUM2%s=NUM2%s", macname, conv))
compat compat
end end
end end
end end
@ -1239,10 +1239,10 @@ end
# pointer. # pointer.
def scalar_ptr_type?(type, member = nil, headers = nil, &b) def scalar_ptr_type?(type, member = nil, headers = nil, &b)
try_compile(<<"SRC", &b) # pointer try_compile(<<"SRC", &b) # pointer
#{cpp_include(headers)} #{cpp_include(headers)}
/*top*/ /*top*/
volatile #{type} conftestval; volatile #{type} conftestval;
#{MAIN_DOES_NOTHING} #{MAIN_DOES_NOTHING}
int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));} int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
SRC SRC
end end
@ -1251,10 +1251,10 @@ end
# pointer. # pointer.
def scalar_type?(type, member = nil, headers = nil, &b) def scalar_type?(type, member = nil, headers = nil, &b)
try_compile(<<"SRC", &b) # pointer try_compile(<<"SRC", &b) # pointer
#{cpp_include(headers)} #{cpp_include(headers)}
/*top*/ /*top*/
volatile #{type} conftestval; volatile #{type} conftestval;
#{MAIN_DOES_NOTHING} #{MAIN_DOES_NOTHING}
int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));} int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
SRC SRC
end end
@ -1266,7 +1266,7 @@ def have_typeof?
$typeof = %w[__typeof__ typeof].find do |t| $typeof = %w[__typeof__ typeof].find do |t|
try_compile(<<SRC) try_compile(<<SRC)
int rbcv_foo; int rbcv_foo;
#{t}(rbcv_foo) rbcv_bar; #{t}(rbcv_foo) rbcv_bar;
SRC SRC
end end
end end
@ -1644,7 +1644,7 @@ ECHO1 = $(V:1=@:)
ECHO = $(ECHO1:0=@echo) ECHO = $(ECHO1:0=@echo)
#### Start of system configuration section. #### #### Start of system configuration section. ####
#{"top_srcdir = " + $top_srcdir.sub(%r"\A#{Regexp.quote($topdir)}/", "$(topdir)/") if $extmk} #{"top_srcdir = " + $top_srcdir.sub(%r"\A#{Regexp.quote($topdir)}/", "$(topdir)/") if $extmk}
srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {mkintpath(CONFIG[$1||$2])}.quote} srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {mkintpath(CONFIG[$1||$2])}.quote}
topdir = #{mkintpath($extmk ? CONFIG["topdir"] : $topdir).quote} topdir = #{mkintpath($extmk ? CONFIG["topdir"] : $topdir).quote}
hdrdir = #{mkintpath(CONFIG["hdrdir"]).quote} hdrdir = #{mkintpath(CONFIG["hdrdir"]).quote}
@ -1730,7 +1730,7 @@ preload = #{defined?($preload) && $preload ? $preload.join(' ') : ''}
x.gsub!(/^(MAKEDIRS|INSTALL_(?:PROG|DATA))+\s*=.*\n/) do x.gsub!(/^(MAKEDIRS|INSTALL_(?:PROG|DATA))+\s*=.*\n/) do
"!ifndef " + $1 + "\n" + "!ifndef " + $1 + "\n" +
$& + $& +
"!endif\n" "!endif\n"
end end
end end
end end
@ -2006,7 +2006,7 @@ static: $(STATIC_LIB)#{$extout ? " install-rb" : ""}
mfile.print "#{dest}: #{f}\n\t@-$(MAKEDIRS) $(@D#{sep})\n" mfile.print "#{dest}: #{f}\n\t@-$(MAKEDIRS) $(@D#{sep})\n"
mfile.print "\t$(INSTALL_PROG) #{fseprepl[f]} $(@D#{sep})\n" mfile.print "\t$(INSTALL_PROG) #{fseprepl[f]} $(@D#{sep})\n"
if defined?($installed_list) if defined?($installed_list)
mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n" mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n"
end end
end end
else else
@ -2020,17 +2020,17 @@ static: $(STATIC_LIB)#{$extout ? " install-rb" : ""}
files = install_files(mfile, i, nil, srcprefix) or next files = install_files(mfile, i, nil, srcprefix) or next
for dir, *files in files for dir, *files in files
unless dirs.include?(dir) unless dirs.include?(dir)
dirs << dir dirs << dir
mfile.print "pre-install-rb#{sfx}: #{dir}\n" mfile.print "pre-install-rb#{sfx}: #{dir}\n"
end end
for f in files for f in files
dest = "#{dir}/#{File.basename(f)}" dest = "#{dir}/#{File.basename(f)}"
mfile.print("install-rb#{sfx}: #{dest} #{dir}\n") mfile.print("install-rb#{sfx}: #{dest} #{dir}\n")
mfile.print("#{dest}: #{f}\n") mfile.print("#{dest}: #{f}\n")
mfile.print("\t$(Q) $(#{$extout ? 'COPY' : 'INSTALL_DATA'}) #{f} $(@D#{sep})\n") mfile.print("\t$(Q) $(#{$extout ? 'COPY' : 'INSTALL_DATA'}) #{f} $(@D#{sep})\n")
if defined?($installed_list) and !$extout if defined?($installed_list) and !$extout
mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n") mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n")
end end
if $extout if $extout
mfile.print("clean-rb#{sfx}::\n") mfile.print("clean-rb#{sfx}::\n")
mfile.print("\t@-$(RM) #{fseprepl[dest]}\n") mfile.print("\t@-$(RM) #{fseprepl[dest]}\n")

View File

@ -1,26 +1,26 @@
# #
# mutex_m.rb - # mutex_m.rb -
# $Release Version: 3.0$ # $Release Version: 3.0$
# $Revision: 1.7 $ # $Revision: 1.7 $
# Original from mutex.rb # Original from mutex.rb
# by Keiju ISHITSUKA(keiju@ishitsuka.com) # by Keiju ISHITSUKA(keiju@ishitsuka.com)
# modified by matz # modified by matz
# patched by akira yamada # patched by akira yamada
# #
# -- # --
# Usage: # Usage:
# require "mutex_m.rb" # require "mutex_m.rb"
# obj = Object.new # obj = Object.new
# obj.extend Mutex_m # obj.extend Mutex_m
# ... # ...
# extended object can be handled like Mutex # extended object can be handled like Mutex
# or # or
# class Foo # class Foo
# include Mutex_m # include Mutex_m
# ... # ...
# end # end
# obj = Foo.new # obj = Foo.new
# this obj can be handled like Mutex # this obj can be handled like Mutex
# #
require 'thread' require 'thread'
@ -52,7 +52,7 @@ module Mutex_m
defined? unlock and defined? unlock and
defined? try_lock and defined? try_lock and
defined? synchronize) defined? synchronize)
Mutex_m.define_aliases(singleton_class) Mutex_m.define_aliases(singleton_class)
end end
mu_initialize mu_initialize
end end

View File

@ -272,7 +272,7 @@ module Net
line = getline line = getline
buff = line buff = line
if line[3] == ?- if line[3] == ?-
code = line[0, 3] code = line[0, 3]
begin begin
line = getline line = getline
buff << "\n" << line buff << "\n" << line
@ -781,15 +781,15 @@ module Net
MDTM_REGEXP = /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ # :nodoc: MDTM_REGEXP = /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ # :nodoc:
# #
# Returns the last modification time of the (remote) file. If +local+ is # Returns the last modification time of the (remote) file. If +local+ is
# +true+, it is returned as a local time, otherwise it's a UTC time. # +true+, it is returned as a local time, otherwise it's a UTC time.
# #
def mtime(filename, local = false) def mtime(filename, local = false)
str = mdtm(filename) str = mdtm(filename)
ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i} ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i}
return local ? Time.local(*ary) : Time.gm(*ary) return local ? Time.local(*ary) : Time.gm(*ary)
end end
# #
# Creates a remote directory. # Creates a remote directory.

View File

@ -1091,7 +1091,7 @@ module Net
when UntaggedResponse when UntaggedResponse
record_response(resp.name, resp.data) record_response(resp.name, resp.data)
if resp.data.instance_of?(ResponseText) && if resp.data.instance_of?(ResponseText) &&
(code = resp.data.code) (code = resp.data.code)
record_response(code.name, code.data) record_response(code.name, code.data)
end end
if resp.name == "BYE" && @logout_command_tag.nil? if resp.name == "BYE" && @logout_command_tag.nil?
@ -1550,7 +1550,7 @@ module Net
def ensure_nz_number(num) def ensure_nz_number(num)
if num < -1 || num == 0 || num >= 4294967296 if num < -1 || num == 0 || num >= 4294967296
msg = "nz_number must be non-zero unsigned 32-bit integer: " + msg = "nz_number must be non-zero unsigned 32-bit integer: " +
num.inspect num.inspect
raise DataFormatError, msg raise DataFormatError, msg
end end
end end
@ -2965,62 +2965,62 @@ module Net
return Address.new(name, route, mailbox, host) return Address.new(name, route, mailbox, host)
end end
# def flag_list # def flag_list
# result = [] # result = []
# match(T_LPAR) # match(T_LPAR)
# while true # while true
# token = lookahead # token = lookahead
# case token.symbol # case token.symbol
# when T_RPAR # when T_RPAR
# shift_token # shift_token
# break # break
# when T_SPACE # when T_SPACE
# shift_token # shift_token
# end # end
# result.push(flag) # result.push(flag)
# end # end
# return result # return result
# end # end
# def flag # def flag
# token = lookahead # token = lookahead
# if token.symbol == T_BSLASH # if token.symbol == T_BSLASH
# shift_token # shift_token
# token = lookahead # token = lookahead
# if token.symbol == T_STAR # if token.symbol == T_STAR
# shift_token # shift_token
# return token.value.intern # return token.value.intern
# else # else
# return atom.intern # return atom.intern
# end # end
# else # else
# return atom # return atom
# end # end
# end # end
FLAG_REGEXP = /\ FLAG_REGEXP = /\
(?# FLAG )\\([^\x80-\xff(){ \x00-\x1f\x7f%"\\]+)|\ (?# FLAG )\\([^\x80-\xff(){ \x00-\x1f\x7f%"\\]+)|\
(?# ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\]+)/n (?# ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\]+)/n
def flag_list def flag_list
if @str.index(/\(([^)]*)\)/ni, @pos) if @str.index(/\(([^)]*)\)/ni, @pos)
@pos = $~.end(0) @pos = $~.end(0)
return $1.scan(FLAG_REGEXP).collect { |flag, atom| return $1.scan(FLAG_REGEXP).collect { |flag, atom|
if atom if atom
atom atom
else else
symbol = flag.capitalize.untaint.intern symbol = flag.capitalize.untaint.intern
@flag_symbols[symbol] = true @flag_symbols[symbol] = true
if @flag_symbols.length > IMAP.max_flag_count if @flag_symbols.length > IMAP.max_flag_count
raise FlagCountError, "number of flag symbols exceeded" raise FlagCountError, "number of flag symbols exceeded"
end
symbol
end
}
else
parse_error("invalid flag list")
end end
symbol
end end
}
else
parse_error("invalid flag list")
end
end
def nstring def nstring
token = lookahead token = lookahead
@ -3389,12 +3389,12 @@ module Net
a2 = "AUTHENTICATE:" + response[:'digest-uri'] a2 = "AUTHENTICATE:" + response[:'digest-uri']
a2 << ":00000000000000000000000000000000" if response[:qop] and response[:qop] =~ /^auth-(?:conf|int)$/ a2 << ":00000000000000000000000000000000" if response[:qop] and response[:qop] =~ /^auth-(?:conf|int)$/
response[:response] = Digest::MD5.hexdigest( response[:response] = Digest::MD5.hexdigest(
[ [
Digest::MD5.hexdigest(a1), Digest::MD5.hexdigest(a1),
response.values_at(:nonce, :nc, :cnonce, :qop), response.values_at(:nonce, :nc, :cnonce, :qop),
Digest::MD5.hexdigest(a2) Digest::MD5.hexdigest(a2)
].join(':') ].join(':')
) )
return response.keys.map {|key| qdval(key.to_s, response[key]) }.join(',') return response.keys.map {|key| qdval(key.to_s, response[key]) }.join(',')

View File

@ -433,18 +433,18 @@ module Net
# combine CR+NULL into CR # combine CR+NULL into CR
string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"] string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"]
# combine EOL into "\n" # combine EOL into "\n"
string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"] string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"]
# remove NULL # remove NULL
string = string.gsub(/#{NULL}/no, '') unless @options["Binmode"] string = string.gsub(/#{NULL}/no, '') unless @options["Binmode"]
string.gsub(/#{IAC}( string.gsub(/#{IAC}(
[#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]| [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
[#{DO}#{DONT}#{WILL}#{WONT}] [#{DO}#{DONT}#{WILL}#{WONT}]
[#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]| [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
#{SB}[^#{IAC}]*#{IAC}#{SE} #{SB}[^#{IAC}]*#{IAC}#{SE}
)/xno) do )/xno) do
if IAC == $1 # handle escaped IAC characters if IAC == $1 # handle escaped IAC characters
IAC IAC
elsif AYT == $1 # respond to "IAC AYT" (are you there) elsif AYT == $1 # respond to "IAC AYT" (are you there)
@ -464,301 +464,301 @@ module Net
elsif WILL[0] == $1[0] # respond to "IAC WILL x" elsif WILL[0] == $1[0] # respond to "IAC WILL x"
if OPT_BINARY[0] == $1[1] if OPT_BINARY[0] == $1[1]
self.write(IAC + DO + OPT_BINARY) self.write(IAC + DO + OPT_BINARY)
elsif OPT_ECHO[0] == $1[1] elsif OPT_ECHO[0] == $1[1]
self.write(IAC + DO + OPT_ECHO) self.write(IAC + DO + OPT_ECHO)
elsif OPT_SGA[0] == $1[1] elsif OPT_SGA[0] == $1[1]
@telnet_option["SGA"] = true @telnet_option["SGA"] = true
self.write(IAC + DO + OPT_SGA) self.write(IAC + DO + OPT_SGA)
else else
self.write(IAC + DONT + $1[1..1]) self.write(IAC + DONT + $1[1..1])
end end
'' ''
elsif WONT[0] == $1[0] # respond to "IAC WON'T x" elsif WONT[0] == $1[0] # respond to "IAC WON'T x"
if OPT_ECHO[0] == $1[1] if OPT_ECHO[0] == $1[1]
self.write(IAC + DONT + OPT_ECHO) self.write(IAC + DONT + OPT_ECHO)
elsif OPT_SGA[0] == $1[1] elsif OPT_SGA[0] == $1[1]
@telnet_option["SGA"] = false @telnet_option["SGA"] = false
self.write(IAC + DONT + OPT_SGA) self.write(IAC + DONT + OPT_SGA)
else else
self.write(IAC + DONT + $1[1..1]) self.write(IAC + DONT + $1[1..1])
end end
'' ''
else else
'' ''
end end
end end
end # preprocess end # preprocess
# Read data from the host until a certain sequence is matched. # Read data from the host until a certain sequence is matched.
# #
# If a block is given, the received data will be yielded as it # If a block is given, the received data will be yielded as it
# is read in (not necessarily all in one go), or nil if EOF # is read in (not necessarily all in one go), or nil if EOF
# occurs before any data is received. Whether a block is given # occurs before any data is received. Whether a block is given
# or not, all data read will be returned in a single string, or again # or not, all data read will be returned in a single string, or again
# nil if EOF occurs before any data is received. Note that # nil if EOF occurs before any data is received. Note that
# received data includes the matched sequence we were looking for. # received data includes the matched sequence we were looking for.
# #
# +options+ can be either a regular expression or a hash of options. # +options+ can be either a regular expression or a hash of options.
# If a regular expression, this specifies the data to wait for. # If a regular expression, this specifies the data to wait for.
# If a hash, this can specify the following options: # If a hash, this can specify the following options:
# #
# Match:: a regular expression, specifying the data to wait for. # Match:: a regular expression, specifying the data to wait for.
# Prompt:: as for Match; used only if Match is not specified. # Prompt:: as for Match; used only if Match is not specified.
# String:: as for Match, except a string that will be converted # String:: as for Match, except a string that will be converted
# into a regular expression. Used only if Match and # into a regular expression. Used only if Match and
# Prompt are not specified. # Prompt are not specified.
# Timeout:: the number of seconds to wait for data from the host # Timeout:: the number of seconds to wait for data from the host
# before raising a TimeoutError. If set to false, # before raising a TimeoutError. If set to false,
# no timeout will occur. If not specified, the # no timeout will occur. If not specified, the
# Timeout option value specified when this instance # Timeout option value specified when this instance
# was created will be used, or, failing that, the # was created will be used, or, failing that, the
# default value of 10 seconds. # default value of 10 seconds.
# Waittime:: the number of seconds to wait after matching against # Waittime:: the number of seconds to wait after matching against
# the input data to see if more data arrives. If more # the input data to see if more data arrives. If more
# data arrives within this time, we will judge ourselves # data arrives within this time, we will judge ourselves
# not to have matched successfully, and will continue # not to have matched successfully, and will continue
# trying to match. If not specified, the Waittime option # trying to match. If not specified, the Waittime option
# value specified when this instance was created will be # value specified when this instance was created will be
# used, or, failing that, the default value of 0 seconds, # used, or, failing that, the default value of 0 seconds,
# which means not to wait for more input. # which means not to wait for more input.
# FailEOF:: if true, when the remote end closes the connection then an # FailEOF:: if true, when the remote end closes the connection then an
# EOFError will be raised. Otherwise, defaults to the old # EOFError will be raised. Otherwise, defaults to the old
# behaviour that the function will return whatever data # behaviour that the function will return whatever data
# has been received already, or nil if nothing was received. # has been received already, or nil if nothing was received.
# #
def waitfor(options) # :yield: recvdata def waitfor(options) # :yield: recvdata
time_out = @options["Timeout"] time_out = @options["Timeout"]
waittime = @options["Waittime"] waittime = @options["Waittime"]
fail_eof = @options["FailEOF"] fail_eof = @options["FailEOF"]
if options.kind_of?(Hash) if options.kind_of?(Hash)
prompt = if options.has_key?("Match") prompt = if options.has_key?("Match")
options["Match"] options["Match"]
elsif options.has_key?("Prompt") elsif options.has_key?("Prompt")
options["Prompt"] options["Prompt"]
elsif options.has_key?("String") elsif options.has_key?("String")
Regexp.new( Regexp.quote(options["String"]) ) Regexp.new( Regexp.quote(options["String"]) )
end end
time_out = options["Timeout"] if options.has_key?("Timeout") time_out = options["Timeout"] if options.has_key?("Timeout")
waittime = options["Waittime"] if options.has_key?("Waittime") waittime = options["Waittime"] if options.has_key?("Waittime")
fail_eof = options["FailEOF"] if options.has_key?("FailEOF") fail_eof = options["FailEOF"] if options.has_key?("FailEOF")
else
prompt = options
end
if time_out == false
time_out = nil
end
line = ''
buf = ''
rest = ''
until(prompt === line and not IO::select([@sock], nil, nil, waittime))
unless IO::select([@sock], nil, nil, time_out)
raise TimeoutError, "timed out while waiting for more data"
end
begin
c = @sock.readpartial(1024 * 1024)
@dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
if @options["Telnetmode"]
c = rest + c
if Integer(c.rindex(/#{IAC}#{SE}/no) || 0) <
Integer(c.rindex(/#{IAC}#{SB}/no) || 0)
buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)])
rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1]
elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no) ||
c.rindex(/\r\z/no)
buf = preprocess(c[0 ... pt])
rest = c[pt .. -1]
else else
prompt = options buf = preprocess(c)
rest = ''
end end
else
if time_out == false # Not Telnetmode.
time_out = nil #
end # We cannot use preprocess() on this data, because that
# method makes some Telnetmode-specific assumptions.
line = '' buf = rest + c
buf = '' rest = ''
rest = '' unless @options["Binmode"]
until(prompt === line and not IO::select([@sock], nil, nil, waittime)) if pt = buf.rindex(/\r\z/no)
unless IO::select([@sock], nil, nil, time_out) buf = buf[0 ... pt]
raise TimeoutError, "timed out while waiting for more data" rest = buf[pt .. -1]
end end
begin buf.gsub!(/#{EOL}/no, "\n")
c = @sock.readpartial(1024 * 1024) end
@dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
if @options["Telnetmode"]
c = rest + c
if Integer(c.rindex(/#{IAC}#{SE}/no) || 0) <
Integer(c.rindex(/#{IAC}#{SB}/no) || 0)
buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)])
rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1]
elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no) ||
c.rindex(/\r\z/no)
buf = preprocess(c[0 ... pt])
rest = c[pt .. -1]
else
buf = preprocess(c)
rest = ''
end
else
# Not Telnetmode.
#
# We cannot use preprocess() on this data, because that
# method makes some Telnetmode-specific assumptions.
buf = rest + c
rest = ''
unless @options["Binmode"]
if pt = buf.rindex(/\r\z/no)
buf = buf[0 ... pt]
rest = buf[pt .. -1]
end
buf.gsub!(/#{EOL}/no, "\n")
end
end
@log.print(buf) if @options.has_key?("Output_log")
line += buf
yield buf if block_given?
rescue EOFError # End of file reached
raise if fail_eof
if line == ''
line = nil
yield nil if block_given?
end
break
end
end
line
end end
@log.print(buf) if @options.has_key?("Output_log")
# Write +string+ to the host. line += buf
# yield buf if block_given?
# Does not perform any conversions on +string+. Will log +string+ to the rescue EOFError # End of file reached
# dumplog, if the Dump_log option is set. raise if fail_eof
def write(string) if line == ''
length = string.length line = nil
while 0 < length yield nil if block_given?
IO::select(nil, [@sock])
@dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log")
length -= @sock.syswrite(string[-length..-1])
end
end end
break
end
end
line
end
# Sends a string to the host. # Write +string+ to the host.
# #
# This does _not_ automatically append a newline to the string. Embedded # Does not perform any conversions on +string+. Will log +string+ to the
# newlines may be converted and telnet command sequences escaped # dumplog, if the Dump_log option is set.
# depending upon the values of telnetmode, binmode, and telnet options def write(string)
# set by the host. length = string.length
def print(string) while 0 < length
string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"] IO::select(nil, [@sock])
@dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log")
length -= @sock.syswrite(string[-length..-1])
end
end
if @options["Binmode"] # Sends a string to the host.
self.write(string) #
else # This does _not_ automatically append a newline to the string. Embedded
if @telnet_option["BINARY"] and @telnet_option["SGA"] # newlines may be converted and telnet command sequences escaped
# IAC WILL SGA IAC DO BIN send EOL --> CR # depending upon the values of telnetmode, binmode, and telnet options
self.write(string.gsub(/\n/n, CR)) # set by the host.
elsif @telnet_option["SGA"] def print(string)
# IAC WILL SGA send EOL --> CR+NULL string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]
self.write(string.gsub(/\n/n, CR + NULL))
else
# NONE send EOL --> CR+LF
self.write(string.gsub(/\n/n, EOL))
end
end
end
# Sends a string to the host. if @options["Binmode"]
# self.write(string)
# Same as #print(), but appends a newline to the string. else
def puts(string) if @telnet_option["BINARY"] and @telnet_option["SGA"]
self.print(string + "\n") # IAC WILL SGA IAC DO BIN send EOL --> CR
end self.write(string.gsub(/\n/n, CR))
elsif @telnet_option["SGA"]
# IAC WILL SGA send EOL --> CR+NULL
self.write(string.gsub(/\n/n, CR + NULL))
else
# NONE send EOL --> CR+LF
self.write(string.gsub(/\n/n, EOL))
end
end
end
# Send a command to the host. # Sends a string to the host.
# #
# More exactly, sends a string to the host, and reads in all received # Same as #print(), but appends a newline to the string.
# data until is sees the prompt or other matched sequence. def puts(string)
# self.print(string + "\n")
# If a block is given, the received data will be yielded to it as end
# it is read in. Whether a block is given or not, the received data
# will be return as a string. Note that the received data includes
# the prompt and in most cases the host's echo of our command.
#
# +options+ is either a String, specified the string or command to
# send to the host; or it is a hash of options. If a hash, the
# following options can be specified:
#
# String:: the command or other string to send to the host.
# Match:: a regular expression, the sequence to look for in
# the received data before returning. If not specified,
# the Prompt option value specified when this instance
# was created will be used, or, failing that, the default
# prompt of /[$%#>] \z/n.
# Timeout:: the seconds to wait for data from the host before raising
# a Timeout error. If not specified, the Timeout option
# value specified when this instance was created will be
# used, or, failing that, the default value of 10 seconds.
#
# The command or other string will have the newline sequence appended
# to it.
def cmd(options) # :yield: recvdata
match = @options["Prompt"]
time_out = @options["Timeout"]
fail_eof = @options["FailEOF"]
if options.kind_of?(Hash) # Send a command to the host.
string = options["String"] #
match = options["Match"] if options.has_key?("Match") # More exactly, sends a string to the host, and reads in all received
time_out = options["Timeout"] if options.has_key?("Timeout") # data until is sees the prompt or other matched sequence.
fail_eof = options["FailEOF"] if options.has_key?("FailEOF") #
else # If a block is given, the received data will be yielded to it as
string = options # it is read in. Whether a block is given or not, the received data
end # will be return as a string. Note that the received data includes
# the prompt and in most cases the host's echo of our command.
#
# +options+ is either a String, specified the string or command to
# send to the host; or it is a hash of options. If a hash, the
# following options can be specified:
#
# String:: the command or other string to send to the host.
# Match:: a regular expression, the sequence to look for in
# the received data before returning. If not specified,
# the Prompt option value specified when this instance
# was created will be used, or, failing that, the default
# prompt of /[$%#>] \z/n.
# Timeout:: the seconds to wait for data from the host before raising
# a Timeout error. If not specified, the Timeout option
# value specified when this instance was created will be
# used, or, failing that, the default value of 10 seconds.
#
# The command or other string will have the newline sequence appended
# to it.
def cmd(options) # :yield: recvdata
match = @options["Prompt"]
time_out = @options["Timeout"]
fail_eof = @options["FailEOF"]
self.puts(string) if options.kind_of?(Hash)
if block_given? string = options["String"]
waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}){|c| yield c } match = options["Match"] if options.has_key?("Match")
else time_out = options["Timeout"] if options.has_key?("Timeout")
waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}) fail_eof = options["FailEOF"] if options.has_key?("FailEOF")
end else
end string = options
end
# Login to the host with a given username and password. self.puts(string)
# if block_given?
# The username and password can either be provided as two string waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}){|c| yield c }
# arguments in that order, or as a hash with keys "Name" and else
# "Password". waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof})
# end
# This method looks for the strings "login" and "Password" from the end
# host to determine when to send the username and password. If the
# login sequence does not follow this pattern (for instance, you
# are connecting to a service other than telnet), you will need
# to handle login yourself.
#
# The password can be omitted, either by only
# provided one String argument, which will be used as the username,
# or by providing a has that has no "Password" key. In this case,
# the method will not look for the "Password:" prompt; if it is
# sent, it will have to be dealt with by later calls.
#
# The method returns all data received during the login process from
# the host, including the echoed username but not the password (which
# the host should not echo). If a block is passed in, this received
# data is also yielded to the block as it is received.
def login(options, password = nil) # :yield: recvdata
login_prompt = /[Ll]ogin[: ]*\z/n
password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n
if options.kind_of?(Hash)
username = options["Name"]
password = options["Password"]
login_prompt = options["LoginPrompt"] if options["LoginPrompt"]
password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"]
else
username = options
end
if block_given? # Login to the host with a given username and password.
line = waitfor(login_prompt){|c| yield c } #
if password # The username and password can either be provided as two string
line += cmd({"String" => username, # arguments in that order, or as a hash with keys "Name" and
"Match" => password_prompt}){|c| yield c } # "Password".
line += cmd(password){|c| yield c } #
else # This method looks for the strings "login" and "Password" from the
line += cmd(username){|c| yield c } # host to determine when to send the username and password. If the
end # login sequence does not follow this pattern (for instance, you
else # are connecting to a service other than telnet), you will need
line = waitfor(login_prompt) # to handle login yourself.
if password #
line += cmd({"String" => username, # The password can be omitted, either by only
"Match" => password_prompt}) # provided one String argument, which will be used as the username,
line += cmd(password) # or by providing a has that has no "Password" key. In this case,
else # the method will not look for the "Password:" prompt; if it is
line += cmd(username) # sent, it will have to be dealt with by later calls.
end #
end # The method returns all data received during the login process from
line # the host, including the echoed username but not the password (which
end # the host should not echo). If a block is passed in, this received
# data is also yielded to the block as it is received.
def login(options, password = nil) # :yield: recvdata
login_prompt = /[Ll]ogin[: ]*\z/n
password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n
if options.kind_of?(Hash)
username = options["Name"]
password = options["Password"]
login_prompt = options["LoginPrompt"] if options["LoginPrompt"]
password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"]
else
username = options
end
# Closes the connection if block_given?
def close line = waitfor(login_prompt){|c| yield c }
@sock.close if password
end line += cmd({"String" => username,
"Match" => password_prompt}){|c| yield c }
line += cmd(password){|c| yield c }
else
line += cmd(username){|c| yield c }
end
else
line = waitfor(login_prompt)
if password
line += cmd({"String" => username,
"Match" => password_prompt})
line += cmd(password)
else
line += cmd(username)
end
end
line
end
end # class Telnet # Closes the connection
end # module Net def close
@sock.close
end
end # class Telnet
end # module Net

View File

@ -99,397 +99,397 @@ class Prime
def method_added(method) # :nodoc: def method_added(method) # :nodoc:
(class<< self;self;end).def_delegator :instance, method (class<< self;self;end).def_delegator :instance, method
end
end
# Iterates the given block over all prime numbers.
#
# == Parameters
# +ubound+::
# Optional. An arbitrary positive number.
# The upper bound of enumeration. The method enumerates
# prime numbers infinitely if +ubound+ is nil.
# +generator+::
# Optional. An implementation of pseudo-prime generator.
#
# == Return value
# An evaluated value of the given block at the last time.
# Or an enumerator which is compatible to an +Enumerator+
# if no block given.
#
# == Description
# Calls +block+ once for each prime number, passing the prime as
# a parameter.
#
# +ubound+::
# Upper bound of prime numbers. The iterator stops after
# yields all prime numbers p <= +ubound+.
#
# == Note
# +Prime+.+new+ returns a object extended by +Prime+::+OldCompatibility+
# in order to compatibility to Ruby 1.8, and +Prime+#each is overwritten
# by +Prime+::+OldCompatibility+#+each+.
#
# +Prime+.+new+ is now obsolete. Use +Prime+.+instance+.+each+ or simply
# +Prime+.+each+.
def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
generator.upper_bound = ubound
generator.each(&block)
end
# Returns true if +value+ is prime, false for a composite.
#
# == Parameters
# +value+:: an arbitrary integer to be checked.
# +generator+:: optional. A pseudo-prime generator.
def prime?(value, generator = Prime::Generator23.new)
value = -value if value < 0
return false if value < 2
for num in generator
q,r = value.divmod num
return true if q < num
return false if r == 0
end
end
# Re-composes a prime factorization and returns the product.
#
# == Parameters
# +pd+:: Array of pairs of integers. The each internal
# pair consists of a prime number -- a prime factor --
# and a natural number -- an exponent.
#
# == Example
# For [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]], it returns
# p_1**e_1 * p_2**e_2 * .... * p_n**e_n.
#
# Prime.int_from_prime_division([[2,2], [3,1]]) #=> 12
def int_from_prime_division(pd)
pd.inject(1){|value, (prime, index)|
value *= prime**index
}
end
# Returns the factorization of +value+.
#
# == Parameters
# +value+:: An arbitrary integer.
# +generator+:: Optional. A pseudo-prime generator.
# +generator+.succ must return the next
# pseudo-prime number in the ascendent
# order. It must generate all prime numbers,
# but may generate non prime numbers.
#
# === Exceptions
# +ZeroDivisionError+:: when +value+ is zero.
#
# == Example
# For an arbitrary integer
# n = p_1**e_1 * p_2**e_2 * .... * p_n**e_n,
# prime_division(n) returns
# [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]].
#
# Prime.prime_division(12) #=> [[2,2], [3,1]]
#
def prime_division(value, generator= Prime::Generator23.new)
raise ZeroDivisionError if value == 0
if value < 0
value = -value
pv = [[-1, 1]]
else
pv = []
end
for prime in generator
count = 0
while (value1, mod = value.divmod(prime)
mod) == 0
value = value1
count += 1
end end
if count != 0 end
pv.push [prime, count]
# Iterates the given block over all prime numbers.
#
# == Parameters
# +ubound+::
# Optional. An arbitrary positive number.
# The upper bound of enumeration. The method enumerates
# prime numbers infinitely if +ubound+ is nil.
# +generator+::
# Optional. An implementation of pseudo-prime generator.
#
# == Return value
# An evaluated value of the given block at the last time.
# Or an enumerator which is compatible to an +Enumerator+
# if no block given.
#
# == Description
# Calls +block+ once for each prime number, passing the prime as
# a parameter.
#
# +ubound+::
# Upper bound of prime numbers. The iterator stops after
# yields all prime numbers p <= +ubound+.
#
# == Note
# +Prime+.+new+ returns a object extended by +Prime+::+OldCompatibility+
# in order to compatibility to Ruby 1.8, and +Prime+#each is overwritten
# by +Prime+::+OldCompatibility+#+each+.
#
# +Prime+.+new+ is now obsolete. Use +Prime+.+instance+.+each+ or simply
# +Prime+.+each+.
def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
generator.upper_bound = ubound
generator.each(&block)
end
# Returns true if +value+ is prime, false for a composite.
#
# == Parameters
# +value+:: an arbitrary integer to be checked.
# +generator+:: optional. A pseudo-prime generator.
def prime?(value, generator = Prime::Generator23.new)
value = -value if value < 0
return false if value < 2
for num in generator
q,r = value.divmod num
return true if q < num
return false if r == 0
end end
break if value1 <= prime
end
if value > 1
pv.push [value, 1]
end
return pv
end
# An abstract class for enumerating pseudo-prime numbers.
#
# Concrete subclasses should override succ, next, rewind.
class PseudoPrimeGenerator
include Enumerable
def initialize(ubound = nil)
@ubound = ubound
end end
def upper_bound=(ubound) # Re-composes a prime factorization and returns the product.
@ubound = ubound
end
def upper_bound
@ubound
end
# returns the next pseudo-prime number, and move the internal
# position forward.
# #
# +PseudoPrimeGenerator+#succ raises +NotImplementedError+. # == Parameters
def succ # +pd+:: Array of pairs of integers. The each internal
raise NotImplementedError, "need to define `succ'" # pair consists of a prime number -- a prime factor --
end # and a natural number -- an exponent.
# alias of +succ+.
def next
raise NotImplementedError, "need to define `next'"
end
# Rewinds the internal position for enumeration.
# #
# See +Enumerator+#rewind. # == Example
def rewind # For [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]], it returns
raise NotImplementedError, "need to define `rewind'" # p_1**e_1 * p_2**e_2 * .... * p_n**e_n.
#
# Prime.int_from_prime_division([[2,2], [3,1]]) #=> 12
def int_from_prime_division(pd)
pd.inject(1){|value, (prime, index)|
value *= prime**index
}
end end
# Iterates the given block for each prime numbers. # Returns the factorization of +value+.
def each(&block) #
return self.dup unless block # == Parameters
if @ubound # +value+:: An arbitrary integer.
last_value = nil # +generator+:: Optional. A pseudo-prime generator.
loop do # +generator+.succ must return the next
prime = succ # pseudo-prime number in the ascendent
break last_value if prime > @ubound # order. It must generate all prime numbers,
last_value = block.call(prime) # but may generate non prime numbers.
end #
# === Exceptions
# +ZeroDivisionError+:: when +value+ is zero.
#
# == Example
# For an arbitrary integer
# n = p_1**e_1 * p_2**e_2 * .... * p_n**e_n,
# prime_division(n) returns
# [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]].
#
# Prime.prime_division(12) #=> [[2,2], [3,1]]
#
def prime_division(value, generator= Prime::Generator23.new)
raise ZeroDivisionError if value == 0
if value < 0
value = -value
pv = [[-1, 1]]
else else
loop do pv = []
block.call(succ) end
for prime in generator
count = 0
while (value1, mod = value.divmod(prime)
mod) == 0
value = value1
count += 1
end end
if count != 0
pv.push [prime, count]
end
break if value1 <= prime
end end
end if value > 1
pv.push [value, 1]
# see +Enumerator+#with_index.
alias with_index each_with_index
# see +Enumerator+#with_object.
def with_object(obj)
return enum_for(:with_object) unless block_given?
each do |prime|
yield prime, obj
end end
end return pv
end
# An implementation of +PseudoPrimeGenerator+.
#
# Uses +EratosthenesSieve+.
class EratosthenesGenerator < PseudoPrimeGenerator
def initialize
@last_prime = nil
super
end end
def succ # An abstract class for enumerating pseudo-prime numbers.
@last_prime = @last_prime ? EratosthenesSieve.instance.next_to(@last_prime) : 2 #
end # Concrete subclasses should override succ, next, rewind.
def rewind class PseudoPrimeGenerator
initialize include Enumerable
end
alias next succ
end
# An implementation of +PseudoPrimeGenerator+ which uses def initialize(ubound = nil)
# a prime table generated by trial division. @ubound = ubound
class TrialDivisionGenerator<PseudoPrimeGenerator end
def initialize
@index = -1
super
end
def succ def upper_bound=(ubound)
TrialDivision.instance[@index += 1] @ubound = ubound
end end
def rewind def upper_bound
initialize @ubound
end end
alias next succ
end
# Generates all integer which are greater than 2 and # returns the next pseudo-prime number, and move the internal
# are not divided by 2 nor 3. # position forward.
# #
# This is a pseudo-prime generator, suitable on # +PseudoPrimeGenerator+#succ raises +NotImplementedError+.
# checking primality of a integer by brute force def succ
# method. raise NotImplementedError, "need to define `succ'"
class Generator23<PseudoPrimeGenerator end
def initialize
@prime = 1
@step = nil
super
end
def succ # alias of +succ+.
loop do def next
if (@step) raise NotImplementedError, "need to define `next'"
@prime += @step end
@step = 6 - @step
# Rewinds the internal position for enumeration.
#
# See +Enumerator+#rewind.
def rewind
raise NotImplementedError, "need to define `rewind'"
end
# Iterates the given block for each prime numbers.
def each(&block)
return self.dup unless block
if @ubound
last_value = nil
loop do
prime = succ
break last_value if prime > @ubound
last_value = block.call(prime)
end
else else
case @prime loop do
when 1; @prime = 2 block.call(succ)
when 2; @prime = 3
when 3; @prime = 5; @step = 2
end end
end end
return @prime
end end
end
alias next succ
def rewind
initialize
end
end
# see +Enumerator+#with_index.
alias with_index each_with_index
# see +Enumerator+#with_object.
def with_object(obj)
# Internal use. An implementation of prime table by trial division method. return enum_for(:with_object) unless block_given?
class TrialDivision each do |prime|
include Singleton yield prime, obj
def initialize # :nodoc:
# These are included as class variables to cache them for later uses. If memory
# usage is a problem, they can be put in Prime#initialize as instance variables.
# There must be no primes between @primes[-1] and @next_to_check.
@primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
# @next_to_check % 6 must be 1.
@next_to_check = 103 # @primes[-1] - @primes[-1] % 6 + 7
@ulticheck_index = 3 # @primes.index(@primes.reverse.find {|n|
# n < Math.sqrt(@@next_to_check) })
@ulticheck_next_squared = 121 # @primes[@ulticheck_index + 1] ** 2
end
# Returns the cached prime numbers.
def cache
return @primes
end
alias primes cache
alias primes_so_far cache
# Returns the +index+th prime number.
#
# +index+ is a 0-based index.
def [](index)
while index >= @primes.length
# Only check for prime factors up to the square root of the potential primes,
# but without the performance hit of an actual square root calculation.
if @next_to_check + 4 > @ulticheck_next_squared
@ulticheck_index += 1
@ulticheck_next_squared = @primes.at(@ulticheck_index + 1) ** 2
end end
# Only check numbers congruent to one and five, modulo six. All others
# are divisible by two or three. This also allows us to skip checking against
# two and three.
@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
@next_to_check += 4
@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
@next_to_check += 2
end end
return @primes[index]
end
end
# Internal use. An implementation of eratosthenes's sieve
class EratosthenesSieve
include Singleton
BITS_PER_ENTRY = 16 # each entry is a set of 16-bits in a Fixnum
NUMS_PER_ENTRY = BITS_PER_ENTRY * 2 # twiced because even numbers are omitted
ENTRIES_PER_TABLE = 8
NUMS_PER_TABLE = NUMS_PER_ENTRY * ENTRIES_PER_TABLE
FILLED_ENTRY = (1 << NUMS_PER_ENTRY) - 1
def initialize # :nodoc:
# bitmap for odd prime numbers less than 256.
# For an arbitrary odd number n, @tables[i][j][k] is
# * 1 if n is prime,
# * 0 if n is composite,
# where i,j,k = indices(n)
@tables = [[0xcb6e, 0x64b4, 0x129a, 0x816d, 0x4c32, 0x864a, 0x820d, 0x2196].freeze]
end end
# returns the least odd prime number which is greater than +n+. # An implementation of +PseudoPrimeGenerator+.
def next_to(n) #
n = (n-1).div(2)*2+3 # the next odd number to given n # Uses +EratosthenesSieve+.
table_index, integer_index, bit_index = indices(n) class EratosthenesGenerator < PseudoPrimeGenerator
loop do def initialize
extend_table until @tables.length > table_index @last_prime = nil
for j in integer_index...ENTRIES_PER_TABLE super
if !@tables[table_index][j].zero? end
for k in bit_index...BITS_PER_ENTRY
return NUMS_PER_TABLE*table_index + NUMS_PER_ENTRY*j + 2*k+1 if !@tables[table_index][j][k].zero? def succ
@last_prime = @last_prime ? EratosthenesSieve.instance.next_to(@last_prime) : 2
end
def rewind
initialize
end
alias next succ
end
# An implementation of +PseudoPrimeGenerator+ which uses
# a prime table generated by trial division.
class TrialDivisionGenerator<PseudoPrimeGenerator
def initialize
@index = -1
super
end
def succ
TrialDivision.instance[@index += 1]
end
def rewind
initialize
end
alias next succ
end
# Generates all integer which are greater than 2 and
# are not divided by 2 nor 3.
#
# This is a pseudo-prime generator, suitable on
# checking primality of a integer by brute force
# method.
class Generator23<PseudoPrimeGenerator
def initialize
@prime = 1
@step = nil
super
end
def succ
loop do
if (@step)
@prime += @step
@step = 6 - @step
else
case @prime
when 1; @prime = 2
when 2; @prime = 3
when 3; @prime = 5; @step = 2
end end
end end
bit_index = 0 return @prime
end
table_index += 1; integer_index = 0
end
end
private
# for an odd number +n+, returns (i, j, k) such that @tables[i][j][k] represents primarity of the number
def indices(n)
# binary digits of n: |0|1|2|3|4|5|6|7|8|9|10|11|....
# indices: |-| k | j | i
# because of NUMS_PER_ENTRY, NUMS_PER_TABLE
k = (n & 0b00011111) >> 1
j = (n & 0b11100000) >> 5
i = n >> 8
return i, j, k
end
def extend_table
lbound = NUMS_PER_TABLE * @tables.length
ubound = lbound + NUMS_PER_TABLE
new_table = [FILLED_ENTRY] * ENTRIES_PER_TABLE # which represents primarity in lbound...ubound
(3..Integer(Math.sqrt(ubound))).step(2) do |p|
i, j, k = indices(p)
next if @tables[i][j][k].zero?
start = (lbound.div(p)+1)*p # least multiple of p which is >= lbound
start += p if start.even?
(start...ubound).step(2*p) do |n|
_, j, k = indices(n)
new_table[j] &= FILLED_ENTRY^(1<<k)
end end
end end
@tables << new_table.freeze alias next succ
def rewind
initialize
end
end end
end
# Provides a +Prime+ object with compatibility to Ruby 1.8 when instantiated via +Prime+.+new+.
module OldCompatibility
# Returns the next prime number and forwards internal pointer.
def succ # Internal use. An implementation of prime table by trial division method.
@generator.succ class TrialDivision
include Singleton
def initialize # :nodoc:
# These are included as class variables to cache them for later uses. If memory
# usage is a problem, they can be put in Prime#initialize as instance variables.
# There must be no primes between @primes[-1] and @next_to_check.
@primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
# @next_to_check % 6 must be 1.
@next_to_check = 103 # @primes[-1] - @primes[-1] % 6 + 7
@ulticheck_index = 3 # @primes.index(@primes.reverse.find {|n|
# n < Math.sqrt(@@next_to_check) })
@ulticheck_next_squared = 121 # @primes[@ulticheck_index + 1] ** 2
end
# Returns the cached prime numbers.
def cache
return @primes
end
alias primes cache
alias primes_so_far cache
# Returns the +index+th prime number.
#
# +index+ is a 0-based index.
def [](index)
while index >= @primes.length
# Only check for prime factors up to the square root of the potential primes,
# but without the performance hit of an actual square root calculation.
if @next_to_check + 4 > @ulticheck_next_squared
@ulticheck_index += 1
@ulticheck_next_squared = @primes.at(@ulticheck_index + 1) ** 2
end
# Only check numbers congruent to one and five, modulo six. All others
# are divisible by two or three. This also allows us to skip checking against
# two and three.
@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
@next_to_check += 4
@primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
@next_to_check += 2
end
return @primes[index]
end
end end
alias next succ
# Overwrites Prime#each. # Internal use. An implementation of eratosthenes's sieve
# class EratosthenesSieve
# Iterates the given block over all prime numbers. Note that enumeration starts from include Singleton
# the current position of internal pointer, not rewound.
def each(&block) BITS_PER_ENTRY = 16 # each entry is a set of 16-bits in a Fixnum
return @generator.dup unless block_given? NUMS_PER_ENTRY = BITS_PER_ENTRY * 2 # twiced because even numbers are omitted
loop do ENTRIES_PER_TABLE = 8
yield succ NUMS_PER_TABLE = NUMS_PER_ENTRY * ENTRIES_PER_TABLE
FILLED_ENTRY = (1 << NUMS_PER_ENTRY) - 1
def initialize # :nodoc:
# bitmap for odd prime numbers less than 256.
# For an arbitrary odd number n, @tables[i][j][k] is
# * 1 if n is prime,
# * 0 if n is composite,
# where i,j,k = indices(n)
@tables = [[0xcb6e, 0x64b4, 0x129a, 0x816d, 0x4c32, 0x864a, 0x820d, 0x2196].freeze]
end
# returns the least odd prime number which is greater than +n+.
def next_to(n)
n = (n-1).div(2)*2+3 # the next odd number to given n
table_index, integer_index, bit_index = indices(n)
loop do
extend_table until @tables.length > table_index
for j in integer_index...ENTRIES_PER_TABLE
if !@tables[table_index][j].zero?
for k in bit_index...BITS_PER_ENTRY
return NUMS_PER_TABLE*table_index + NUMS_PER_ENTRY*j + 2*k+1 if !@tables[table_index][j][k].zero?
end
end
bit_index = 0
end
table_index += 1; integer_index = 0
end
end
private
# for an odd number +n+, returns (i, j, k) such that @tables[i][j][k] represents primarity of the number
def indices(n)
# binary digits of n: |0|1|2|3|4|5|6|7|8|9|10|11|....
# indices: |-| k | j | i
# because of NUMS_PER_ENTRY, NUMS_PER_TABLE
k = (n & 0b00011111) >> 1
j = (n & 0b11100000) >> 5
i = n >> 8
return i, j, k
end
def extend_table
lbound = NUMS_PER_TABLE * @tables.length
ubound = lbound + NUMS_PER_TABLE
new_table = [FILLED_ENTRY] * ENTRIES_PER_TABLE # which represents primarity in lbound...ubound
(3..Integer(Math.sqrt(ubound))).step(2) do |p|
i, j, k = indices(p)
next if @tables[i][j][k].zero?
start = (lbound.div(p)+1)*p # least multiple of p which is >= lbound
start += p if start.even?
(start...ubound).step(2*p) do |n|
_, j, k = indices(n)
new_table[j] &= FILLED_ENTRY^(1<<k)
end
end
@tables << new_table.freeze
end
end
# Provides a +Prime+ object with compatibility to Ruby 1.8 when instantiated via +Prime+.+new+.
module OldCompatibility
# Returns the next prime number and forwards internal pointer.
def succ
@generator.succ
end
alias next succ
# Overwrites Prime#each.
#
# Iterates the given block over all prime numbers. Note that enumeration starts from
# the current position of internal pointer, not rewound.
def each(&block)
return @generator.dup unless block_given?
loop do
yield succ
end
end end
end end
end end
end

View File

@ -6,15 +6,15 @@ module REXML
STOP = ']]>' STOP = ']]>'
ILLEGAL = /(\]\]>)/ ILLEGAL = /(\]\]>)/
# Constructor. CData is data between <![CDATA[ ... ]]> # Constructor. CData is data between <![CDATA[ ... ]]>
# #
# _Examples_ # _Examples_
# CData.new( source ) # CData.new( source )
# CData.new( "Here is some CDATA" ) # CData.new( "Here is some CDATA" )
# CData.new( "Some unprocessed data", respect_whitespace_TF, parent_element ) # CData.new( "Some unprocessed data", respect_whitespace_TF, parent_element )
def initialize( first, whitespace=true, parent=nil ) def initialize( first, whitespace=true, parent=nil )
super( first, whitespace, parent, false, true, ILLEGAL ) super( first, whitespace, parent, false, true, ILLEGAL )
end end
# Make a copy of this object # Make a copy of this object
# #

View File

@ -7,7 +7,7 @@ module REXML
# class directly. # class directly.
class Child class Child
include Node include Node
attr_reader :parent # The Parent of this object attr_reader :parent # The Parent of this object
# Constructor. Any inheritors of this class should call super to make # Constructor. Any inheritors of this class should call super to make
# sure this method is called. # sure this method is called.

View File

@ -38,15 +38,15 @@ module REXML
# See REXML::Formatters # See REXML::Formatters
# #
# output:: # output::
# Where to write the string # Where to write the string
# indent:: # indent::
# An integer. If -1, no indenting will be used; otherwise, the # An integer. If -1, no indenting will be used; otherwise, the
# indentation will be this number of spaces, and children will be # indentation will be this number of spaces, and children will be
# indented an additional amount. # indented an additional amount.
# transitive:: # transitive::
# Ignored by this class. The contents of comments are never modified. # Ignored by this class. The contents of comments are never modified.
# ie_hack:: # ie_hack::
# Needed for conformity to the child API, but not used by this class. # Needed for conformity to the child API, but not used by this class.
def write( output, indent=-1, transitive=false, ie_hack=false ) def write( output, indent=-1, transitive=false, ie_hack=false )
Kernel.warn("Comment.write is deprecated. See REXML::Formatters") Kernel.warn("Comment.write is deprecated. See REXML::Formatters")
indent( output, indent ) indent( output, indent )

View File

@ -165,7 +165,7 @@ module REXML
# Document.new("<a><b/></a>").serialize( tr ) # Document.new("<a><b/></a>").serialize( tr )
# #
# output:: # output::
# output an object which supports '<< string'; this is where the # output an object which supports '<< string'; this is where the
# document will be written. # document will be written.
# indent:: # indent::
# An integer. If -1, no indenting will be used; otherwise, the # An integer. If -1, no indenting will be used; otherwise, the
@ -188,15 +188,15 @@ module REXML
output = Output.new( output, xml_decl.encoding ) output = Output.new( output, xml_decl.encoding )
end end
formatter = if indent > -1 formatter = if indent > -1
if transitive if transitive
require "rexml/formatters/transitive" require "rexml/formatters/transitive"
REXML::Formatters::Transitive.new( indent, ie_hack ) REXML::Formatters::Transitive.new( indent, ie_hack )
else else
REXML::Formatters::Pretty.new( indent, ie_hack ) REXML::Formatters::Pretty.new( indent, ie_hack )
end end
else else
REXML::Formatters::Default.new( ie_hack ) REXML::Formatters::Default.new( ie_hack )
end end
formatter.write( self, output ) formatter.write( self, output )
end end

View File

@ -20,7 +20,7 @@ module REXML
class Element < Parent class Element < Parent
include Namespace include Namespace
UNDEFINED = "UNDEFINED"; # The default name UNDEFINED = "UNDEFINED"; # The default name
# Mechanisms for accessing attributes and child elements of this # Mechanisms for accessing attributes and child elements of this
# element. # element.
@ -297,7 +297,7 @@ module REXML
el = @elements.add(element) el = @elements.add(element)
attrs.each do |key, value| attrs.each do |key, value|
el.attributes[key]=value el.attributes[key]=value
end if attrs.kind_of? Hash end if attrs.kind_of? Hash
el el
end end
@ -667,7 +667,7 @@ module REXML
# #
# Writes out this element, and recursively, all children. # Writes out this element, and recursively, all children.
# output:: # output::
# output an object which supports '<< string'; this is where the # output an object which supports '<< string'; this is where the
# document will be written. # document will be written.
# indent:: # indent::
# An integer. If -1, no indenting will be used; otherwise, the # An integer. If -1, no indenting will be used; otherwise, the
@ -690,15 +690,15 @@ module REXML
def write(output=$stdout, indent=-1, transitive=false, ie_hack=false) def write(output=$stdout, indent=-1, transitive=false, ie_hack=false)
Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters") Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters")
formatter = if indent > -1 formatter = if indent > -1
if transitive if transitive
require "rexml/formatters/transitive" require "rexml/formatters/transitive"
REXML::Formatters::Transitive.new( indent, ie_hack ) REXML::Formatters::Transitive.new( indent, ie_hack )
else else
REXML::Formatters::Pretty.new( indent, ie_hack ) REXML::Formatters::Pretty.new( indent, ie_hack )
end end
else else
REXML::Formatters::Default.new( ie_hack ) REXML::Formatters::Default.new( ie_hack )
end end
formatter.write( self, output ) formatter.write( self, output )
end end
@ -778,7 +778,7 @@ module REXML
else else
return XPath::first( @element, index ) return XPath::first( @element, index )
#{ |element| #{ |element|
# return element if element.kind_of? Element # return element if element.kind_of? Element
#} #}
#return nil #return nil
end end
@ -1086,7 +1086,7 @@ module REXML
# doc.root.attributes['foo'] = '4' # doc.root.attributes['foo'] = '4'
# doc.root.attributes['x:foo'] = nil # doc.root.attributes['x:foo'] = nil
def []=( name, value ) def []=( name, value )
if value.nil? # Delete the named attribute if value.nil? # Delete the named attribute
attr = get_attribute(name) attr = get_attribute(name)
delete attr delete attr
return return
@ -1116,8 +1116,8 @@ module REXML
value.prefix != "xmlns" and old_attr.prefix != "xmlns" and value.prefix != "xmlns" and old_attr.prefix != "xmlns" and
@element.namespace( old_attr.prefix ) == @element.namespace( old_attr.prefix ) ==
@element.namespace( value.prefix ) @element.namespace( value.prefix )
store value.name, { old_attr.prefix => old_attr, store value.name, { old_attr.prefix => old_attr,
value.prefix => value } value.prefix => value }
else else
store value.name, value store value.name, value
end end
@ -1236,7 +1236,7 @@ module REXML
( !namespace.empty? || !attribute.fully_expanded_name.index(':') ) ( !namespace.empty? || !attribute.fully_expanded_name.index(':') )
# foo will match xmlns:foo, but only if foo isn't also an attribute # foo will match xmlns:foo, but only if foo isn't also an attribute
result = attribute if !result or !namespace.empty? or result = attribute if !result or !namespace.empty? or
!attribute.fully_expanded_name.index(':') !attribute.fully_expanded_name.index(':')
end end
} }
result result

View File

@ -1,13 +1,13 @@
require 'rexml/xmltokens' require 'rexml/xmltokens'
# [ :element, parent, name, attributes, children* ] # [ :element, parent, name, attributes, children* ]
# a = Node.new # a = Node.new
# a << "B" # => <a>B</a> # a << "B" # => <a>B</a>
# a.b # => <a>B<b/></a> # a.b # => <a>B<b/></a>
# a.b[1] # => <a>B<b/><b/><a> # a.b[1] # => <a>B<b/><b/><a>
# a.b[1]["x"] = "y" # => <a>B<b/><b x="y"/></a> # a.b[1]["x"] = "y" # => <a>B<b/><b x="y"/></a>
# a.b[0].c # => <a>B<b><c/></b><b x="y"/></a> # a.b[0].c # => <a>B<b><c/></b><b x="y"/></a>
# a.b.c << "D" # => <a>B<b><c>D</c></b><b x="y"/></a> # a.b.c << "D" # => <a>B<b><c>D</c></b><b x="y"/></a>
module REXML module REXML
module Light module Light
# Represents a tagged XML element. Elements are characterized by # Represents a tagged XML element. Elements are characterized by

View File

@ -36,12 +36,12 @@ module REXML
end end
def indent to, ind def indent to, ind
if @parent and @parent.context and not @parent.context[:indentstyle].nil? then if @parent and @parent.context and not @parent.context[:indentstyle].nil? then
indentstyle = @parent.context[:indentstyle] indentstyle = @parent.context[:indentstyle]
else else
indentstyle = ' ' indentstyle = ' '
end end
to << indentstyle*ind unless ind<1 to << indentstyle*ind unless ind<1
end end
def parent? def parent?

View File

@ -44,10 +44,10 @@ module REXML
end end
# An element is an array. The array contains: # An element is an array. The array contains:
# 0 The parent element # 0 The parent element
# 1 The tag name # 1 The tag name
# 2 A hash of attributes # 2 A hash of attributes
# 3..-1 The child elements # 3..-1 The child elements
# An element is an array of size > 3 # An element is an array of size > 3
# Text is a String # Text is a String
# PIs are [ :processing_instruction, target, data ] # PIs are [ :processing_instruction, target, data ]

View File

@ -28,15 +28,15 @@ module REXML
# Listen arguments: # Listen arguments:
# #
# Symbol, Array, Block # Symbol, Array, Block
# Listen to Symbol events on Array elements # Listen to Symbol events on Array elements
# Symbol, Block # Symbol, Block
# Listen to Symbol events # Listen to Symbol events
# Array, Listener # Array, Listener
# Listen to all events on Array elements # Listen to all events on Array elements
# Array, Block # Array, Block
# Listen to :start_element events on Array elements # Listen to :start_element events on Array elements
# Listener # Listener
# Listen to All events # Listen to All events
# #
# Symbol can be one of: :start_element, :end_element, # Symbol can be one of: :start_element, :end_element,
# :start_prefix_mapping, :end_prefix_mapping, :characters, # :start_prefix_mapping, :end_prefix_mapping, :characters,
@ -209,7 +209,7 @@ module REXML
((name.nil? and match.nil?) or match.nil? or ( ((name.nil? and match.nil?) or match.nil? or (
(name == match) or (name == match) or
(match.kind_of? Regexp and name =~ match) (match.kind_of? Regexp and name =~ match)
) )
) )
) )
end.collect{|x| x[-1]} end.collect{|x| x[-1]}
@ -222,7 +222,7 @@ module REXML
((name.nil? and match.nil?) or match.nil? or ( ((name.nil? and match.nil?) or match.nil? or (
(name == match) or (name == match) or
(match.kind_of? Regexp and name =~ match) (match.kind_of? Regexp and name =~ match)
) )
) )
) )
end.collect{|x| x[-1]} end.collect{|x| x[-1]}

View File

@ -42,10 +42,10 @@ module REXML
end end
# An element is an array. The array contains: # An element is an array. The array contains:
# 0 The parent element # 0 The parent element
# 1 The tag name # 1 The tag name
# 2 A hash of attributes # 2 A hash of attributes
# 3..-1 The child elements # 3..-1 The child elements
# An element is an array of size > 3 # An element is an array of size > 3
# Text is a String # Text is a String
# PIs are [ :processing_instruction, target, data ] # PIs are [ :processing_instruction, target, data ]

View File

@ -49,20 +49,20 @@ module REXML
def QuickPath::filter elements, path def QuickPath::filter elements, path
return elements if path.nil? or path == '' or elements.size == 0 return elements if path.nil? or path == '' or elements.size == 0
case path case path
when /^\/\//u # Descendant when /^\/\//u # Descendant
return axe( elements, "descendant-or-self", $' ) return axe( elements, "descendant-or-self", $' )
when /^\/?\b(\w[-\w]*)\b::/u # Axe when /^\/?\b(\w[-\w]*)\b::/u # Axe
return axe( elements, $1, $' ) return axe( elements, $1, $' )
when /^\/(?=\b([:!\w][-\.\w]*:)?[-!\*\.\w]*\b([^:(]|$)|\*)/u # Child when /^\/(?=\b([:!\w][-\.\w]*:)?[-!\*\.\w]*\b([^:(]|$)|\*)/u # Child
rest = $' rest = $'
results = [] results = []
elements.each do |element| elements.each do |element|
results |= filter( element.to_a, rest ) results |= filter( element.to_a, rest )
end end
return results return results
when /^\/?(\w[-\w]*)\(/u # / Function when /^\/?(\w[-\w]*)\(/u # / Function
return function( elements, $1, $' ) return function( elements, $1, $' )
when Namespace::NAMESPLIT # Element name when Namespace::NAMESPLIT # Element name
name = $2 name = $2
ns = $1 ns = $1
rest = $' rest = $'
@ -79,22 +79,22 @@ module REXML
matches |= predicate( element.to_a, path[1..-1] ) if element.kind_of? Element matches |= predicate( element.to_a, path[1..-1] ) if element.kind_of? Element
end end
return matches return matches
when /^\[/u # Predicate when /^\[/u # Predicate
return predicate( elements, path ) return predicate( elements, path )
when /^\/?\.\.\./u # Ancestor when /^\/?\.\.\./u # Ancestor
return axe( elements, "ancestor", $' ) return axe( elements, "ancestor", $' )
when /^\/?\.\./u # Parent when /^\/?\.\./u # Parent
return filter( elements.collect{|e|e.parent}, $' ) return filter( elements.collect{|e|e.parent}, $' )
when /^\/?\./u # Self when /^\/?\./u # Self
return filter( elements, $' ) return filter( elements, $' )
when /^\*/u # Any when /^\*/u # Any
results = [] results = []
elements.each do |element| elements.each do |element|
results |= filter( [element], $' ) if element.kind_of? Element results |= filter( [element], $' ) if element.kind_of? Element
#if element.kind_of? Element #if element.kind_of? Element
# children = element.to_a # children = element.to_a
# children.delete_if { |child| !child.kind_of?(Element) } # children.delete_if { |child| !child.kind_of?(Element) }
# results |= filter( children, $' ) # results |= filter( children, $' )
#end #end
end end
return results return results
@ -132,7 +132,7 @@ module REXML
matches = filter(elements.collect{|element| element.parent}.uniq, rest) matches = filter(elements.collect{|element| element.parent}.uniq, rest)
when "following-sibling" when "following-sibling"
matches = filter(elements.collect{|element| element.next_sibling}.uniq, matches = filter(elements.collect{|element| element.next_sibling}.uniq,
rest) rest)
when "previous-sibling" when "previous-sibling"
matches = filter(elements.collect{|element| matches = filter(elements.collect{|element|
element.previous_sibling}.uniq, rest ) element.previous_sibling}.uniq, rest )
@ -174,32 +174,32 @@ module REXML
predicate.gsub!( predicate.gsub!(
/#{OPERAND_}\s*([<>=])\s*#{OPERAND_}\s*([<>=])\s*#{OPERAND_}/u, /#{OPERAND_}\s*([<>=])\s*#{OPERAND_}\s*([<>=])\s*#{OPERAND_}/u,
'\1 \2 \3 and \3 \4 \5' ) '\1 \2 \3 and \3 \4 \5' )
# Let's do some Ruby trickery to avoid some work: # Let's do some Ruby trickery to avoid some work:
predicate.gsub!( /&/u, "&&" ) predicate.gsub!( /&/u, "&&" )
predicate.gsub!( /=/u, "==" ) predicate.gsub!( /=/u, "==" )
predicate.gsub!( /@(\w[-\w.]*)/u, 'attribute("\1")' ) predicate.gsub!( /@(\w[-\w.]*)/u, 'attribute("\1")' )
predicate.gsub!( /\bmod\b/u, "%" ) predicate.gsub!( /\bmod\b/u, "%" )
predicate.gsub!( /\b(\w[-\w.]*\()/u ) { predicate.gsub!( /\b(\w[-\w.]*\()/u ) {
fname = $1 fname = $1
fname.gsub( /-/u, "_" ) fname.gsub( /-/u, "_" )
} }
Functions.pair = [ 0, elements.size ] Functions.pair = [ 0, elements.size ]
results = [] results = []
elements.each do |element| elements.each do |element|
Functions.pair[0] += 1 Functions.pair[0] += 1
Functions.node = element Functions.node = element
res = eval( predicate ) res = eval( predicate )
case res case res
when true when true
results << element results << element
when Fixnum when Fixnum
results << element if Functions.pair[0] == res results << element if Functions.pair[0] == res
when String when String
results << element results << element
end
end end
return filter( results, rest ) end
return filter( results, rest )
end end
def QuickPath::attribute( name ) def QuickPath::attribute( name )

View File

@ -51,7 +51,7 @@ module RSS
module_eval(<<-EOC, __FILE__, __LINE__ + 1) module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def new_#{name} def new_#{name}
#{name} = self.class::#{klass_name}.new(@maker) #{name} = self.class::#{klass_name}.new(@maker)
@#{plural} << #{name} @#{plural} << #{name}
if block_given? if block_given?
yield #{name} yield #{name}
@ -63,14 +63,14 @@ module RSS
def to_feed(*args) def to_feed(*args)
@#{plural}.each do |#{name}| @#{plural}.each do |#{name}|
#{name}.to_feed(*args) #{name}.to_feed(*args)
end end
end end
def replace(elements) def replace(elements)
@#{plural}.replace(elements.to_a) @#{plural}.replace(elements.to_a)
end end
EOC EOC
end end
def def_classed_element_without_accessor(name, class_name=nil) def def_classed_element_without_accessor(name, class_name=nil)
@ -88,7 +88,7 @@ module RSS
def make_#{name} def make_#{name}
self.class::#{class_name}.new(@maker) self.class::#{class_name}.new(@maker)
end end
EOC EOC
end end
def def_classed_element(name, class_name=nil, attribute_name=nil) def def_classed_element(name, class_name=nil, attribute_name=nil)
@ -106,7 +106,7 @@ module RSS
def #{name}=(new_value) def #{name}=(new_value)
@#{name}.#{attribute_name} = new_value @#{name}.#{attribute_name} = new_value
end end
EOC EOC
else else
attr_reader name attr_reader name
end end
@ -126,17 +126,17 @@ module RSS
end end
module_eval(<<-EOC, __FILE__, __LINE__ + 1) module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def #{name} def #{name}
#{local_variable_name} = #{plural_name}.first #{local_variable_name} = #{plural_name}.first
#{local_variable_name} ? #{local_variable_name}.#{attribute} : nil #{local_variable_name} ? #{local_variable_name}.#{attribute} : nil
end end
def #{name}=(#{new_value_variable_name}) def #{name}=(#{new_value_variable_name})
#{local_variable_name} = #{local_variable_name} =
#{plural_name}.first || #{plural_name}.new_#{new_name} #{plural_name}.first || #{plural_name}.new_#{new_name}
#{additional_setup_code} #{additional_setup_code}
#{local_variable_name}.#{attribute} = #{new_value_variable_name} #{local_variable_name}.#{attribute} = #{new_value_variable_name}
end end
EOC EOC
end end
def def_other_element(name) def def_other_element(name)
@ -153,7 +153,7 @@ module RSS
current.#{name} = @#{name} current.#{name} = @#{name}
end end
end end
EOC EOC
end end
def def_csv_element(name, type=nil) def def_csv_element(name, type=nil)
@ -167,7 +167,7 @@ module RSS
def #{name}=(value) def #{name}=(value)
@#{name} = Utils::CSV.parse(value)#{converter} @#{name} = Utils::CSV.parse(value)#{converter}
end end
EOC EOC
end end
end end
@ -308,7 +308,7 @@ module RSS
def ensure_xml_content(content) def ensure_xml_content(content)
xhtml_uri = ::RSS::Atom::XHTML_URI xhtml_uri = ::RSS::Atom::XHTML_URI
unless content.is_a?(RSS::XML::Element) and unless content.is_a?(RSS::XML::Element) and
["div", xhtml_uri] == [content.name, content.uri] ["div", xhtml_uri] == [content.name, content.uri]
children = content children = content
children = [children] unless content.is_a?(Array) children = [children] unless content.is_a?(Array)
children = set_xhtml_uri_as_default_uri(children) children = set_xhtml_uri_as_default_uri(children)
@ -331,7 +331,7 @@ module RSS
def set_xhtml_uri_as_default_uri(children) def set_xhtml_uri_as_default_uri(children)
children.collect do |child| children.collect do |child|
if child.is_a?(RSS::XML::Element) and if child.is_a?(RSS::XML::Element) and
child.prefix.nil? and child.uri.nil? child.prefix.nil? and child.uri.nil?
RSS::XML::Element.new(child.name, nil, ::RSS::Atom::XHTML_URI, RSS::XML::Element.new(child.name, nil, ::RSS::Atom::XHTML_URI,
child.attributes.dup, child.attributes.dup,
set_xhtml_uri_as_default_uri(child.children)) set_xhtml_uri_as_default_uri(child.children))
@ -385,7 +385,7 @@ module RSS
} }
_language = language _language = language
if _language and if _language and
!dc_languages.any? {|dc_language| dc_language.value == _language} !dc_languages.any? {|dc_language| dc_language.value == _language}
dc_language = self.class::DublinCoreLanguages::DublinCoreLanguage.new(self) dc_language = self.class::DublinCoreLanguages::DublinCoreLanguage.new(self)
dc_language.value = _language.dup dc_language.value = _language.dup
dc_languages.unshift(dc_language) dc_languages.unshift(dc_language)
@ -417,7 +417,7 @@ module RSS
def make_#{element} def make_#{element}
self.class::#{Utils.to_class_name(element)}.new(self) self.class::#{Utils.to_class_name(element)}.new(self)
end end
EOC EOC
end end
attr_reader :feed_version attr_reader :feed_version
@ -500,9 +500,9 @@ module RSS
end end
[ [
["link", "href", Proc.new {|target,| "#{target}.href = 'self'"}], ["link", "href", Proc.new {|target,| "#{target}.href = 'self'"}],
["author", "name"], ["author", "name"],
["contributor", "name"], ["contributor", "name"],
].each do |name, attribute, additional_setup_maker| ].each do |name, attribute, additional_setup_maker|
def_classed_elements(name, attribute, &additional_setup_maker) def_classed_elements(name, attribute, &additional_setup_maker)
end end
@ -511,7 +511,7 @@ module RSS
managingEditor webMaster rating docs ttl).each do |element| managingEditor webMaster rating docs ttl).each do |element|
attr_accessor element attr_accessor element
add_need_initialize_variable(element) add_need_initialize_variable(element)
end end
%w(date lastBuildDate).each do |date_element| %w(date lastBuildDate).each do |date_element|
attr_reader date_element attr_reader date_element
@ -713,9 +713,9 @@ module RSS
end end
[ [
["author", "name"], ["author", "name"],
["link", "href", Proc.new {|target,| "#{target}.href = 'alternate'"}], ["link", "href", Proc.new {|target,| "#{target}.href = 'alternate'"}],
["contributor", "name"], ["contributor", "name"],
].each do |name, attribute| ].each do |name, attribute|
def_classed_elements(name, attribute) def_classed_elements(name, attribute)
end end
@ -795,10 +795,10 @@ module RSS
%w(authors categories contributors generator icon %w(authors categories contributors generator icon
logo rights subtitle title).each do |name| logo rights subtitle title).each do |name|
def_classed_element(name) def_classed_element(name)
end end
[ [
["link", "href"], ["link", "href"],
].each do |name, attribute| ].each do |name, attribute|
def_classed_elements(name, attribute) def_classed_elements(name, attribute)
end end

View File

@ -17,7 +17,7 @@ module RSS
class ImageItem < ImageItemBase class ImageItem < ImageItemBase
DublinCoreModel.install_dublin_core(self) DublinCoreModel.install_dublin_core(self)
end end
EOC EOC
end end
class ImageItemBase < Base class ImageItemBase < Base
@ -29,9 +29,9 @@ module RSS
add_need_initialize_variable("image_width") add_need_initialize_variable("image_width")
add_need_initialize_variable("image_height") add_need_initialize_variable("image_height")
alias width= image_width= alias width= image_width=
alias width image_width alias width image_width
alias height= image_height= alias height= image_height=
alias height image_height alias height image_height
def have_required_values? def have_required_values?
@about @about
@ -73,9 +73,9 @@ module RSS
alias size image_size alias size image_size
alias size= image_size= alias size= image_size=
def have_required_values? def have_required_values?
@about and @image_size @about and @image_size
end end
def to_feed(feed, current) def to_feed(feed, current)
if current.respond_to?(:image_favicon=) and have_required_values? if current.respond_to?(:image_favicon=) and have_required_values?

View File

@ -5,27 +5,27 @@ class Time
unless respond_to?(:w3cdtf) unless respond_to?(:w3cdtf)
def w3cdtf(date) def w3cdtf(date)
if /\A\s* if /\A\s*
(-?\d+)-(\d\d)-(\d\d) (-?\d+)-(\d\d)-(\d\d)
(?:T (?:T
(\d\d):(\d\d)(?::(\d\d))? (\d\d):(\d\d)(?::(\d\d))?
(\.\d+)? (\.\d+)?
(Z|[+-]\d\d:\d\d)?)? (Z|[+-]\d\d:\d\d)?)?
\s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8)) \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8))
datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i] datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i]
usec = 0 usec = 0
usec = $7.to_f * 1000000 if $7 usec = $7.to_f * 1000000 if $7
zone = $8 zone = $8
if zone if zone
off = zone_offset(zone, datetime[0]) off = zone_offset(zone, datetime[0])
datetime = apply_offset(*(datetime + [off])) datetime = apply_offset(*(datetime + [off]))
datetime << usec datetime << usec
time = Time.utc(*datetime) time = Time.utc(*datetime)
time.localtime unless zone_utc?(zone) time.localtime unless zone_utc?(zone)
time time
else else
datetime << usec datetime << usec
Time.local(*datetime) Time.local(*datetime)
end end
else else
raise ArgumentError.new("invalid date: #{date.inspect}") raise ArgumentError.new("invalid date: #{date.inspect}")
end end
@ -209,7 +209,7 @@ module RSS
else else
'' ''
end end
EOC EOC
end end
end end
alias_method(:install_have_attribute_element, :install_have_child_element) alias_method(:install_have_attribute_element, :install_have_child_element)
@ -230,7 +230,7 @@ module RSS
rv << value if /\\A\\s*\\z/ !~ value rv << value if /\\A\\s*\\z/ !~ value
end end
rv.join("\n") rv.join("\n")
EOC EOC
end end
end end
@ -259,12 +259,12 @@ module RSS
else else
rv << value rv << value
end end
rv << "</#{elem_name}>" rv << "</#{elem_name}>"
rv rv
else else
'' ''
end end
EOC EOC
end end
end end
@ -290,12 +290,12 @@ module RSS
else else
rv << value rv << value
end end
rv << "</#{elem_name}>" rv << "</#{elem_name}>"
rv rv
else else
'' ''
end end
EOC EOC
end end
end end
@ -307,10 +307,10 @@ module RSS
add_to_element_method(method_name) add_to_element_method(method_name)
module_eval(<<-EOC, *get_file_and_line_from_caller(2)) module_eval(<<-EOC, *get_file_and_line_from_caller(2))
def #{method_name}(need_convert=true, indent='') def #{method_name}(need_convert=true, indent='')
#{yield(name, elem_name)} #{yield(name, elem_name)}
end end
private :#{method_name} private :#{method_name}
EOC EOC
end end
def inherit_convert_attr_reader(*attrs) def inherit_convert_attr_reader(*attrs)
@ -323,14 +323,14 @@ module RSS
def #{attr} def #{attr}
if @#{attr} if @#{attr}
#{attr}_without_inherit #{attr}_without_inherit
elsif @parent elsif @parent
@parent.#{attr} @parent.#{attr}
else else
nil nil
end end
end end
EOC EOC
end end
end end
@ -351,7 +351,7 @@ module RSS
"\#{base}\#{value}" "\#{base}\#{value}"
end end
end end
EOC EOC
end end
end end
@ -362,7 +362,7 @@ module RSS
def #{attr} def #{attr}
convert(@#{attr}) convert(@#{attr})
end end
EOC EOC
end end
end end
@ -408,7 +408,7 @@ module RSS
@#{attr}.join(#{separator.dump}) @#{attr}.join(#{separator.dump})
end end
end end
EOC EOC
end end
end end
@ -448,7 +448,7 @@ module RSS
end end
end end
EOC EOC
end end
def integer_writer(name, disp_name=name) def integer_writer(name, disp_name=name)
@ -468,7 +468,7 @@ module RSS
end end
end end
end end
EOC EOC
end end
def positive_integer_writer(name, disp_name=name) def positive_integer_writer(name, disp_name=name)
@ -490,7 +490,7 @@ module RSS
end end
end end
end end
EOC EOC
end end
def boolean_writer(name, disp_name=name) def boolean_writer(name, disp_name=name)
@ -510,7 +510,7 @@ module RSS
end end
end end
end end
EOC EOC
end end
def text_type_writer(name, disp_name=name) def text_type_writer(name, disp_name=name)
@ -522,7 +522,7 @@ module RSS
end end
@#{name} = new_value @#{name} = new_value
end end
EOC EOC
end end
def content_writer(name, disp_name=name) def content_writer(name, disp_name=name)
@ -536,7 +536,7 @@ module RSS
@#{name}.content = new_value @#{name}.content = new_value
end end
end end
EOC EOC
end end
def yes_clean_other_writer(name, disp_name=name) def yes_clean_other_writer(name, disp_name=name)
@ -603,7 +603,7 @@ module RSS
end end
end end
alias_method(:set_#{accessor_name}, :#{accessor_name}=) alias_method(:set_#{accessor_name}, :#{accessor_name}=)
EOC EOC
end end
end end
@ -630,7 +630,7 @@ module RSS
value = __send__(var) value = __send__(var)
next if value.nil? next if value.nil?
if value.respond_to?("setup_maker") and if value.respond_to?("setup_maker") and
!not_need_to_call_setup_maker_variables.include?(var) !not_need_to_call_setup_maker_variables.include?(var)
value.setup_maker(target) value.setup_maker(target)
else else
setter = "#{var}=" setter = "#{var}="
@ -1173,7 +1173,7 @@ module RSS
else else
if name == tag if name == tag
if models[i+1] and models[i+1][0] != name and if models[i+1] and models[i+1][0] != name and
tags and tags.first == name tags and tags.first == name
raise TooMuchTagError.new(name, tag_name) raise TooMuchTagError.new(name, tag_name)
end end
else else

View File

@ -506,28 +506,28 @@ module Scanf
class FormatString class FormatString
attr_reader :string_left, :last_spec_tried, attr_reader :string_left, :last_spec_tried,
:last_match_tried, :matched_count, :space :last_match_tried, :matched_count, :space
SPECIFIERS = 'diuXxofFeEgGscaA' SPECIFIERS = 'diuXxofFeEgGscaA'
REGEX = / REGEX = /
# possible space, followed by... # possible space, followed by...
(?:\s* (?:\s*
# percent sign, followed by... # percent sign, followed by...
% %
# another percent sign, or... # another percent sign, or...
(?:%| (?:%|
# optional assignment suppression flag # optional assignment suppression flag
\*? \*?
# optional maximum field width # optional maximum field width
\d* \d*
# named character class, ... # named character class, ...
(?:\[\[:\w+:\]\]| (?:\[\[:\w+:\]\]|
# traditional character class, or... # traditional character class, or...
\[[^\]]*\]| \[[^\]]*\]|
# specifier letter. # specifier letter.
[#{SPECIFIERS}])))| [#{SPECIFIERS}])))|
# or miscellaneous characters # or miscellaneous characters
[^%\s]+/ix [^%\s]+/ix
def initialize(str) def initialize(str)
@specs = [] @specs = []
@ -578,33 +578,33 @@ end
class IO class IO
# The trick here is doing a match where you grab one *line* # The trick here is doing a match where you grab one *line*
# of input at a time. The linebreak may or may not occur # of input at a time. The linebreak may or may not occur
# at the boundary where the string matches a format specifier. # at the boundary where the string matches a format specifier.
# And if it does, some rule about whitespace may or may not # And if it does, some rule about whitespace may or may not
# be in effect... # be in effect...
# #
# That's why this is much more elaborate than the string # That's why this is much more elaborate than the string
# version. # version.
# #
# For each line: # For each line:
# Match succeeds (non-emptily) # Match succeeds (non-emptily)
# and the last attempted spec/string sub-match succeeded: # and the last attempted spec/string sub-match succeeded:
# #
# could the last spec keep matching? # could the last spec keep matching?
# yes: save interim results and continue (next line) # yes: save interim results and continue (next line)
# #
# The last attempted spec/string did not match: # The last attempted spec/string did not match:
# #
# are we on the next-to-last spec in the string? # are we on the next-to-last spec in the string?
# yes: # yes:
# is fmt_string.string_left all spaces? # is fmt_string.string_left all spaces?
# yes: does current spec care about input space? # yes: does current spec care about input space?
# yes: fatal failure # yes: fatal failure
# no: save interim results and continue # no: save interim results and continue
# no: continue [this state could be analyzed further] # no: continue [this state could be analyzed further]
# #
# #
def scanf(str,&b) def scanf(str,&b)
return block_scanf(str,&b) if b return block_scanf(str,&b) if b
@ -671,8 +671,8 @@ class IO
def block_scanf(str) def block_scanf(str)
final = [] final = []
# Sub-ideal, since another FS gets created in scanf. # Sub-ideal, since another FS gets created in scanf.
# But used here to determine the number of specifiers. # But used here to determine the number of specifiers.
fstr = Scanf::FormatString.new(str) fstr = Scanf::FormatString.new(str)
last_spec = fstr.last_spec last_spec = fstr.last_spec
begin begin

View File

@ -92,19 +92,19 @@ class Set
@hash = orig.instance_eval{@hash}.dup @hash = orig.instance_eval{@hash}.dup
end end
def freeze # :nodoc: def freeze # :nodoc:
super super
@hash.freeze @hash.freeze
self self
end end
def taint # :nodoc: def taint # :nodoc:
super super
@hash.taint @hash.taint
self self
end end
def untaint # :nodoc: def untaint # :nodoc:
super super
@hash.untaint @hash.untaint
self self
@ -325,163 +325,163 @@ class Set
def |(enum) def |(enum)
dup.merge(enum) dup.merge(enum)
end end
alias + | ## alias + | ##
alias union | ## alias union | ##
# Returns a new set built by duplicating the set, removing every # Returns a new set built by duplicating the set, removing every
# element that appears in the given enumerable object. # element that appears in the given enumerable object.
def -(enum) def -(enum)
dup.subtract(enum) dup.subtract(enum)
end end
alias difference - ## alias difference - ##
# Returns a new set containing elements common to the set and the # Returns a new set containing elements common to the set and the
# given enumerable object. # given enumerable object.
def &(enum) def &(enum)
n = self.class.new n = self.class.new
do_with_enum(enum) { |o| n.add(o) if include?(o) } do_with_enum(enum) { |o| n.add(o) if include?(o) }
n n
end end
alias intersection & ## alias intersection & ##
# Returns a new set containing elements exclusive between the set # Returns a new set containing elements exclusive between the set
# and the given enumerable object. (set ^ enum) is equivalent to # and the given enumerable object. (set ^ enum) is equivalent to
# ((set | enum) - (set & enum)). # ((set | enum) - (set & enum)).
def ^(enum) def ^(enum)
n = Set.new(enum) n = Set.new(enum)
each { |o| if n.include?(o) then n.delete(o) else n.add(o) end } each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
n n
end
# Returns true if two sets are equal. The equality of each couple
# of elements is defined according to Object#eql?.
def ==(other)
if self.equal?(other)
true
elsif other.instance_of?(self.class)
@hash == other.instance_variable_get(:@hash)
elsif other.is_a?(Set) && self.size == other.size
other.all? { |o| @hash.include?(o) }
else
false
end end
end
def hash # :nodoc: # Returns true if two sets are equal. The equality of each couple
@hash.hash # of elements is defined according to Object#eql?.
end def ==(other)
if self.equal?(other)
true
elsif other.instance_of?(self.class)
@hash == other.instance_variable_get(:@hash)
elsif other.is_a?(Set) && self.size == other.size
other.all? { |o| @hash.include?(o) }
else
false
end
end
def eql?(o) # :nodoc: def hash # :nodoc:
return false unless o.is_a?(Set) @hash.hash
@hash.eql?(o.instance_eval{@hash}) end
end
# Classifies the set by the return value of the given block and def eql?(o) # :nodoc:
# returns a hash of {value => set of elements} pairs. The block is return false unless o.is_a?(Set)
# called once for each element of the set, passing the element as @hash.eql?(o.instance_eval{@hash})
# parameter. end
#
# e.g.:
#
# require 'set'
# files = Set.new(Dir.glob("*.rb"))
# hash = files.classify { |f| File.mtime(f).year }
# p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
# # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
# # 2002=>#<Set: {"f.rb"}>}
def classify # :yields: o
block_given? or return enum_for(__method__)
h = {} # Classifies the set by the return value of the given block and
# returns a hash of {value => set of elements} pairs. The block is
# called once for each element of the set, passing the element as
# parameter.
#
# e.g.:
#
# require 'set'
# files = Set.new(Dir.glob("*.rb"))
# hash = files.classify { |f| File.mtime(f).year }
# p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
# # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
# # 2002=>#<Set: {"f.rb"}>}
def classify # :yields: o
block_given? or return enum_for(__method__)
each { |i| h = {}
x = yield(i)
(h[x] ||= self.class.new).add(i)
}
h each { |i|
end x = yield(i)
(h[x] ||= self.class.new).add(i)
}
# Divides the set into a set of subsets according to the commonality h
# defined by the given block. end
#
# If the arity of the block is 2, elements o1 and o2 are in common
# if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
# in common if block.call(o1) == block.call(o2).
#
# e.g.:
#
# require 'set'
# numbers = Set[1, 3, 4, 6, 9, 10, 11]
# set = numbers.divide { |i,j| (i - j).abs == 1 }
# p set # => #<Set: {#<Set: {1}>,
# # #<Set: {11, 9, 10}>,
# # #<Set: {3, 4}>,
# # #<Set: {6}>}>
def divide(&func)
func or return enum_for(__method__)
if func.arity == 2 # Divides the set into a set of subsets according to the commonality
require 'tsort' # defined by the given block.
#
# If the arity of the block is 2, elements o1 and o2 are in common
# if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
# in common if block.call(o1) == block.call(o2).
#
# e.g.:
#
# require 'set'
# numbers = Set[1, 3, 4, 6, 9, 10, 11]
# set = numbers.divide { |i,j| (i - j).abs == 1 }
# p set # => #<Set: {#<Set: {1}>,
# # #<Set: {11, 9, 10}>,
# # #<Set: {3, 4}>,
# # #<Set: {6}>}>
def divide(&func)
func or return enum_for(__method__)
class << dig = {} # :nodoc: if func.arity == 2
include TSort require 'tsort'
alias tsort_each_node each_key class << dig = {} # :nodoc:
def tsort_each_child(node, &block) include TSort
fetch(node).each(&block)
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end end
each { |u|
dig[u] = a = []
each{ |v| func.call(u, v) and a << v }
}
set = Set.new()
dig.each_strongly_connected_component { |css|
set.add(self.class.new(css))
}
set
else
Set.new(classify(&func).values)
end
end
InspectKey = :__inspect_key__ # :nodoc:
# Returns a string containing a human-readable representation of the
# set. ("#<Set: {element1, element2, ...}>")
def inspect
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return sprintf('#<%s: {...}>', self.class.name)
end end
each { |u| begin
dig[u] = a = [] ids << object_id
each{ |v| func.call(u, v) and a << v } return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
ensure
ids.pop
end
end
def pretty_print(pp) # :nodoc:
pp.text sprintf('#<%s: {', self.class.name)
pp.nest(1) {
pp.seplist(self) { |o|
pp.pp o
}
} }
pp.text "}>"
set = Set.new()
dig.each_strongly_connected_component { |css|
set.add(self.class.new(css))
}
set
else
Set.new(classify(&func).values)
end
end
InspectKey = :__inspect_key__ # :nodoc:
# Returns a string containing a human-readable representation of the
# set. ("#<Set: {element1, element2, ...}>")
def inspect
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return sprintf('#<%s: {...}>', self.class.name)
end end
begin def pretty_print_cycle(pp) # :nodoc:
ids << object_id pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
ensure
ids.pop
end end
end end
def pretty_print(pp) # :nodoc:
pp.text sprintf('#<%s: {', self.class.name)
pp.nest(1) {
pp.seplist(self) { |o|
pp.pp o
}
}
pp.text "}>"
end
def pretty_print_cycle(pp) # :nodoc:
pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
end
end
# #
# SortedSet implements a Set that guarantees that it's element are # SortedSet implements a Set that guarantees that it's element are
# yielded in sorted order (according to the return values of their # yielded in sorted order (according to the return values of their
@ -515,11 +515,11 @@ class SortedSet < Set
@@setup = false @@setup = false
class << self class << self
def [](*ary) # :nodoc: def [](*ary) # :nodoc:
new(ary) new(ary)
end end
def setup # :nodoc: def setup # :nodoc:
@@setup and return @@setup and return
module_eval { module_eval {
@ -531,78 +531,78 @@ class SortedSet < Set
require 'rbtree' require 'rbtree'
module_eval %{ module_eval %{
def initialize(*args, &block) def initialize(*args, &block)
@hash = RBTree.new @hash = RBTree.new
super super
end end
def add(o) def add(o)
o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>" o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
super super
end end
alias << add alias << add
} }
rescue LoadError rescue LoadError
module_eval %{ module_eval %{
def initialize(*args, &block) def initialize(*args, &block)
@keys = nil @keys = nil
super super
end end
def clear def clear
@keys = nil @keys = nil
super super
end end
def replace(enum) def replace(enum)
@keys = nil @keys = nil
super super
end end
def add(o) def add(o)
o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>" o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
@keys = nil @keys = nil
super super
end end
alias << add alias << add
def delete(o) def delete(o)
@keys = nil @keys = nil
@hash.delete(o) @hash.delete(o)
self self
end end
def delete_if def delete_if
block_given? or return enum_for(__method__) block_given? or return enum_for(__method__)
n = @hash.size n = @hash.size
super super
@keys = nil if @hash.size != n @keys = nil if @hash.size != n
self self
end end
def keep_if def keep_if
block_given? or return enum_for(__method__) block_given? or return enum_for(__method__)
n = @hash.size n = @hash.size
super super
@keys = nil if @hash.size != n @keys = nil if @hash.size != n
self self
end end
def merge(enum) def merge(enum)
@keys = nil @keys = nil
super super
end end
def each def each
block_given? or return enum_for(__method__) block_given? or return enum_for(__method__)
to_a.each { |o| yield(o) } to_a.each { |o| yield(o) }
self self
end end
def to_a def to_a
(@keys = @hash.keys).sort! unless @keys (@keys = @hash.keys).sort! unless @keys
@keys @keys
end end
} }
end end
@ -610,7 +610,7 @@ class SortedSet < Set
end end
end end
def initialize(*args, &block) # :nodoc: def initialize(*args, &block) # :nodoc:
SortedSet.setup SortedSet.setup
initialize(*args, &block) initialize(*args, &block)
end end
@ -657,54 +657,54 @@ end
# #
# if @proc.arity == 2 # if @proc.arity == 2
# instance_eval %{ # instance_eval %{
# def add(o) # def add(o)
# @hash[o] = true if @proc.call(self, o) # @hash[o] = true if @proc.call(self, o)
# self # self
# end # end
# alias << add # alias << add
# #
# def add?(o) # def add?(o)
# if include?(o) || !@proc.call(self, o) # if include?(o) || !@proc.call(self, o)
# nil # nil
# else # else
# @hash[o] = true # @hash[o] = true
# self # self
# end # end
# end # end
# #
# def replace(enum) # def replace(enum)
# enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable" # enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
# clear # clear
# enum.each_entry { |o| add(o) } # enum.each_entry { |o| add(o) }
# #
# self # self
# end # end
# #
# def merge(enum) # def merge(enum)
# enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable" # enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
# enum.each_entry { |o| add(o) } # enum.each_entry { |o| add(o) }
# #
# self # self
# end # end
# } # }
# else # else
# instance_eval %{ # instance_eval %{
# def add(o) # def add(o)
# if @proc.call(o) # if @proc.call(o)
# @hash[o] = true # @hash[o] = true
# end # end
# self # self
# end # end
# alias << add # alias << add
# #
# def add?(o) # def add?(o)
# if include?(o) || !@proc.call(o) # if include?(o) || !@proc.call(o)
# nil # nil
# else # else
# @hash[o] = true # @hash[o] = true
# self # self
# end # end
# end # end
# } # }
# end # end
# #
@ -838,10 +838,10 @@ class TC_Set < Test::Unit::TestCase
5, 5,
Set[7, Set[7,
Set[0] Set[0]
], ],
Set[6,2], Set[6,2],
1 1
], ],
3, 3,
Set[3,4] Set[3,4]
] ]
@ -1020,8 +1020,8 @@ class TC_Set < Test::Unit::TestCase
assert_nothing_raised { assert_nothing_raised {
set.each { |o| set.each { |o|
ary.delete(o) or raise "unexpected element: #{o}" ary.delete(o) or raise "unexpected element: #{o}"
} }
ary.empty? or raise "forgotten elements: #{ary.join(', ')}" ary.empty? or raise "forgotten elements: #{ary.join(', ')}"
} }
@ -1168,8 +1168,8 @@ class TC_Set < Test::Unit::TestCase
set2 = Set["a", "b", set1] set2 = Set["a", "b", set1]
set1 = set1.add(set1.clone) set1 = set1.add(set1.clone)
# assert_equal(set1, set2) # assert_equal(set1, set2)
# assert_equal(set2, set1) # assert_equal(set2, set1)
assert_equal(set2, set2.clone) assert_equal(set2, set2.clone)
assert_equal(set1.clone, set1) assert_equal(set1.clone, set1)

View File

@ -1,8 +1,8 @@
# #
# shell.rb - # shell.rb -
# $Release Version: 0.7 $ # $Release Version: 0.7 $
# $Revision: 1.9 $ # $Revision: 1.9 $
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #
@ -25,7 +25,7 @@ class Shell
include Error include Error
extend Exception2MessageMapper extend Exception2MessageMapper
# @cascade = true # @cascade = true
# debug: true -> normal debug # debug: true -> normal debug
# debug: 1 -> eval definition debug # debug: 1 -> eval definition debug
# debug: 2 -> detail inspect debug # debug: 2 -> detail inspect debug
@ -41,7 +41,7 @@ class Shell
attr_accessor :cascade, :debug, :verbose attr_accessor :cascade, :debug, :verbose
# alias cascade? cascade # alias cascade? cascade
alias debug? debug alias debug? debug
alias verbose? verbose alias verbose? verbose
@verbose = true @verbose = true
@ -286,7 +286,7 @@ class Shell
yield mes if iterator? yield mes if iterator?
if _head if _head
_head = false _head = false
# "shell" " + mes # "shell" " + mes
prefix + mes prefix + mes
else else
" "* prefix.size + mes " "* prefix.size + mes

View File

@ -1,8 +1,8 @@
# #
# shell/builtin-command.rb - # shell/builtin-command.rb -
# $Release Version: 0.7 $ # $Release Version: 0.7 $
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #
@ -83,19 +83,19 @@ class Shell
end end
end end
# class Sort < Cat # class Sort < Cat
# def initialize(sh, *filenames) # def initialize(sh, *filenames)
# super # super
# end # end
# #
# def each(rs = nil) # def each(rs = nil)
# ary = [] # ary = []
# super{|l| ary.push l} # super{|l| ary.push l}
# for l in ary.sort! # for l in ary.sort!
# yield l # yield l
# end # end
# end # end
# end # end
class AppendIO < BuiltInCommand class AppendIO < BuiltInCommand
def initialize(sh, io, filter) def initialize(sh, io, filter)

View File

@ -1,8 +1,8 @@
# #
# shell/command-controller.rb - # shell/command-controller.rb -
# $Release Version: 0.7 $ # $Release Version: 0.7 $
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #
@ -19,7 +19,7 @@ require "shell/builtin-command"
class Shell class Shell
class CommandProcessor class CommandProcessor
# include Error # include Error
# #
# initialize of Shell and related classes. # initialize of Shell and related classes.
@ -68,9 +68,9 @@ class Shell
# #
# CommandProcessor#expand_path(path) # CommandProcessor#expand_path(path)
# path: String # path: String
# return: String # return: String
# returns the absolute path for <path> # returns the absolute path for <path>
# #
def expand_path(path) def expand_path(path)
@shell.expand_path(path) @shell.expand_path(path)
@ -86,13 +86,13 @@ class Shell
# - # -
# #
# CommandProcessor#foreach(path, rs) # CommandProcessor#foreach(path, rs)
# path: String # path: String
# rs: String - record separator # rs: String - record separator
# iterator # iterator
# Same as: # Same as:
# File#foreach (when path is file) # File#foreach (when path is file)
# Dir#foreach (when path is directory) # Dir#foreach (when path is directory)
# path is relative to pwd # path is relative to pwd
# #
def foreach(path = nil, *rs) def foreach(path = nil, *rs)
path = "." unless path path = "." unless path
@ -107,13 +107,13 @@ class Shell
# #
# CommandProcessor#open(path, mode) # CommandProcessor#open(path, mode)
# path: String # path: String
# mode: String # mode: String
# return: File or Dir # return: File or Dir
# Same as: # Same as:
# File#open (when path is file) # File#open (when path is file)
# Dir#open (when path is directory) # Dir#open (when path is directory)
# mode has an effect only when path is a file # mode has an effect only when path is a file
# #
def open(path, mode = nil, perm = 0666, &b) def open(path, mode = nil, perm = 0666, &b)
path = expand_path(path) path = expand_path(path)
@ -136,9 +136,9 @@ class Shell
# #
# CommandProcessor#unlink(path) # CommandProcessor#unlink(path)
# same as: # same as:
# Dir#unlink (when path is directory) # Dir#unlink (when path is directory)
# File#unlink (when path is file) # File#unlink (when path is file)
# #
def unlink(path) def unlink(path)
@shell.check_point @shell.check_point
@ -155,19 +155,19 @@ class Shell
# #
# CommandProcessor#test(command, file1, file2) # CommandProcessor#test(command, file1, file2)
# CommandProcessor#[command, file1, file2] # CommandProcessor#[command, file1, file2]
# command: char or String or Symbol # command: char or String or Symbol
# file1: String # file1: String
# file2: String(optional) # file2: String(optional)
# return: Boolean # return: Boolean
# same as: # same as:
# test() (when command is char or length 1 string or symbol) # test() (when command is char or length 1 string or symbol)
# FileTest.command (others) # FileTest.command (others)
# example: # example:
# sh[?e, "foo"] # sh[?e, "foo"]
# sh[:e, "foo"] # sh[:e, "foo"]
# sh["e", "foo"] # sh["e", "foo"]
# sh[:exists?, "foo"] # sh[:exists?, "foo"]
# sh["exists?", "foo"] # sh["exists?", "foo"]
# #
alias top_level_test test alias top_level_test test
def test(command, file1, file2=nil) def test(command, file1, file2=nil)
@ -209,8 +209,8 @@ class Shell
#-- #--
# #
# CommandProcessor#mkdir(*path) # CommandProcessor#mkdir(*path)
# path: String # path: String
# same as Dir.mkdir() # same as Dir.mkdir()
# #
def mkdir(*path) def mkdir(*path)
@shell.check_point @shell.check_point
@ -234,8 +234,8 @@ class Shell
# #
# CommandProcessor#rmdir(*path) # CommandProcessor#rmdir(*path)
# path: String # path: String
# same as Dir.rmdir() # same as Dir.rmdir()
# #
def rmdir(*path) def rmdir(*path)
@shell.check_point @shell.check_point
@ -249,13 +249,13 @@ class Shell
# #
# CommandProcessor#system(command, *opts) # CommandProcessor#system(command, *opts)
# command: String # command: String
# opts: String # opts: String
# return: SystemCommand # return: SystemCommand
# Same as system() function # Same as system() function
# example: # example:
# print sh.system("ls", "-l") # print sh.system("ls", "-l")
# sh.system("ls", "-l") | sh.head > STDOUT # sh.system("ls", "-l") | sh.head > STDOUT
# #
def system(command, *opts) def system(command, *opts)
if opts.empty? if opts.empty?
@ -270,7 +270,7 @@ class Shell
# #
# ProcessCommand#rehash # ProcessCommand#rehash
# clear command hash table. # clear command hash table.
# #
def rehash def rehash
@system_commands = {} @system_commands = {}
@ -373,21 +373,21 @@ class Shell
# #
# CommandProcessor.def_system_command(command, path) # CommandProcessor.def_system_command(command, path)
# command: String # command: String
# path: String # path: String
# define 'command()' method as method. # define 'command()' method as method.
# #
def self.def_system_command(command, path = command) def self.def_system_command(command, path = command)
begin begin
eval((d = %Q[def #{command}(*opts) eval((d = %Q[def #{command}(*opts)
SystemCommand.new(@shell, '#{path}', *opts) SystemCommand.new(@shell, '#{path}', *opts)
end]), nil, __FILE__, __LINE__ - 1) end]), nil, __FILE__, __LINE__ - 1)
rescue SyntaxError rescue SyntaxError
Shell.notify "warn: Can't define #{command} path: #{path}." Shell.notify "warn: Can't define #{command} path: #{path}."
end end
Shell.notify "Define #{command} path: #{path}.", Shell.debug? Shell.notify "Define #{command} path: #{path}.", Shell.debug?
Shell.notify("Definition of #{command}: ", d, Shell.notify("Definition of #{command}: ", d,
Shell.debug.kind_of?(Integer) && Shell.debug > 1) Shell.debug.kind_of?(Integer) && Shell.debug > 1)
end end
def self.undef_system_command(command) def self.undef_system_command(command)
@ -417,11 +417,11 @@ class Shell
eval((d = %Q[def #{ali}(*opts) eval((d = %Q[def #{ali}(*opts)
@shell.__send__(:#{command}, @shell.__send__(:#{command},
*(CommandProcessor.alias_map[:#{ali}].call *opts)) *(CommandProcessor.alias_map[:#{ali}].call *opts))
end]), nil, __FILE__, __LINE__ - 1) end]), nil, __FILE__, __LINE__ - 1)
else else
args = opts.collect{|opt| '"' + opt + '"'}.join(",") args = opts.collect{|opt| '"' + opt + '"'}.join(",")
eval((d = %Q[def #{ali}(*opts) eval((d = %Q[def #{ali}(*opts)
@shell.__send__(:#{command}, #{args}, *opts) @shell.__send__(:#{command}, #{args}, *opts)
end]), nil, __FILE__, __LINE__ - 1) end]), nil, __FILE__, __LINE__ - 1)
end end
@ -432,7 +432,7 @@ class Shell
end end
Shell.notify "Define #{ali} command: #{command}.", Shell.debug? Shell.notify "Define #{ali} command: #{command}.", Shell.debug?
Shell.notify("Definition of #{ali}: ", d, Shell.notify("Definition of #{ali}: ", d,
Shell.debug.kind_of?(Integer) && Shell.debug > 1) Shell.debug.kind_of?(Integer) && Shell.debug > 1)
self self
end end
@ -444,14 +444,14 @@ class Shell
# #
# CommandProcessor.def_builtin_commands(delegation_class, command_specs) # CommandProcessor.def_builtin_commands(delegation_class, command_specs)
# delegation_class: Class or Module # delegation_class: Class or Module
# command_specs: [[command_name, [argument,...]],...] # command_specs: [[command_name, [argument,...]],...]
# command_name: String # command_name: String
# arguments: String # arguments: String
# FILENAME?? -> expand_path(filename??) # FILENAME?? -> expand_path(filename??)
# *FILENAME?? -> filename??.collect{|f|expand_path(f)}.join(", ") # *FILENAME?? -> filename??.collect{|f|expand_path(f)}.join(", ")
# define command_name(argument,...) as # define command_name(argument,...) as
# delegation_class.command_name(argument,...) # delegation_class.command_name(argument,...)
# #
def self.def_builtin_commands(delegation_class, command_specs) def self.def_builtin_commands(delegation_class, command_specs)
for meth, args in command_specs for meth, args in command_specs
@ -469,18 +469,18 @@ class Shell
end end
}.join(", ") }.join(", ")
d = %Q[def #{meth}(#{arg_str}) d = %Q[def #{meth}(#{arg_str})
#{delegation_class}.#{meth}(#{call_arg_str}) #{delegation_class}.#{meth}(#{call_arg_str})
end] end]
Shell.notify "Define #{meth}(#{arg_str})", Shell.debug? Shell.notify "Define #{meth}(#{arg_str})", Shell.debug?
Shell.notify("Definition of #{meth}: ", d, Shell.notify("Definition of #{meth}: ", d,
Shell.debug.kind_of?(Integer) && Shell.debug > 1) Shell.debug.kind_of?(Integer) && Shell.debug > 1)
eval d eval d
end end
end end
# #
# CommandProcessor.install_system_commands(pre) # CommandProcessor.install_system_commands(pre)
# pre: String - command name prefix # pre: String - command name prefix
# defines every command which belongs in default_system_path via # defines every command which belongs in default_system_path via
# CommandProcessor.command(). It doesn't define already defined # CommandProcessor.command(). It doesn't define already defined
# methods twice. By default, "pre_" is prefixes to each method # methods twice. By default, "pre_" is prefixes to each method
@ -526,29 +526,29 @@ class Shell
end end
Shell.notify "method added: Shell##{name}.", Shell.debug? Shell.notify "method added: Shell##{name}.", Shell.debug?
Shell.module_eval(%Q[def #{name}(*args, &block) Shell.module_eval(%Q[def #{name}(*args, &block)
begin begin
@command_processor.__send__(:#{name}, *args, &block) @command_processor.__send__(:#{name}, *args, &block)
rescue Exception rescue Exception
$@.delete_if{|s| /:in `__getobj__'$/ =~ s} #` $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
$@.delete_if{|s| /^\\(eval\\):/ =~ s} $@.delete_if{|s| /^\\(eval\\):/ =~ s}
raise raise
end end
end], __FILE__, __LINE__) end], __FILE__, __LINE__)
if Shell::Filter.method_defined?(id) if Shell::Filter.method_defined?(id)
Shell.notify "warn: override definition of Shell::Filter##{name}." Shell.notify "warn: override definition of Shell::Filter##{name}."
Shell.notify "warn: alias Shell##{name} to Shell::Filter##{name}_org." Shell.notify "warn: alias Shell##{name} to Shell::Filter##{name}_org."
Filter.module_eval "alias #{name}_org #{name}" Filter.module_eval "alias #{name}_org #{name}"
end end
Shell.notify "method added: Shell::Filter##{name}.", Shell.debug? Shell.notify "method added: Shell::Filter##{name}.", Shell.debug?
Filter.module_eval(%Q[def #{name}(*args, &block) Filter.module_eval(%Q[def #{name}(*args, &block)
begin begin
self | @shell.__send__(:#{name}, *args, &block) self | @shell.__send__(:#{name}, *args, &block)
rescue Exception rescue Exception
$@.delete_if{|s| /:in `__getobj__'$/ =~ s} #` $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
$@.delete_if{|s| /^\\(eval\\):/ =~ s} $@.delete_if{|s| /^\\(eval\\):/ =~ s}
raise raise
end end
end], __FILE__, __LINE__) end], __FILE__, __LINE__)
end end
@ -557,7 +557,7 @@ class Shell
# #
def self.install_builtin_commands def self.install_builtin_commands
# method related File. # method related File.
# (exclude open/foreach/unlink) # (exclude open/foreach/unlink)
normal_delegation_file_methods = [ normal_delegation_file_methods = [
["atime", ["FILENAME"]], ["atime", ["FILENAME"]],
["basename", ["fn", "*opts"]], ["basename", ["fn", "*opts"]],
@ -580,12 +580,12 @@ class Shell
["truncate", ["FILENAME", "length"]], ["truncate", ["FILENAME", "length"]],
["utime", ["atime", "mtime", "*FILENAMES"]]] ["utime", ["atime", "mtime", "*FILENAMES"]]]
def_builtin_commands(File, normal_delegation_file_methods) def_builtin_commands(File, normal_delegation_file_methods)
alias_method :rm, :delete alias_method :rm, :delete
# method related FileTest # method related FileTest
def_builtin_commands(FileTest, def_builtin_commands(FileTest,
FileTest.singleton_methods(false).collect{|m| [m, ["FILENAME"]]}) FileTest.singleton_methods(false).collect{|m| [m, ["FILENAME"]]})
end end

View File

@ -1,8 +1,8 @@
# #
# shell/error.rb - # shell/error.rb -
# $Release Version: 0.7 $ # $Release Version: 0.7 $
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #

View File

@ -1,8 +1,8 @@
# #
# shell/filter.rb - # shell/filter.rb -
# $Release Version: 0.7 $ # $Release Version: 0.7 $
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #
@ -19,8 +19,8 @@ class Shell
include Enumerable include Enumerable
def initialize(sh) def initialize(sh)
@shell = sh # parent shell @shell = sh # parent shell
@input = nil # input filter @input = nil # input filter
end end
attr_reader :input attr_reader :input

View File

@ -1,8 +1,8 @@
# #
# shell/process-controller.rb - # shell/process-controller.rb -
# $Release Version: 0.7 $ # $Release Version: 0.7 $
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #
@ -157,19 +157,19 @@ class Shell
@waiting_jobs.delete command @waiting_jobs.delete command
else else
command = @waiting_jobs.shift command = @waiting_jobs.shift
# command.notify "job(%id) pre-start.", @shell.debug? # command.notify "job(%id) pre-start.", @shell.debug?
return unless command return unless command
end end
@active_jobs.push command @active_jobs.push command
command.start command.start
# command.notify "job(%id) post-start.", @shell.debug? # command.notify "job(%id) post-start.", @shell.debug?
# start all jobs that input from the job # start all jobs that input from the job
for job in @waiting_jobs.dup for job in @waiting_jobs.dup
start_job(job) if job.input == command start_job(job) if job.input == command
end end
# command.notify "job(%id) post2-start.", @shell.debug? # command.notify "job(%id) post2-start.", @shell.debug?
end end
end end
@ -254,20 +254,20 @@ class Shell
pid = fork { pid = fork {
Thread.list.each do |th| Thread.list.each do |th|
# th.kill unless [Thread.main, Thread.current].include?(th) # th.kill unless [Thread.main, Thread.current].include?(th)
th.kill unless Thread.current == th th.kill unless Thread.current == th
end end
STDIN.reopen(pipe_peer_in) STDIN.reopen(pipe_peer_in)
STDOUT.reopen(pipe_peer_out) STDOUT.reopen(pipe_peer_out)
ObjectSpace.each_object(IO) do |io| ObjectSpace.each_object(IO) do |io|
if ![STDIN, STDOUT, STDERR].include?(io) if ![STDIN, STDOUT, STDERR].include?(io)
io.close unless io.closed? io.close unless io.closed?
end
end end
end
yield yield
} }
end end
pid_cv.signal pid_cv.signal
@ -283,8 +283,8 @@ class Shell
rescue Errno::ECHILD rescue Errno::ECHILD
command.notify "warn: job(%id) was done already waitpid." command.notify "warn: job(%id) was done already waitpid."
_pid = true _pid = true
# rescue # rescue
# STDERR.puts $! # STDERR.puts $!
ensure ensure
command.notify("Job(%id): Wait to finish when Process finished.", @shell.debug?) command.notify("Job(%id): Wait to finish when Process finished.", @shell.debug?)
# when the process ends, wait until the command terminates # when the process ends, wait until the command terminates
@ -296,11 +296,11 @@ class Shell
redo redo
end end
# command.notify "job(%id) pre-pre-finish.", @shell.debug? # command.notify "job(%id) pre-pre-finish.", @shell.debug?
@job_monitor.synchronize do @job_monitor.synchronize do
# command.notify "job(%id) pre-finish.", @shell.debug? # command.notify "job(%id) pre-finish.", @shell.debug?
terminate_job(command) terminate_job(command)
# command.notify "job(%id) pre-finish2.", @shell.debug? # command.notify "job(%id) pre-finish2.", @shell.debug?
@job_condition.signal @job_condition.signal
command.notify "job(%id) finish.", @shell.debug? command.notify "job(%id) finish.", @shell.debug?
end end

View File

@ -1,8 +1,8 @@
# #
# shell/system-command.rb - # shell/system-command.rb -
# $Release Version: 0.7 $ # $Release Version: 0.7 $
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #
@ -141,9 +141,9 @@ class Shell
# ex) # ex)
# if you wish to output: # if you wish to output:
# "shell: job(#{@command}:#{@pid}) close pipe-out." # "shell: job(#{@command}:#{@pid}) close pipe-out."
# then # then
# mes: "job(%id) close pipe-out." # mes: "job(%id) close pipe-out."
# yorn: Boolean(@shell.debug? or @shell.verbose?) # yorn: Boolean(@shell.debug? or @shell.verbose?)
def notify(*opts, &block) def notify(*opts, &block)
@shell.notify(*opts) do |mes| @shell.notify(*opts) do |mes|

View File

@ -1,8 +1,8 @@
# #
# version.rb - shell version definition file # version.rb - shell version definition file
# $Release Version: 0.7$ # $Release Version: 0.7$
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ruby-lang.org) # by Keiju ISHITSUKA(keiju@ruby-lang.org)
# #
# -- # --
# #

View File

@ -1,8 +1,8 @@
# #
# sync.rb - 2 phase lock with counter # sync.rb - 2 phase lock with counter
# $Release Version: 1.0$ # $Release Version: 1.0$
# $Revision$ # $Revision$
# by Keiju ISHITSUKA(keiju@ishitsuka.com) # by Keiju ISHITSUKA(keiju@ishitsuka.com)
# #
# -- # --
# Sync_m, Synchronizer_m # Sync_m, Synchronizer_m
@ -10,8 +10,8 @@
# obj.extend(Sync_m) # obj.extend(Sync_m)
# or # or
# class Foo # class Foo
# include Sync_m # include Sync_m
# : # :
# end # end
# #
# Sync_m#sync_mode # Sync_m#sync_mode
@ -100,12 +100,12 @@ module Sync_m
def sync_extend def sync_extend
unless (defined? locked? and unless (defined? locked? and
defined? shared? and defined? shared? and
defined? exclusive? and defined? exclusive? and
defined? lock and defined? lock and
defined? unlock and defined? unlock and
defined? try_lock and defined? try_lock and
defined? synchronize) defined? synchronize)
Sync_m.define_aliases(singleton_class) Sync_m.define_aliases(singleton_class)
end end
sync_initialize sync_initialize
@ -281,7 +281,7 @@ module Sync_m
end end
when EX when EX
if sync_mode == UN or if sync_mode == UN or
sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current) sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current)
self.sync_mode = m self.sync_mode = m
self.sync_ex_locker = Thread.current self.sync_ex_locker = Thread.current
self.sync_ex_count = 1 self.sync_ex_count = 1

View File

@ -165,7 +165,7 @@ class Tempfile < DelegateClass(File)
__setobj__(@tmpfile) __setobj__(@tmpfile)
end end
def _close # :nodoc: def _close # :nodoc:
@tmpfile.close if @tmpfile @tmpfile.close if @tmpfile
@tmpfile = nil @tmpfile = nil
@data[1] = nil if @data @data[1] = nil if @data

View File

@ -1,6 +1,6 @@
# #
# thread.rb - thread support classes # thread.rb - thread support classes
# by Yukihiro Matsumoto <matz@netlab.co.jp> # by Yukihiro Matsumoto <matz@netlab.co.jp>
# #
# Copyright (C) 2001 Yukihiro Matsumoto # Copyright (C) 2001 Yukihiro Matsumoto
# Copyright (C) 2000 Network Applied Communication Laboratory, Inc. # Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
@ -144,7 +144,7 @@ class Queue
def initialize def initialize
@que = [] @que = []
@waiting = [] @waiting = []
@que.taint # enable tainted comunication @que.taint # enable tainted comunication
@waiting.taint @waiting.taint
self.taint self.taint
@mutex = Mutex.new @mutex = Mutex.new
@ -252,7 +252,7 @@ class SizedQueue < Queue
raise ArgumentError, "queue size must be positive" unless max > 0 raise ArgumentError, "queue size must be positive" unless max > 0
@max = max @max = max
@queue_wait = [] @queue_wait = []
@queue_wait.taint # enable tainted comunication @queue_wait.taint # enable tainted comunication
super() super()
end end

View File

@ -1,8 +1,8 @@
# #
# thwait.rb - thread synchronization class # thwait.rb - thread synchronization class
# $Release Version: 0.9 $ # $Release Version: 0.9 $
# $Revision: 1.3 $ # $Revision: 1.3 $
# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd.) # by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd.)
require "thread.rb" require "thread.rb"
require "e2mmap.rb" require "e2mmap.rb"

View File

@ -69,9 +69,9 @@ end
# #
# ruby -run -e cp -- [OPTION] SOURCE DEST # ruby -run -e cp -- [OPTION] SOURCE DEST
# #
# -p preserve file attributes if possible # -p preserve file attributes if possible
# -r copy recursively # -r copy recursively
# -v verbose # -v verbose
# #
def cp def cp
@ -90,9 +90,9 @@ end
# #
# ruby -run -e ln -- [OPTION] TARGET LINK_NAME # ruby -run -e ln -- [OPTION] TARGET LINK_NAME
# #
# -s make symbolic links instead of hard links # -s make symbolic links instead of hard links
# -f remove existing destination files # -f remove existing destination files
# -v verbose # -v verbose
# #
def ln def ln
@ -111,7 +111,7 @@ end
# #
# ruby -run -e mv -- [OPTION] SOURCE DEST # ruby -run -e mv -- [OPTION] SOURCE DEST
# #
# -v verbose # -v verbose
# #
def mv def mv
@ -127,9 +127,9 @@ end
# #
# ruby -run -e rm -- [OPTION] FILE # ruby -run -e rm -- [OPTION] FILE
# #
# -f ignore nonexistent files # -f ignore nonexistent files
# -r remove the contents of directories recursively # -r remove the contents of directories recursively
# -v verbose # -v verbose
# #
def rm def rm
@ -146,8 +146,8 @@ end
# #
# ruby -run -e mkdir -- [OPTION] DIR # ruby -run -e mkdir -- [OPTION] DIR
# #
# -p no error if existing, make parent directories as needed # -p no error if existing, make parent directories as needed
# -v verbose # -v verbose
# #
def mkdir def mkdir
@ -163,8 +163,8 @@ end
# #
# ruby -run -e rmdir -- [OPTION] DIR # ruby -run -e rmdir -- [OPTION] DIR
# #
# -p remove DIRECTORY and its ancestors. # -p remove DIRECTORY and its ancestors.
# -v verbose # -v verbose
# #
def rmdir def rmdir
@ -179,10 +179,10 @@ end
# #
# ruby -run -e install -- [OPTION] SOURCE DEST # ruby -run -e install -- [OPTION] SOURCE DEST
# #
# -p apply access/modification times of SOURCE files to # -p apply access/modification times of SOURCE files to
# corresponding destination files # corresponding destination files
# -m set permission mode (as in chmod), instead of 0755 # -m set permission mode (as in chmod), instead of 0755
# -v verbose # -v verbose
# #
def install def install
@ -200,7 +200,7 @@ end
# #
# ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE # ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
# #
# -v verbose # -v verbose
# #
def chmod def chmod
@ -215,7 +215,7 @@ end
# #
# ruby -run -e touch -- [OPTION] FILE # ruby -run -e touch -- [OPTION] FILE
# #
# -v verbose # -v verbose
# #
def touch def touch
@ -229,9 +229,9 @@ end
# #
# ruby -run -e wait_writable -- [OPTION] FILE # ruby -run -e wait_writable -- [OPTION] FILE
# #
# -n RETRY count to retry # -n RETRY count to retry
# -w SEC each wait time in seconds # -w SEC each wait time in seconds
# -v verbose # -v verbose
# #
def wait_writable def wait_writable
@ -260,15 +260,15 @@ end
# #
# ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION] # ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]
# #
# -d ARGS run dir_config # -d ARGS run dir_config
# -h ARGS run have_header # -h ARGS run have_header
# -l ARGS run have_library # -l ARGS run have_library
# -f ARGS run have_func # -f ARGS run have_func
# -v ARGS run have_var # -v ARGS run have_var
# -t ARGS run have_type # -t ARGS run have_type
# -m ARGS run have_macro # -m ARGS run have_macro
# -c ARGS run have_const # -c ARGS run have_const
# --vendor install to vendor_ruby # --vendor install to vendor_ruby
# #
def mkmf def mkmf

View File

@ -202,13 +202,13 @@ module URI
# #
# == Usage # == Usage
# #
# p = URI::Parser.new # p = URI::Parser.new
# p.parse("ldap://ldap.example.com/dc=example?user=john") # p.parse("ldap://ldap.example.com/dc=example?user=john")
# #=> #<URI::LDAP:0x00000000b9e7e8 URL:ldap://ldap.example.com/dc=example?user=john> # #=> #<URI::LDAP:0x00000000b9e7e8 URL:ldap://ldap.example.com/dc=example?user=john>
# #
def parse(uri) def parse(uri)
scheme, userinfo, host, port, scheme, userinfo, host, port,
registry, path, opaque, query, fragment = self.split(uri) registry, path, opaque, query, fragment = self.split(uri)
if scheme && URI.scheme_list.include?(scheme.upcase) if scheme && URI.scheme_list.include?(scheme.upcase)
URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port, URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port,
@ -273,7 +273,7 @@ module URI
# unless +schemes+ is provided. Then it is a Regexp.union with self.pattern[:X_ABS_URI] # unless +schemes+ is provided. Then it is a Regexp.union with self.pattern[:X_ABS_URI]
def make_regexp(schemes = nil) def make_regexp(schemes = nil)
unless schemes unless schemes
@regexp[:ABS_URI_REF] @regexp[:ABS_URI_REF]
else else
/(?=#{Regexp.union(*schemes)}:)#{@pattern[:X_ABS_URI]}/x /(?=#{Regexp.union(*schemes)}:)#{@pattern[:X_ABS_URI]}/x
end end

View File

@ -1321,8 +1321,8 @@ module URI
self.query, self.fragment, parser) self.query, self.fragment, parser)
if rel.userinfo != oth.userinfo || if rel.userinfo != oth.userinfo ||
rel.host.to_s.downcase != oth.host.to_s.downcase || rel.host.to_s.downcase != oth.host.to_s.downcase ||
rel.port != oth.port rel.port != oth.port
if self.userinfo.nil? && self.host.nil? if self.userinfo.nil? && self.host.nil?
return self, self.dup return self, self.dup

View File

@ -3,11 +3,11 @@
# Usage: # Usage:
# foo = Object.new # foo = Object.new
# foo = Object.new # foo = Object.new
# p foo.to_s # original's class # p foo.to_s # original's class
# foo = WeakRef.new(foo) # foo = WeakRef.new(foo)
# p foo.to_s # should be same class # p foo.to_s # should be same class
# ObjectSpace.garbage_collect # ObjectSpace.garbage_collect
# p foo.to_s # should raise exception (recycled) # p foo.to_s # should raise exception (recycled)
require "delegate" require "delegate"
require 'thread' require 'thread'
@ -71,10 +71,10 @@ end
if __FILE__ == $0 if __FILE__ == $0
# require 'thread' # require 'thread'
foo = Object.new foo = Object.new
p foo.to_s # original's class p foo.to_s # original's class
foo = WeakRef.new(foo) foo = WeakRef.new(foo)
p foo.to_s # should be same class p foo.to_s # should be same class
ObjectSpace.garbage_collect ObjectSpace.garbage_collect
ObjectSpace.garbage_collect ObjectSpace.garbage_collect
p foo.to_s # should raise exception (recycled) p foo.to_s # should raise exception (recycled)
end end