jdogo 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/jdogo/text.rb ADDED
@@ -0,0 +1,281 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JDogo
4
+ # Text rules shared by the encoders. Column choices count UTF-16 code units and classify one unit at
5
+ # a time, as Java and TypeScript strings do (spec 2.3 rule 2.5): a character outside the Basic
6
+ # Multilingual Plane is two units, neither of them a letter, digit or space.
7
+ #
8
+ # @api private
9
+ module Text
10
+ module_function
11
+
12
+ UTF8 = Encoding::UTF_8
13
+ REPLACEMENT = "\uFFFD"
14
+
15
+ # valid_text returns s as valid UTF-8: invalid bytes become U+FFFD, as the other SDKs do, since
16
+ # JDogo text is UTF-8 (spec 2.1 section 4). A valid UTF-8 string is returned as it is.
17
+ def valid_text(s)
18
+ enc = s.encoding
19
+ if enc == UTF8
20
+ return s if s.valid_encoding?
21
+
22
+ return s.scrub(REPLACEMENT)
23
+ end
24
+ if enc == Encoding::BINARY || enc == Encoding::US_ASCII
25
+ t = s.dup.force_encoding(UTF8)
26
+ return t.valid_encoding? ? t : t.scrub(REPLACEMENT)
27
+ end
28
+ s.encode(UTF8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
29
+ end
30
+
31
+ # len16 is the length of s in UTF-16 code units.
32
+ def len16(s)
33
+ return s.bytesize if s.ascii_only?
34
+
35
+ s.length + s.b.count(ASTRAL_LEADS) # a 4-byte UTF-8 sequence is two UTF-16 units
36
+ end
37
+
38
+ ASTRAL_LEADS = "\xF0-\xF4".b.freeze
39
+
40
+ # units returns the UTF-16 code units of s.
41
+ def units(s)
42
+ return s.bytes if s.ascii_only?
43
+
44
+ s.encode(Encoding::UTF_16LE).unpack("v*")
45
+ end
46
+
47
+ # from_units turns UTF-16 code units back into a UTF-8 string.
48
+ def from_units(us)
49
+ return us.pack("C*").force_encoding(UTF8) if us.all? { |u| u < 0x80 }
50
+
51
+ us.pack("v*").force_encoding(Encoding::UTF_16LE)
52
+ .encode(UTF8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
53
+ end
54
+
55
+ # ---------------------------------------------------------------- character classes
56
+
57
+ LETTER = 1
58
+ DIGIT = 2
59
+ SPACE = 4
60
+ LETTER_RE = /\A\p{L}\z/
61
+ DIGIT_RE = /\A\p{Nd}\z/
62
+ SPACE_RE = /\A[\p{Zs}\p{Zl}\p{Zp}]\z/
63
+ CLASSES = Array.new(0x10000)
64
+
65
+ def compute_class(u)
66
+ return 0 if u >= 0xD800 && u <= 0xDFFF
67
+
68
+ ch = u.chr(UTF8)
69
+ m = 0
70
+ m |= LETTER if LETTER_RE.match?(ch)
71
+ m |= DIGIT if DIGIT_RE.match?(ch)
72
+ case u
73
+ when 0x09..0x0D, 0x1C..0x1F then m |= SPACE
74
+ when 0x00A0, 0x2007, 0x202F then nil # non-breaking spaces are not whitespace in Java
75
+ else m |= SPACE if SPACE_RE.match?(ch)
76
+ end
77
+ m
78
+ end
79
+
80
+ # char_class: Java's Character.isLetter (1), isDigit (2) and isWhitespace (4) for one UTF-16 unit,
81
+ # as a bit mask. A code point outside the BMP is none of them.
82
+ def char_class(u)
83
+ return 0 if u > 0xFFFF
84
+
85
+ CLASSES[u] || (CLASSES[u] = compute_class(u))
86
+ end
87
+
88
+ (0..0x7F).each { |u| CLASSES[u] = compute_class(u) }
89
+
90
+ def letter?(u) = char_class(u).anybits?(LETTER)
91
+ def digit?(u) = char_class(u).anybits?(DIGIT)
92
+ def letter_or_digit?(u) = char_class(u).anybits?(LETTER | DIGIT)
93
+
94
+ # ---------------------------------------------------------------- quoting
95
+
96
+ RAW_UNSAFE = /[,\[\]{}"\\;\x00-\x1f]/
97
+ RAW_UNSAFE_WRAP = /[,\[\]{}"\\;()\x00-\x1f]/
98
+ AFFIX_UNSAFE = /[,\[\]{}"\\;+$^\x00-\x1f]/
99
+ KEY_UNSAFE = /[,\[\]{}()"\\;=:@?+^$\x00-\x1f]/
100
+ NUMERIC = /\A-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?\z/
101
+ SPECIAL_TOKENS = %w[~ ^ true false null].freeze
102
+
103
+ # edge_space?: a leading or trailing space or tab, which readers would drop around bare text.
104
+ def edge_space?(s)
105
+ a = s.getbyte(0)
106
+ b = s.getbyte(s.bytesize - 1)
107
+ a == 32 || a == 9 || b == 32 || b == 9
108
+ end
109
+
110
+ # needs_quote_raw?: whether a dictionary entry, affix or row key must be quoted. An affix (prefix
111
+ # true) with '+', '$' or '^' is quoted too, since the header reads a prefix up to '$' and a suffix
112
+ # up to '^'.
113
+ def needs_quote_raw?(s, in_wrap, prefix: false)
114
+ return true if s.empty? || edge_space?(s)
115
+
116
+ re = if prefix
117
+ AFFIX_UNSAFE
118
+ else
119
+ (in_wrap ? RAW_UNSAFE_WRAP : RAW_UNSAFE)
120
+ end
121
+ re.match?(s)
122
+ end
123
+
124
+ # needs_quote_value?: whether a string value must be quoted so it reads back as the same string.
125
+ def needs_quote_value?(s, in_wrap, top)
126
+ return true if s.empty? || edge_space?(s)
127
+ # '@' starts a document; spec 2.3.1 rule 7.3: readers drop a leading U+FEFF and take '!JDOGO/' for typed JDogo
128
+ return true if top && (s.getbyte(0) == 64 || s.start_with?("\uFEFF", "!JDOGO/"))
129
+ return true if (in_wrap ? RAW_UNSAFE_WRAP : RAW_UNSAFE).match?(s)
130
+ return true if SPECIAL_TOKENS.include?(s)
131
+
132
+ looks_numeric?(s)
133
+ end
134
+
135
+ # looks_numeric?: '-'?, ASCII digits, optional '.digits', at least one digit, optional exponent
136
+ # (Java DocEscaper.looksNumeric). '.5' and '007' are numbers.
137
+ def looks_numeric?(s) = NUMERIC.match?(s)
138
+
139
+ QUOTE_RE = /["\\\x00-\x1f]/
140
+ QUOTE_MAP = (0..0x1f).to_h { |c| [c.chr, format("\\u%04x", c)] }.merge(
141
+ '"' => '\\"', "\\" => "\\\\", "\n" => "\\n", "\r" => "\\r", "\t" => "\\t", "\b" => "\\b", "\f" => "\\f"
142
+ ).freeze
143
+
144
+ # quote writes s as a JSON string literal: '\b' and '\f' by name, other control characters as
145
+ # lowercase '\u00xx', everything else as it is (spec 2.3 rule 1.4).
146
+ def quote(s)
147
+ return "\"#{s}\"" unless QUOTE_RE.match?(s)
148
+
149
+ "\"#{s.gsub(QUOTE_RE, QUOTE_MAP)}\""
150
+ end
151
+
152
+ def write_raw_string(s, in_wrap) = needs_quote_raw?(s, in_wrap) ? quote(s) : s
153
+ def write_string(s, in_wrap, top) = needs_quote_value?(s, in_wrap, top) ? quote(s) : s
154
+ def write_affix(s) = needs_quote_raw?(s, false, prefix: true) ? quote(s) : s
155
+
156
+ def write_key(k)
157
+ return quote(k) if k.empty? || edge_space?(k) || KEY_UNSAFE.match?(k)
158
+
159
+ k
160
+ end
161
+
162
+ # ---------------------------------------------------------------- token estimate
163
+
164
+ # token_estimate is the Java codec's calibrated token estimate over UTF-16 units: a run of ASCII
165
+ # digits costs 1 per 3, a run of letters 1 per 4 (at least 1), whitespace nothing, any other unit 1;
166
+ # a non-empty value costs at least 1 in all.
167
+ def token_estimate(s)
168
+ return 0 if s.empty?
169
+
170
+ cps = s.codepoints
171
+ n = cps.size
172
+ tokens = 0
173
+ i = 0
174
+ while i < n
175
+ c = cps[i]
176
+ if c >= 48 && c <= 57
177
+ j = i + 1
178
+ j += 1 while j < n && cps[j] >= 48 && cps[j] <= 57
179
+ tokens += (j - i + 2) / 3
180
+ i = j
181
+ elsif c > 0xFFFF # two surrogate units: two symbols
182
+ tokens += 2
183
+ i += 1
184
+ else
185
+ cl = char_class(c)
186
+ if cl.anybits?(LETTER)
187
+ j = i + 1
188
+ j += 1 while j < n && char_class(cps[j]).anybits?(LETTER)
189
+ run = (j - i + 2) / 4
190
+ tokens += run < 1 ? 1 : run
191
+ i = j
192
+ else
193
+ tokens += 1 unless cl.anybits?(SPACE)
194
+ i += 1
195
+ end
196
+ end
197
+ end
198
+ tokens < 1 ? 1 : tokens # as Java: a non-empty value costs at least one token (a lone space too)
199
+ end
200
+
201
+ # ---------------------------------------------------------------- affixes
202
+
203
+ BOUNDARY = "_-:/.@#".bytes.freeze
204
+
205
+ def boundary?(u) = u < 0x80 && BOUNDARY.include?(u)
206
+
207
+ # snap_prefix is the Java codec's snapPrefix: the common prefix of every value, cut after its last
208
+ # separator, or after a letter that every value follows with a digit ('ORD-' in 'ORD-1', 'v' in
209
+ # 'v12').
210
+ def snap_prefix(strs)
211
+ return "" if strs.empty?
212
+
213
+ us = strs.map { |s| units(s) }
214
+ lcp = us[0]
215
+ us.drop(1).each do |s|
216
+ k = 0
217
+ m = [lcp.size, s.size].min
218
+ k += 1 while k < m && lcp[k] == s[k]
219
+ return "" if k.zero?
220
+
221
+ lcp = lcp[0, k]
222
+ end
223
+ best = 0
224
+ lcp.each_with_index do |c, i|
225
+ if boundary?(c)
226
+ best = i + 1
227
+ elsif letter?(c) && us.all? { |s| s.size > i + 1 && digit?(s[i + 1]) }
228
+ best = i + 1
229
+ end
230
+ end
231
+ best -= 1 if best.positive? && lcp[best - 1] >= 0xD800 && lcp[best - 1] <= 0xDBFF # never split a pair
232
+ from_units(lcp[0, best])
233
+ end
234
+
235
+ # snap_suffix is the Java codec's snapSuffix: the longest common suffix after the prefix, cut so that
236
+ # it starts at a separator ('@company.internal', '/END'), never inside a word or number. pfx_len is
237
+ # in UTF-16 units.
238
+ def snap_suffix(strs, pfx_len)
239
+ return "" if strs.empty?
240
+
241
+ first = units(strs[0])
242
+ return "" if first.size <= pfx_len
243
+
244
+ s0 = first[pfx_len..]
245
+ common = s0.size
246
+ strs.drop(1).each do |v|
247
+ u = units(v)
248
+ return "" if u.size <= pfx_len
249
+
250
+ cur = u[pfx_len..]
251
+ k = 0
252
+ m = [common, cur.size].min
253
+ k += 1 while k < m && s0[s0.size - 1 - k] == cur[cur.size - 1 - k]
254
+ common = k
255
+ return "" if common.zero?
256
+ end
257
+ tail = s0[(s0.size - common)..]
258
+ tail.each_with_index { |c, i| return from_units(tail[i..]) if boundary?(c) }
259
+ ""
260
+ end
261
+
262
+ # strip_affix removes a prefix and suffix (counted in UTF-16 units) from s; nil when they overlap.
263
+ def strip_affix(s, pfx, sfx)
264
+ if s.ascii_only? && pfx.ascii_only? && sfx.ascii_only?
265
+ len = s.bytesize - pfx.bytesize - sfx.bytesize
266
+ return len.negative? ? nil : s.byteslice(pfx.bytesize, len)
267
+ end
268
+ u = units(s)
269
+ start = len16(pfx)
270
+ stop = u.size - len16(sfx)
271
+ return nil if start > stop
272
+
273
+ from_units(u[start...stop])
274
+ end
275
+
276
+ # middle: s without a prefix and suffix that it is known to have (byte lengths, as Go slices).
277
+ def middle(s, pfx, sfx)
278
+ s.byteslice(pfx.bytesize, s.bytesize - pfx.bytesize - sfx.bytesize)
279
+ end
280
+ end
281
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JDogo
4
+ # Time columns (spec 2.2, '+t' and '+t3'): canonical UTC timestamps stored as differences in seconds
5
+ # or milliseconds. Integer calendar arithmetic (proleptic Gregorian, UTC), identical in every SDK, so a
6
+ # timestamp always comes back as the exact same string.
7
+ #
8
+ # @api private
9
+ module TimeColumn
10
+ module_function
11
+
12
+ SECONDS = 0 # '+t': YYYY-MM-DDTHH:MM:SSZ
13
+ MILLIS = 3 # '+t3': YYYY-MM-DDTHH:MM:SS.sssZ
14
+ DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze
15
+ SHAPE = /\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z\z/
16
+
17
+ # Ruby's Integer division already rounds down, as these formulas need.
18
+ def days_from_civil(y, m, d)
19
+ y -= 1 if m <= 2
20
+ era = y / 400
21
+ yoe = y - (era * 400)
22
+ mp = m > 2 ? m - 3 : m + 9
23
+ doy = (((153 * mp) + 2) / 5) + d - 1
24
+ doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy
25
+ (era * 146_097) + doe - 719_468
26
+ end
27
+
28
+ def civil_from_days(z)
29
+ z += 719_468
30
+ era = z / 146_097
31
+ doe = z - (era * 146_097)
32
+ yoe = (doe - (doe / 1460) + (doe / 36_524) - (doe / 146_096)) / 365
33
+ doy = doe - ((365 * yoe) + (yoe / 4) - (yoe / 100))
34
+ mp = ((5 * doy) + 2) / 153
35
+ d = doy - (((153 * mp) + 2) / 5) + 1
36
+ m = mp < 10 ? mp + 3 : mp - 9
37
+ y = yoe + (era * 400)
38
+ y += 1 if m <= 2
39
+ [y, m, d]
40
+ end
41
+
42
+ MIN_SECONDS = days_from_civil(1, 1, 1) * 86_400
43
+ MAX_SECONDS = (days_from_civil(9999, 12, 31) * 86_400) + 86_399
44
+
45
+ # parse reads a canonical UTC timestamp: [unit, value] with seconds since 1970 for
46
+ # 'YYYY-MM-DDTHH:MM:SSZ' (unit 0) or milliseconds for 'YYYY-MM-DDTHH:MM:SS.sssZ' (unit 3); nil for
47
+ # anything else, including dates that do not exist, leap seconds and the year 0000.
48
+ def parse(s)
49
+ return nil unless s.bytesize == 20 || s.bytesize == 24
50
+
51
+ md = SHAPE.match(s)
52
+ return nil unless md
53
+
54
+ y, mo, d, h, mi, sec = (1..6).map { |i| md[i].to_i }
55
+ return nil if y < 1 || mo < 1 || mo > 12 || h > 23 || mi > 59 || sec > 59
56
+
57
+ dim = DAYS_IN_MONTH[mo - 1]
58
+ dim = 29 if mo == 2 && (y % 4).zero? && (y % 100 != 0 || (y % 400).zero?)
59
+ return nil if d < 1 || d > dim
60
+
61
+ seconds = (days_from_civil(y, mo, d) * 86_400) + (h * 3600) + (mi * 60) + sec
62
+ md[7] ? [MILLIS, (seconds * 1000) + md[7].to_i] : [SECONDS, seconds]
63
+ end
64
+
65
+ # format writes a '+t' (unit 0) or '+t3' (unit 3) value back as its canonical string; nil outside
66
+ # the years 0001 to 9999.
67
+ def format(unit, value)
68
+ seconds = value
69
+ millis = 0
70
+ seconds, millis = value.divmod(1000) if unit == MILLIS
71
+ return nil if seconds < MIN_SECONDS || seconds > MAX_SECONDS
72
+
73
+ days, rem = seconds.divmod(86_400)
74
+ y, m, d = civil_from_days(days)
75
+ out = Kernel.format("%04d-%02d-%02dT%02d:%02d:%02d", y, m, d, rem / 3600, rem / 60 % 60, rem % 60)
76
+ unit == MILLIS ? "#{out}.#{Kernel.format('%03d', millis)}Z" : "#{out}Z"
77
+ end
78
+
79
+ # column returns [unit, values] when every value is a canonical timestamp of the same precision.
80
+ def column(vals)
81
+ return nil if vals.empty?
82
+
83
+ unit = nil
84
+ values = vals.map do |v|
85
+ return nil unless v.is_a?(String)
86
+
87
+ u, t = parse(v)
88
+ return nil if u.nil? || (unit && u != unit)
89
+
90
+ unit = u
91
+ t
92
+ end
93
+ [unit, values]
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,321 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+
5
+ module JDogo
6
+ # Base class of every error this library raises.
7
+ class Error < StandardError; end
8
+
9
+ # Raised for text that is not a valid JDogo document (or JSON text that is not valid JSON).
10
+ class ParseError < Error
11
+ # Byte offset in the text, after a byte-order mark and trailing line endings are removed.
12
+ attr_reader :offset
13
+
14
+ def initialize(offset, msg)
15
+ @offset = offset
16
+ super("Invalid JDogo document at offset #{offset}: #{msg}")
17
+ end
18
+ end
19
+
20
+ # Raised when a document nests deeper or holds more items than the reader allows, or a value to
21
+ # encode nests deeper than any reader would accept.
22
+ class LimitError < Error; end
23
+
24
+ # Raised for a value the encoders cannot write (an object with neither as_json nor to_h).
25
+ class EncodeError < Error; end
26
+
27
+ # The value model and its JSON bridge.
28
+ #
29
+ # nil null
30
+ # true, false booleans
31
+ # String text (UTF-8)
32
+ # Integer an integer of any size, kept exactly
33
+ # Float any other number
34
+ # Array a list
35
+ # Hash an object with String keys, in order
36
+ #
37
+ # @api private
38
+ module Value
39
+ module_function
40
+
41
+ # Bounds parse_json and generate_json; the encoders apply MAX_DEPTH.
42
+ MAX_JSON_DEPTH = 1000
43
+
44
+ # normalize converts an encoder input to the value model. It returns the input itself when it
45
+ # already is one, and a converted copy otherwise: Symbols become Strings, Hash keys Strings, objects
46
+ # with as_json or to_h their result, invalid UTF-8 is replaced.
47
+ def normalize(v, depth = 0, limit = MAX_DEPTH)
48
+ case v
49
+ when String then Text.valid_text(v)
50
+ when nil, true, false, Integer, Float then v
51
+ when Array then normalize_array(v, depth, limit)
52
+ when Hash then normalize_hash(v, depth, limit)
53
+ when Symbol then Text.valid_text(v.to_s)
54
+ when Numeric
55
+ begin
56
+ Float(v)
57
+ rescue StandardError => e
58
+ raise EncodeError, "cannot encode #{v.class}: #{e.message}"
59
+ end
60
+ else
61
+ if v.respond_to?(:as_json)
62
+ normalize(v.as_json, depth, limit)
63
+ elsif v.respond_to?(:to_h)
64
+ normalize(v.to_h, depth, limit)
65
+ else
66
+ raise EncodeError, "cannot encode #{v.class}"
67
+ end
68
+ end
69
+ end
70
+
71
+ def check_depth(depth, limit)
72
+ # the encoders never write text that a reader would reject
73
+ raise LimitError, "Maximum recursion depth exceeded: #{depth + 1} > #{limit}" if depth >= limit
74
+ end
75
+
76
+ def normalize_array(v, depth, limit)
77
+ check_depth(depth, limit)
78
+ out = v
79
+ v.each_with_index do |e, i|
80
+ n = normalize(e, depth + 1, limit)
81
+ next if n.equal?(e)
82
+
83
+ out = v.dup if out.equal?(v)
84
+ out[i] = n
85
+ end
86
+ out.instance_of?(Array) ? out : Array.new(out)
87
+ end
88
+
89
+ def normalize_hash(v, depth, limit)
90
+ check_depth(depth, limit)
91
+ out = nil
92
+ index = 0
93
+ v.each_pair do |k, x|
94
+ nk = k.is_a?(String) ? Text.valid_text(k) : Text.valid_text(k.to_s)
95
+ nx = normalize(x, depth + 1, limit)
96
+ if out
97
+ out[nk] = nx
98
+ elsif !nk.equal?(k) || !nx.equal?(x)
99
+ out = {}
100
+ v.each_pair.with_index do |(k2, x2), j|
101
+ break if j == index
102
+
103
+ out[k2] = x2
104
+ end
105
+ out[nk] = nx
106
+ end
107
+ index += 1
108
+ end
109
+ out ||= v
110
+ out.instance_of?(Hash) && !out.compare_by_identity? ? out : {}.merge!(out)
111
+ end
112
+
113
+ # ---------------------------------------------------------------- JSON bridge
114
+
115
+ # parse_json reads JSON text into the value model: object keys in order, integers of any size kept
116
+ # exactly, other numbers as Float. A lone surrogate escape becomes U+FFFD.
117
+ def parse_json(text, max_depth: MAX_JSON_DEPTH)
118
+ JsonReader.new(Text.valid_text(text), max_depth).read
119
+ end
120
+
121
+ # generate_json writes a value as compact JSON, object keys in order. NaN and infinities are written
122
+ # as null, as JSON.stringify writes them.
123
+ def generate_json(v)
124
+ out = +""
125
+ write_json(out, normalize(v, 0, MAX_JSON_DEPTH))
126
+ out
127
+ end
128
+
129
+ JSON_ESCAPE_RE = /["\\\x00-\x1f]/
130
+
131
+ def json_string(s)
132
+ return "\"#{s}\"" unless JSON_ESCAPE_RE.match?(s)
133
+
134
+ "\"#{s.gsub(JSON_ESCAPE_RE, Text::QUOTE_MAP)}\""
135
+ end
136
+
137
+ def write_json(out, v)
138
+ case v
139
+ when nil then out << "null"
140
+ when true then out << "true"
141
+ when false then out << "false"
142
+ when String then out << json_string(v)
143
+ when Integer then out << v.to_s
144
+ when Float then out << (v.nan? || v.infinite? ? "null" : Num.es_number(v))
145
+ when Array
146
+ out << "["
147
+ v.each_with_index do |e, i|
148
+ out << "," if i.positive?
149
+ write_json(out, e)
150
+ end
151
+ out << "]"
152
+ when Hash
153
+ out << "{"
154
+ first = true
155
+ v.each_pair do |k, x|
156
+ out << "," unless first
157
+ first = false
158
+ out << json_string(k) << ":"
159
+ write_json(out, x)
160
+ end
161
+ out << "}"
162
+ end
163
+ end
164
+
165
+ # A strict JSON reader (RFC 8259) that keeps key order and exact integers.
166
+ class JsonReader
167
+ WS = /[ \t\n\r]*/
168
+ NUMBER = /-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/
169
+ PLAIN = /[^"\\\x00-\x1f]*/
170
+ ESCAPES = { '"' => '"', "\\" => "\\", "/" => "/", "b" => "\b", "f" => "\f", "n" => "\n", "r" => "\r",
171
+ "t" => "\t" }.freeze
172
+
173
+ def initialize(text, max_depth)
174
+ @ss = StringScanner.new(text)
175
+ @max_depth = max_depth
176
+ end
177
+
178
+ def read
179
+ v = value(0)
180
+ @ss.skip(WS)
181
+ fail!("unexpected data after the JSON value") unless @ss.eos?
182
+ v
183
+ end
184
+
185
+ private
186
+
187
+ def fail!(msg) = raise(ParseError.new(@ss.pos, msg))
188
+
189
+ def value(depth)
190
+ fail!("JSON nested deeper than #{@max_depth} levels") if depth > @max_depth
191
+ @ss.skip(WS)
192
+ case @ss.peek(1)
193
+ when "{" then object(depth)
194
+ when "[" then array(depth)
195
+ when '"' then string
196
+ when "t" then literal("true", true)
197
+ when "f" then literal("false", false)
198
+ when "n" then literal("null", nil)
199
+ else number
200
+ end
201
+ end
202
+
203
+ def literal(word, v)
204
+ fail!("invalid literal") unless @ss.skip(word)
205
+ v
206
+ end
207
+
208
+ def number
209
+ tok = @ss.scan(NUMBER) or fail!("unexpected character")
210
+ return Integer(tok, 10) unless @ss[1] || @ss[2]
211
+
212
+ Num.parse_float(tok) or fail!("number out of range: #{tok[0, 40]}")
213
+ end
214
+
215
+ def array(depth)
216
+ @ss.pos += 1
217
+ out = []
218
+ @ss.skip(WS)
219
+ return out if @ss.skip(/\]/)
220
+
221
+ loop do
222
+ out << value(depth + 1)
223
+ @ss.skip(WS)
224
+ next if @ss.skip(/,/)
225
+ return out if @ss.skip(/\]/)
226
+
227
+ fail!("expected ',' or ']'")
228
+ end
229
+ end
230
+
231
+ def object(depth)
232
+ @ss.pos += 1
233
+ out = {}
234
+ @ss.skip(WS)
235
+ return out if @ss.skip(/\}/)
236
+
237
+ loop do
238
+ @ss.skip(WS)
239
+ fail!("expected a string key") unless @ss.peek(1) == '"'
240
+ k = string
241
+ @ss.skip(WS)
242
+ fail!("expected ':'") unless @ss.skip(/:/)
243
+ out[k] = value(depth + 1)
244
+ @ss.skip(WS)
245
+ next if @ss.skip(/,/)
246
+ return out if @ss.skip(/\}/)
247
+
248
+ fail!("expected ',' or '}'")
249
+ end
250
+ end
251
+
252
+ def string
253
+ @ss.pos += 1
254
+ out = +""
255
+ loop do
256
+ out << @ss.scan(PLAIN)
257
+ c = @ss.getch
258
+ case c
259
+ when '"' then return out
260
+ when "\\"
261
+ e = @ss.getch
262
+ if e == "u"
263
+ out << unicode_escape
264
+ elsif (r = ESCAPES[e])
265
+ out << r
266
+ else
267
+ fail!("invalid escape")
268
+ end
269
+ else
270
+ fail!(c.nil? ? "unterminated string" : "control character in string")
271
+ end
272
+ end
273
+ end
274
+
275
+ def hex4
276
+ h = @ss.scan(/\h{4}/) or fail!("invalid unicode escape")
277
+ h.to_i(16)
278
+ end
279
+
280
+ def unicode_escape
281
+ r = hex4
282
+ if r >= 0xD800 && r < 0xDC00 && @ss.match?(/\\u\h{4}/)
283
+ save = @ss.pos
284
+ @ss.pos += 2
285
+ lo = hex4
286
+ return (0x10000 + ((r - 0xD800) << 10) + (lo - 0xDC00)).chr(Text::UTF8) if lo >= 0xDC00 && lo <= 0xDFFF
287
+
288
+ @ss.pos = save
289
+ end
290
+ return Text::REPLACEMENT if r >= 0xD800 && r <= 0xDFFF
291
+
292
+ r.chr(Text::UTF8)
293
+ end
294
+ end
295
+
296
+ # ---------------------------------------------------------------- equality
297
+
298
+ # equal? reports whether a and b are the same JSON value: numbers are compared by value (5 and 5.0
299
+ # are equal, as spec 2.1 rule 5.2 says), objects by their keys in order and their values.
300
+ def same_json?(a, b)
301
+ equal_values(normalize(a, 0, MAX_JSON_DEPTH), normalize(b, 0, MAX_JSON_DEPTH))
302
+ rescue Error
303
+ false
304
+ end
305
+
306
+ def equal_values(a, b)
307
+ case a
308
+ when Array
309
+ b.is_a?(Array) && a.size == b.size && a.each_index.all? { |i| equal_values(a[i], b[i]) }
310
+ when Hash
311
+ b.is_a?(Hash) && a.size == b.size && a.keys == b.keys && a.all? { |k, v| equal_values(v, b[k]) }
312
+ when Integer, Float
313
+ b.is_a?(Numeric) && a == b
314
+ when String
315
+ b.is_a?(String) && a == b
316
+ else
317
+ a.equal?(b)
318
+ end
319
+ end
320
+ end
321
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JDogo
4
+ VERSION = "3.0.0"
5
+ end