summaryrefslogtreecommitdiff
path: root/jni/ruby/lib/rexml/encoding.rb
blob: 1c7e79a124a20ed3f382e5f5083d6d73da1c5dfe (plain)
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
# coding: US-ASCII
module REXML
  module Encoding
    # ID ---> Encoding name
    attr_reader :encoding
    def encoding=(encoding)
      encoding = encoding.name if encoding.is_a?(Encoding)
      if encoding.is_a?(String)
        original_encoding = encoding
        encoding = find_encoding(encoding)
        unless encoding
          raise ArgumentError, "Bad encoding name #{original_encoding}"
        end
      end
      return false if defined?(@encoding) and encoding == @encoding
      if encoding
        @encoding = encoding.upcase
      else
        @encoding = 'UTF-8'
      end
      true
    end

    def encode(string)
      string.encode(@encoding)
    end

    def decode(string)
      string.encode(::Encoding::UTF_8, @encoding)
    end

    private
    def find_encoding(name)
      case name
      when /\Ashift-jis\z/i
        return "SHIFT_JIS"
      when /\ACP-(\d+)\z/
        name = "CP#{$1}"
      when /\AUTF-8\z/i
        return name
      end
      begin
        ::Encoding::Converter.search_convpath(name, 'UTF-8')
      rescue ::Encoding::ConverterNotFoundError
        return nil
      end
      name
    end
  end
end