Class: Fuzzer

Inherits:
Object show all
Defined in:
lib/crazy_ivan/vendor/json-1.1.7/tools/fuzz.rb

Instance Method Summary collapse

Constructor Details

#initialize(n, freqs = {}) ⇒ Fuzzer

Returns a new instance of Fuzzer.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/crazy_ivan/vendor/json-1.1.7/tools/fuzz.rb', line 12

def initialize(n, freqs = {})
  sum = freqs.inject(0.0) { |s, x| s + x.last }
  freqs.each_key { |x| freqs[x] /= sum }
  s = 0.0
  freqs.each_key do |x|
    freqs[x] = s .. (s + t = freqs[x])
    s += t
  end
  @freqs = freqs
  @n = n
  @alpha = (0..0xff).to_a
end

Instance Method Details

#fuzz(current = nil) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/crazy_ivan/vendor/json-1.1.7/tools/fuzz.rb', line 53

def fuzz(current = nil)
  if @n > 0
    case current
    when nil
      @n -= 1
      current = fuzz [ Hash, Array ][rand(2)].new
    when Array
      while @n > 0
        @n -= 1
        current << case p = make_pick
        when Array, Hash
          fuzz(p)
        else
          p
        end
      end
    when Hash
      while @n > 0
        @n -= 1
        current[random_string] = case p = make_pick
        when Array, Hash
          fuzz(p)
        else
          p
        end
      end
    end
  end
  current
end

#make_pickObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/crazy_ivan/vendor/json-1.1.7/tools/fuzz.rb', line 37

def make_pick
  k = pick
  case
  when k == Hash, k == Array
    k.new
  when k == true, k == false, k == nil
    k
  when k == String
    random_string
  when k == Fixnum
    rand(2 ** 30) - 2 ** 29
  when k == Bignum
    rand(2 ** 70) - 2 ** 69
  end
end

#pickObject



31
32
33
34
35
# File 'lib/crazy_ivan/vendor/json-1.1.7/tools/fuzz.rb', line 31

def pick
  r = rand
  found = @freqs.find { |k, f| f.include? rand }
  found && found.first
end

#random_stringObject



25
26
27
28
29
# File 'lib/crazy_ivan/vendor/json-1.1.7/tools/fuzz.rb', line 25

def random_string
  s = ''
  30.times { s << @alpha[rand(@alpha.size)] }
  s.to_utf8
end