Module: Spotify::UTF8StringPointer

Extended by:
FFI::DataConverter
Defined in:
lib/spotify/data_converters/utf8_string_pointer.rb

Overview

The NULString is used to allow you to assign struct fields with regular ruby strings. Usually, it would raise an error.

Keep in mind this implementation is unsafe to use on Rubinius as long as it ignores the .reference_required? indication.

Class Method Summary collapse

Class Method Details

.from_native(value, ctx) ⇒ String?

Given a pointer, read out it’s string.

Parameters:

  • value (FFI::Pointer)
  • ctx

Returns:

  • (String, nil)


27
28
29
# File 'lib/spotify/data_converters/utf8_string_pointer.rb', line 27

def from_native(value, ctx)
  value.read_string.force_encoding(Encoding::UTF_8) unless value.null?
end

.reference_required?Boolean

Used by FFI::StructLayoutField to know if this field requires the reference to be maintained by FFI. If we return false here, the MemoryPointer from to_native will be garbage collected before the struct.

Returns:

  • (Boolean)


35
36
37
# File 'lib/spotify/data_converters/utf8_string_pointer.rb', line 35

def reference_required?
  true
end

.to_native(value, ctx) ⇒ FFI::Pointer

Given either a String or nil, make an actual FFI::Pointer of that value.

Parameters:

  • value (#to_str, nil)
  • ctx

Returns:

  • (FFI::Pointer)


18
19
20
# File 'lib/spotify/data_converters/utf8_string_pointer.rb', line 18

def to_native(value, ctx)
  value && FFI::MemoryPointer.from_string(value.to_str.encode(Encoding::UTF_8))
end