File: string_utils.rb

package info (click to toggle)
ruby-tomlrb 2.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 132 kB
  • sloc: ruby: 999; yacc: 195; makefile: 4
file content (39 lines) | stat: -rw-r--r-- 875 bytes parent folder | download
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
module Tomlrb
  class StringUtils

    SPECIAL_CHARS = {
      '\\t'  => "\t",
      '\\b'  => "\b",
      '\\f'  => "\f",
      '\\n'  => "\n",
      '\\r'  => "\r",
      '\\"'  => '"',
      '\\\\' => '\\'
    }.freeze

    def self.multiline_replacements(str)
      strip_spaces(str).gsub(/\\+\s*\n\s*/) {|matched|
        if matched.match(/\\+/)[0].length.odd?
          matched.gsub(/\\\s*\n\s*/, '')
        else
          matched
        end
      }
    end

    def self.replace_escaped_chars(str)
      str.gsub(/\\(u[\da-fA-F]{4}|U[\da-fA-F]{8}|.)/) do |m|
        if m.size == 2
          SPECIAL_CHARS[m] || (raise Tomlrb::ParseError.new "Escape sequence #{m} is reserved")
        else
          m[2..-1].to_i(16).chr(Encoding::UTF_8)
        end
      end
    end

    def self.strip_spaces(str)
      str[0] = '' if str[0] == "\n"
      str
    end
  end
end