Class: CF::String

Inherits:
Base
  • Object
show all
Includes:
Comparable
Defined in:
lib/corefoundation/string.rb

Overview

Wrapper class for CFString

Unlike ruby, CFString is not an arbitrary bag of bytes - the data will be converted to a collection of unicode characters

Constant Summary collapse

UTF8 =

The cfstring encoding for UTF8

0x08000100

Instance Attribute Summary

Attributes inherited from Base

#ptr

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

check_cftype, #eql?, #equals?, finalize, #hash, #initialize, #null?, #to_cf, typecast

Methods included from Memory

#inspect, #release, #retain, #to_ptr

Methods included from Register

included, #register_type

Constructor Details

This class inherits a constructor from CF::Base

Class Method Details

.from_string(s) ⇒ CF::String

Creates a string from a ruby string The string must be convertable to UTF-8

Parameters:

Returns:



28
29
30
31
32
# File 'lib/corefoundation/string.rb', line 28

def self.from_string(s)
  s_utf = s.encode("UTF-8")
  raw = CF.CFStringCreateWithBytes(nil, s_utf, s_utf.bytesize, UTF8, 0)
  raw.null? ? nil : new(raw)
end

Instance Method Details

#<=>(other) ⇒ Integer

Compares the receiver with the argument

Parameters:

Returns:

  • (Integer)


43
44
45
46
# File 'lib/corefoundation/string.rb', line 43

def <=>(other)
  Base.check_cftype(other)
  CF.CFStringCompare(self,other,0)
end

#lengthInteger

Returns the length, in unicode characters of the string

Returns:

  • (Integer)


36
37
38
# File 'lib/corefoundation/string.rb', line 36

def length
  CF.CFStringGetLength(self)
end

#to_sString Also known as: to_ruby

Converts the CF::String to a UTF-8 ruby string

Returns:



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/corefoundation/string.rb', line 51

def to_s
  max_size = CF.CFStringGetMaximumSizeForEncoding(length, UTF8)
  range = CF::Range.new
  range[:location] = 0
  range[:length] = length
  buffer = FFI::MemoryPointer.new(:char, max_size)
  cfindex = CF.find_type(:cfindex)
  bytes_used_buffer = FFI::MemoryPointer.new(cfindex)

  CF.CFStringGetBytes(self, range, UTF8, 0, 0, buffer, max_size, bytes_used_buffer)
  len = bytes_used_buffer.send(cfindex == CF.find_type(:long_long) ? :read_long_long : :read_long)

  buffer.read_string(len).force_encoding(Encoding::UTF_8)
end