2
require 'json/pure/parser'
3
require 'json/pure/generator'
8
# An iconv instance to convert from UTF8 to UTF16 Big Endian.
9
UTF16toUTF8 = Iconv.new('utf-8', 'utf-16be') # :nodoc:
10
# An iconv instance to convert from UTF16 Big Endian to UTF8.
11
UTF8toUTF16 = Iconv.new('utf-16be', 'utf-8') # :nodoc:
12
UTF8toUTF16.iconv('no bom')
13
rescue Errno::EINVAL, Iconv::InvalidEncoding
14
# Iconv doesn't support big endian utf-16. Let's try to hack this manually
15
# into the converters.
17
old_verbose, $VERBSOSE = $VERBOSE, nil
18
# An iconv instance to convert from UTF8 to UTF16 Big Endian.
19
UTF16toUTF8 = Iconv.new('utf-8', 'utf-16') # :nodoc:
20
# An iconv instance to convert from UTF16 Big Endian to UTF8.
21
UTF8toUTF16 = Iconv.new('utf-16', 'utf-8') # :nodoc:
22
UTF8toUTF16.iconv('no bom')
23
if UTF8toUTF16.iconv("\xe2\x82\xac") == "\xac\x20"
24
swapper = Class.new do
25
def initialize(iconv) # :nodoc:
29
def iconv(string) # :nodoc:
30
result = @iconv.iconv(string)
34
UTF8toUTF16 = swapper.new(UTF8toUTF16) # :nodoc:
36
if UTF16toUTF8.iconv("\xac\x20") == "\xe2\x82\xac"
37
swapper = Class.new do
38
def initialize(iconv) # :nodoc:
42
def iconv(string) # :nodoc:
43
string = JSON.swap!(string.dup)
47
UTF16toUTF8 = swapper.new(UTF16toUTF8) # :nodoc:
49
rescue Errno::EINVAL, Iconv::InvalidEncoding
50
raise MissingUnicodeSupport, "iconv doesn't seem to support UTF-8/UTF-16 conversions"
52
$VERBOSE = old_verbose
55
raise MissingUnicodeSupport,
56
"iconv couldn't be loaded, which is required for UTF-8/UTF-16 conversions"
59
# Swap consecutive bytes of _string_ in place.
60
def self.swap!(string) # :nodoc:
61
0.upto(string.size / 2) do |i|
62
break unless string[2 * i + 1]
63
string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
68
# This module holds all the modules/classes that implement JSON's
69
# functionality in pure ruby.
71
$DEBUG and warn "Using pure library for JSON."
73
JSON.generator = Generator