Module: Archive::Utils

Defined in:
lib/ffi_libarchive/utils.rb

Defined Under Namespace

Modules: LibC

Constant Summary collapse

WCHAR_ENCODINGS =
{
  'UTF-16LE' => "!\x00@\x00\x00\x00",
  'UTF-16BE' => "\x00!\x00@\x00\x00",
  'UTF-32LE' => "!\x00\x00\x00@\x00",
  'UTF-32BE' => "\x00\x00\x00!\x00\x00"
}.freeze

Class Method Summary collapse

Class Method Details

.change_cwd(dir) ⇒ Integer

Parameters:

  • dir (String)

Returns:

  • (Integer)


84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ffi_libarchive/utils.rb', line 84

def change_cwd(dir)
  if block_given?
    # @type [String]
    cwd = Dir.getwd
    change_cwd dir

    begin
      yield
    ensure
      change_cwd cwd
    end
  else
    rc = Dir.chdir dir
    rc != 0 ? rc : LibC.chdir(dir)
  end
end

.get_memory_ptr(string) {|| ... } ⇒ FFI::Pointer

Parameters:

  • string (String)

    MANDATORY

Yield Parameters:

  • (FFI::Pointer)

Returns:

  • (FFI::Pointer)


104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/ffi_libarchive/utils.rb', line 104

def get_memory_ptr(string)
  len = string.bytesize
  if block_given?
    FFI::MemoryPointer.new(:char, len, false) do |ptr|
      ptr.put_bytes(0, string, 0, len)
      yield ptr
    end
  else
    ptr = FFI::MemoryPointer.new(:char, len, false)
    ptr.put_bytes(0, string, 0, len)
    ptr
  end
end

.read_wide_string(ptr) ⇒ String

Parameters:

  • ptr (FFI::Pointer)

Returns:

  • (String)


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/ffi_libarchive/utils.rb', line 55

def read_wide_string(ptr)
  return nil if !ptr.respond_to?(:null?) || ptr.null?

  if wchar_encoding.include?('32')
    wchar_sz = 4
    wchar_t  = :int32
  else
    wchar_sz = 2
    wchar_t  = :int16
  end

  # detect string length in bytes
  sz = ptr.size
  sz -= wchar_sz if sz

  len = 0
  len += wchar_sz while (!sz || len < sz) && ptr.send("get_#{wchar_t}", len) != 0

  ptr.get_bytes(0, len).force_encoding(wchar_encoding)
end

.to_wide_string(str) ⇒ String

Parameters:

  • str (String)

Returns:

  • (String)


78
79
80
# File 'lib/ffi_libarchive/utils.rb', line 78

def to_wide_string(str)
  str ? str.encode(wchar_encoding) : str
end

.wchar_encodingString

Returns:

  • (String)


39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ffi_libarchive/utils.rb', line 39

def wchar_encoding
  @wchar_encoding ||=
    begin
      ptr = FFI::MemoryPointer.new :char, 12
      rc  = LibC.mbstowcs ptr, '!@', 3

      str = ptr.get_bytes 0, 6
      enc = WCHAR_ENCODINGS.key(str)
      raise "Unsupported wide-character: #{rc} - #{str.inspect}" unless enc

      enc
    end
end