Module: CStruct::Utils

Defined in:
lib/cstruct/utils.rb

Overview

:nodoc: all

Constant Summary collapse

UnpackFormat =
{
  :little => { 1=>'C',2=>'v',4=>'V',8=>'Q',:float=>'e',:double=>'E'},
  :big    => { 1=>'C',2=>'n',4=>'N',8=>'Q',:float=>'g',:double=>'G'}, #8=>'Q'? 'Q' is native endian
}
SigedMaxValue =

8=>‘Q’? ‘Q’ is native endian

{  1 => 0x7F, 2 => 0x7FFF, 4 => 0x7FFFFFFF, 8 => 0x7FFFFFFFFFFFFFFF }
UnsigedMaxValue =
{  1 => 0xFF, 2 => 0xFFFF, 4 => 0xFFFFFFFF, 8 => 0xFFFFFFFFFFFFFFFF }

Class Method Summary collapse

Class Method Details

.buffer_setbytes(target, source, target_index) ⇒ Object



45
46
47
48
49
# File 'lib/cstruct/utils.rb', line 45

def buffer_setbytes(target,source,target_index)
    source.enum_for(:each_byte).each_with_index do |byte,index|
    string_setbyte(target,target_index + index,byte)
  end
end

.pack(buffer, struct_endian, fsize, fsign) ⇒ Object

buffer is a Array’s object



27
28
29
30
31
# File 'lib/cstruct/utils.rb', line 27

def pack(buffer,struct_endian,fsize,fsign)
  format_index = (fsign==:float or fsign ==:double) ? (fsign):(fsize)
  format = UnpackFormat[struct_endian][format_index] 
  buffer.pack format
end

.string_getbyte(string, index) ⇒ Object



37
38
39
# File 'lib/cstruct/utils.rb', line 37

def string_getbyte(string,index)
  RUBY_VERSION < "1.9" ? (string[index]):(string.getbyte index)
end

.string_setbyte(string, index, value) ⇒ Object



33
34
35
# File 'lib/cstruct/utils.rb', line 33

def string_setbyte(string,index,value)
  RUBY_VERSION < "1.9" ? (string[index] = value):(string.setbyte index,value)       
end

.unpack(buffer, struct_endian, fsize, fsign) ⇒ Object

buffer is a String’s object



15
16
17
18
19
20
21
22
23
24
# File 'lib/cstruct/utils.rb', line 15

def unpack(buffer,struct_endian,fsize,fsign)
  format_index = (fsign==:float or fsign ==:double) ? (fsign):(fsize)
  format = UnpackFormat[struct_endian][format_index]
  value  = buffer.unpack(format).first
 
  if  fsign == :signed
    value = unsigned_to_signed value,fsize
  end  
  value
end

.unsigned_to_signed(value, value_size) ⇒ Object



41
42
43
# File 'lib/cstruct/utils.rb', line 41

def unsigned_to_signed(value,value_size)
  value > SigedMaxValue[value_size] ? (value - UnsigedMaxValue[value_size]-1):(value)  
end