module Archive::Utils

Constants

WCHAR_ENCODINGS

Public Class Methods

change_cwd(dir) { || ... } click to toggle source

@param [String] dir @return [Integer]

# 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) { |ptr| ... } click to toggle source

@param [String] string MANDATORY @return [FFI::Pointer] @yieldparam [FFI::Pointer]

# 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) click to toggle source

@param [FFI::Pointer] ptr @return [String]

# 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) click to toggle source

@param [String] str @return [String]

# File lib/ffi_libarchive/utils.rb, line 78
def to_wide_string(str)
  str ? str.encode(wchar_encoding) : str
end
wchar_encoding() click to toggle source

@return [String]

# 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