1 # coding: utf-8
2 # frozen_string_literal: true
3
4
5
6 module Umu
7
8 module Escape
9
10 EACAPE_PAIRS = [
11 ["\\n", "\n"],
12 ["\\t", "\t"],
13 ["\\\"", "\""],
14 ["\\\\", "\\"]
15 ]
16
17 MAP_OF_UNESCAPE_TO_ESCAPE = EACAPE_PAIRS.inject({}) { |hash, (unesc, esc)|
18 hash.merge(unesc => esc) { |key, _, _|
19 ASSERT.abort format("Duplicated unescape-char: '%s'", key)
20 }
21 }
22
23 MAP_OF_ESCAPE_TO_UNESCAPE = EACAPE_PAIRS.inject({}) { |hash, (unesc, esc)|
24 hash.merge(esc => unesc) { |key, _, _|
25 ASSERT.abort format("Duplicated escape-char: '%s'", key)
26 }
27 }
28
29
30 module_function
31
32 def opt_escape(unesc)
33 ASSERT.kind_of unesc, ::String
34
35 opt_esc = MAP_OF_UNESCAPE_TO_ESCAPE[unesc]
36
37 ASSERT.opt_kind_of opt_esc.freeze, ::String
38 end
39
40
41 def unescape(esc)
42 ASSERT.kind_of esc, ::String
43
44 esc.each_char.map { |esc_char|
45 opt_unesc_char = MAP_OF_ESCAPE_TO_UNESCAPE[esc_char]
46
47 if opt_unesc_char
48 opt_unesc_char
49 else
50 esc_char
51 end
52 }.join
53 end
54
55
56 def find_escape(unesc)
57 ASSERT.kind_of unesc, ::String
58
59 opt_esc = unesc.each_char.find { |unesc_char|
60 ! MAP_OF_ESCAPE_TO_UNESCAPE[unesc_char].nil?
61 }
62
63 ASSERT.opt_kind_of opt_esc.freeze, ::String
64 end
65
66 end # Umu::Escape
67
68 end # Umu