BitStream
BitStream is a mixin to write data structures of bit streams such as picture, music, movie files, and e.t.c.. You can refer contents of bit streams even when you are defining the data structures. With the function, you can write a data structure easily that the header contains the data length of the body field.
Installation
gem install bitstream
Sample
gzip.rb: A metadata definition of a gzip file. ( www.gzip.org/zlib/rfc-gzip.html )
require 'bitstream'
class Gzip
include BitStream
byte_order :little_endian
FHCRC = 1 << 1
FEXTRA = 1 << 2
FNAME = 1 << 3
FCOMMENT = 1 << 4
fields do
unsigned :id1, 8
unsigned :id2, 8
unsigned :cm, 8
unsigned :flg, 8
unsigned :mtime, 32
unsigned :xfl, 8
unsigned :os, 8
if (flg & FEXTRA) != 0
unsigned :xlen, 16
string :extra_field, xlen
end
if (flg & FNAME) != 0
# cstring means a NULL-terminated string.
cstring :original_file_name
end
if (flg & FCOMMENT) != 0
# cstring means a NULL-terminated string.
cstring :file_comment
end
if (flg & FHCRC) != 0
unsigned :crc16, 16
end
end
end
gzip-viewer.rb: A viewer of the original file name of a gzip file.
require_relative 'gzip'
gzip = nil
File.open(ARGV[0], "rb") do |file|
gzip = Gzip.create(file.read)
end
if gzip.respond_to? :original_file_name
puts "original_file_name:#{gzip.original_file_name}"
else
puts "The gzip does not contain its original file name."
end
Documentation
In preparation.
License
This library is distributed under the dual license of the Ruby license (in the narrow sense) and the 2-clause BSD license. Please see www.ruby-lang.org and BSDL. Copyright © 2011, 2012 Natsuki Kawai.