Module: Clojure::StringParser

Included in:
Parser
Defined in:
lib/str_parse.rb

Overview

Taken from the JSON parser at flori.github.com/json/

Constant Summary collapse

STRING =
/" ((?:[^\x0-\x1f"\\] |
  # escaped special characters:
  \\["\\\/bfnrt] |
  \\u[0-9a-fA-F]{4} |
  # match all but escaped special characters:
  \\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*)
"/nx
EMPTY_8BIT_STRING =
''
UNESCAPE_MAP =
Hash.new { |h, k| h[k] = k.chr }

Instance Method Summary collapse

Instance Method Details

#parse_stringObject



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
# File 'lib/str_parse.rb', line 14

def parse_string
  if scan(STRING)
    return '' if self[1].empty?

    string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c|
      if u = UNESCAPE_MAP[$&[1]]
        u
      else # \uXXXX
        bytes = EMPTY_8BIT_STRING.dup
        i = 0
        while c[6 * i] == ?\\ && c[6 * i + 1] == ?u
          bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16)
          i += 1
        end
    
        Iconv.iconv('utf-8', 'utf-16be', bytes)
      end
    end

    if string.respond_to?(:force_encoding)
      string.force_encoding(::Encoding::UTF_8)
    end

    string
  else
    :no_string
  end
rescue => e
  raise ParserError, "Caught #{e.class} at '#{peek(20)}': #{e}"
end