Blob of strokedb-ruby/lib/util/class_optimization.rb (raw blob data)

1 module StrokeDB
2 class ::Class
3 # Declare which methods are optimized for particular language.
4 # It is assumed, that optimized method name looks that way:
5 # <tt>method_name_(language name)</tt>
6 #
7 # If you supply a block of code, it will be executed in a context of a class
8 # each time <tt>optimize!</tt> is called.
9 #
10 # You may add some exception handling where you call <tt>optimize!</tt>.
11 #
12 # Example:
13 #
14 # # assume, there're methods find_C and insert_C
15 # declare_optimized_methods(:C, :find, :insert) { require 'bundle' }</tt>
16 #
17 def declare_optimized_methods(lang, *meths, &block)
18 meths.flatten!
19 @optimized_methods ||= {}
20 @optimized_methods_init ||= {}
21 @optimized_methods[lang.to_s] = meths
22 @optimized_methods_init[lang.to_s] = block
23 extend ClassOptimization::ClassMethods
24 end
25
26 # Returns a list of optimized methods for a given language.
27 # If no language given, a Hash is returned where key is a language name.
28 #
29 def optimized_methods(lang = nil)
30 @optimized_methods ||= {}
31 return @optimized_methods unless lang
32 @optimized_methods[lang.to_s] || []
33 end
34 end
35 module ClassOptimization
36 module ClassMethods
37 # Switches methods into optimized versions as declared in
38 # <tt>declare_optimized_methods</tt>.
39 # Pure ruby methods become accessible with suffix _PureRuby.
40 #
41 def optimize!(lang)
42 if block = @optimized_methods_init[lang.to_s]
43 self.instance_eval(&block)
44 end
45 optimized_methods(lang).each do |meth|
46 alias_method(:"#{meth}_PureRuby", :"#{meth}")
47 alias_method(:"#{meth}", :"#{meth}_#{lang}")
48 end
49 end
50
51 # Reverts method optimization done with <tt>optimize!</tt>
52 # Note: you may call this method only after optimize! was called.
53 #
54 def deoptimize!(lang)
55 optimized_methods(lang).each do |meth|
56 alias_method(:"#{meth}", :"#{meth}_PureRuby")
57 end
58 end
59
60 # Executes code in a block with optimizations turned on.
61 # This ensures that appropriate <tt>deoptimize!</tt> method is called.
62 #
63 def optimized_with(lang)
64 optimize!(lang)
65 yield
66 ensure
67 deoptimize!(lang)
68 end
69
70 # Iterates through all the optimizations. Non-optimized
71 # mode ("pure Ruby") is yielded first.
72 # Useful for testing and benchmarks.
73 #
74 # Example:
75 #
76 # Klass.with_optimizations(:InlineC) do |lang|
77 # puts "Klass#some_method is written in #{lang}"
78 # puts Klass.new.some_method
79 # end
80 #
81 def with_optimizations(*langs)
82 langs.flatten!
83 yield("pure Ruby")
84 langs.each do |lang|
85 optimized_with(lang) do
86 yield(lang)
87 end
88 end
89 self
90 end
91 end
92 end
93 end