Class: Codec
- Inherits:
-
Object
- Object
- Codec
- Defined in:
- lib/ruby-doom.rb
Class Method Summary collapse
-
.decode(format, bytes) ⇒ Object
Accepts a format string like “sl48” and a byte array s - short l - long 4 - 4 byte string 8 - 8 bytes string.
-
.encode(format, values) ⇒ Object
Accepts a format string like “sl48” and an array of values.
- .marshal_string(n, len) ⇒ Object
- .unmarshal_string(a) ⇒ Object
Class Method Details
.decode(format, bytes) ⇒ Object
Accepts a format string like “sl48” and a byte array s - short l - long 4 - 4 byte string 8 - 8 bytes string
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'lib/ruby-doom.rb', line 203 def Codec.decode(format, bytes) res = [] ptr = 0 format.split(//).each {|x| if x == "s" res << bytes.slice(ptr,2).pack("c2").unpack("s")[0] ptr += 2 elsif x == "l" res << bytes.slice(ptr,4).pack("C4").unpack("V")[0] ptr += 4 elsif x == "4" res << Codec.unmarshal_string(bytes.slice(ptr,4)) ptr += 4 elsif x == "8" res << Codec.unmarshal_string(bytes.slice(ptr,8)) ptr += 8 else raise "Unknown character in decode format string " + format end } return res end |
.encode(format, values) ⇒ Object
Accepts a format string like “sl48” and an array of values
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
# File 'lib/ruby-doom.rb', line 226 def Codec.encode(format, values) bytes = [] ptr = 0 format.split(//).each {|x| if x == "s" bytes += [values[ptr]].pack("S").unpack("C2") elsif x == "l" bytes += [values[ptr]].pack("N").unpack("C4").reverse elsif x == "4" bytes += Codec.marshal_string(values[ptr],4) elsif x == "8" bytes += Codec.marshal_string(values[ptr],8) else raise "Unknown character in decode format string " + format end ptr += 1 } return bytes end |
.marshal_string(n, len) ⇒ Object
248 249 250 251 252 253 254 |
# File 'lib/ruby-doom.rb', line 248 def Codec.marshal_string(n,len) arr = n.unpack("C#{len}").compact if arr.size < len arr += Array.new(len-arr.size, 0) end arr end |
.unmarshal_string(a) ⇒ Object
245 246 247 |
# File 'lib/ruby-doom.rb', line 245 def Codec.unmarshal_string(a) a.pack("C*").strip end |