50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
|
# File 'lib/unibits.rb', line 50
def self.visualize(string)
cols = determine_terminal_cols
cp_buffer = [" "]
enc_buffer = [" "]
hex_buffer = [" "]
bin_buffer = [" "]
separator = [" "]
puts
string.each_char{ |char|
current_color = random_color
char.each_byte.with_index{ |byte, index|
if Paint.unpaint(hex_buffer[-1]).bytesize > cols - 12
cp_buffer << " "
enc_buffer << " "
hex_buffer << " "
bin_buffer << " "
separator << " "
end
if index == 0
cp_buffer[-1] << Paint[
("U+%04X" % char.ord).ljust(10), current_color, :bold
]
symbolified_char = symbolify(char)
padding = 10 - Unicode::DisplayWidth.of(symbolified_char)
enc_buffer[-1] << Paint[
symbolified_char, current_color
]
enc_buffer[-1] << " " * padding if padding > 0
else
cp_buffer[-1] << " " * 10
enc_buffer[-1] << " " * 10
end
hex_buffer[-1] << Paint[
("%02X" % byte).ljust(10, " "), current_color
]
bin_byte_complete = byte.to_s(2).rjust(8, "0")
case string.encoding.name
when 'US-ASCII'
bin_byte_1 = bin_byte_complete[0...1]
bin_byte_2 = bin_byte_complete[1...8]
when 'ASCII-8BIT'
bin_byte_1 = ""
bin_byte_2 = bin_byte_complete
when 'UTF-8'
if index == 0
if bin_byte_complete =~ /^(0|1{2,4}0)([01]+)$/
bin_byte_1 = $1
bin_byte_2 = $2
else
bin_byte_1 = ""
bin_byte_2 = bin_byte_complete
end
else
bin_byte_1 = bin_byte_complete[0...2]
bin_byte_2 = bin_byte_complete[2...8]
end
when 'UTF-16LE'
if char.ord <= 0xFFFF || index == 0 || index == 2
bin_byte_1 = ""
bin_byte_2 = bin_byte_complete
else
bin_byte_complete =~ /^(11011[01])([01]+)$/
bin_byte_1 = $1
bin_byte_2 = $2
end
when 'UTF-16BE'
if char.ord <= 0xFFFF || index == 1 || index == 3
bin_byte_1 = ""
bin_byte_2 = bin_byte_complete
else
bin_byte_complete =~ /^(11011[01])([01]+)$/
bin_byte_1 = $1
bin_byte_2 = $2
end
when 'UTF-32LE', 'UTF-32BE'
bin_byte_1 = ""
bin_byte_2 = bin_byte_complete
end
bin_buffer[-1] << Paint[
bin_byte_1, current_color
] unless !bin_byte_1 || bin_byte_1.empty?
bin_buffer[-1] << Paint[
bin_byte_2, current_color, :underline
] unless !bin_byte_2 || bin_byte_2.empty?
bin_buffer[-1] << " "
}
}
if string.encoding.name[0, 3] == "UTF"
enc_buffer.zip(cp_buffer, hex_buffer, bin_buffer, separator).flatten.join("\n")
else
enc_buffer.zip(hex_buffer, bin_buffer, separator).flatten.join("\n")
end
end
|