This repository has been archived by the owner on May 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
vdf.rb
131 lines (111 loc) · 2.16 KB
/
vdf.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
require 'strscan'
class VDF
attr_reader :scanner
def initialize(string)
@scanner = StringScanner.new(string)
end
def translate
parse
end
def parse
until scanner.eos?
@oldpos = scanner.pos
if comment || ignorable
elsif hash_head
return scanner[1] => kvs
else scan(/./m)
# p any: s.matched
end
if @oldpos == scanner.pos
raise scanner.inspect
end
end
rescue => ex
puts ex, *ex.backtrace
p @scanner
end
def ignorable
while space || comment
end
end
def comment
scan(/\s*\/.*/)
end
def space
scan(/\s+/m)
end
def string
if scan(/""/)
""
else scan(/"((\\"|[^"])+)"/)
scanner[1]
end
end
def hash_head
scan(/"([^"]*)"(\s|\s*\/[^\r\n]+)*\{/m)
end
def hash_tail
space
scan(/\}/)
end
def kv_pair
[string, space, string]
end
def kvs
hash = {}
until hash_tail || scanner.eos?
@oldpos = scanner.pos
ignorable
if hash_head
key = scanner[1]
value = kvs
hash[key] = value
ignorable
elsif key = string
ignorable
if value = string
hash[key] = value
else
raise "expected value"
end
elsif hash_tail
# nothing to do here
else
raise "expected key"
end
ignorable
if @oldpos == scanner.pos
raise scanner.inspect
end
end
kvs_transmute hash
end
def scan(*a)
scanner.scan(*a)
end
def kvs_transmute(hash)
if var_type = hash.delete('var_type')
key, value = hash.first
case var_type
when 'FIELD_INTEGER'
if value =~ /\s/
hash = {key => value.split.map{|i| i.to_i }}
else
hash = {key => value.to_i}
end
when 'FIELD_FLOAT'
if value =~ /\s/
hash = {key => value.scan(/[\d.]+/).map{|i| Float(i) }}
else
hash = {key => Float(value[/[\d.]+/])}
end
else
raise var_type
end
elsif hash.keys.all?{|k| k =~ /^\s*\d+\s*$/ }
hash.sort_by{|k,v| k.to_i }.map{|k,v| v }
else
hash
end
end
end