Class: CF::String
- 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
- HAS_ENCODING =
workaround for ruby 1.8.7 compat
"foo".respond_to? "encode"
Class Method Summary collapse
-
.from_string(s, src_encoding = 'UTF-8') ⇒ CF::String
Creates a string from a ruby string The string must be convertable to UTF-8.
Instance Method Summary collapse
-
#<=>(other) ⇒ Integer
Compares the receiver with the argument.
-
#length ⇒ Integer
Returns the length, in unicode characters of the string.
-
#to_s ⇒ String
(also: #to_ruby)
Converts the CF::String to a UTF-8 ruby string.
Methods inherited from Base
check_cftype, #eql?, #equals?, #hash, #initialize, #inspect, #null?, #ptr=, #release, #release_on_gc, #retain, #to_cf, #to_ptr, typecast
Constructor Details
This class inherits a constructor from CF::Base
Class Method Details
.from_string(s, src_encoding = 'UTF-8') ⇒ CF::String
Creates a string from a ruby string The string must be convertable to UTF-8
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/corefoundation/string.rb', line 31 def self.from_string(s, src_encoding='UTF-8') if HAS_ENCODING s_utf = s.encode('UTF-8') else begin s_utf = Iconv.conv('UTF-8', src_encoding, s.to_s) rescue Iconv::IllegalSequence => e return nil end end raw = CF.CFStringCreateWithBytes(nil, s_utf, s_utf.bytesize, UTF8, 0) raw.null? ? nil : new(raw).release_on_gc end |
Instance Method Details
#<=>(other) ⇒ Integer
Compares the receiver with the argument
54 55 56 57 |
# File 'lib/corefoundation/string.rb', line 54 def <=>(other) Base.check_cftype(other) CF.CFStringCompare(self,other,0) end |
#length ⇒ Integer
Returns the length, in unicode characters of the string
47 48 49 |
# File 'lib/corefoundation/string.rb', line 47 def length CF.CFStringGetLength(self) end |
#to_s ⇒ String Also known as: to_ruby
Converts the CF::String to a UTF-8 ruby string
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/corefoundation/string.rb', line 62 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) bytes_used = if cfindex == CF.find_type(:long_long) bytes_used_buffer.read_long_long else bytes_used_buffer.read_long end if HAS_ENCODING buffer.read_string(bytes_used).force_encoding(Encoding::UTF_8) else buffer.read_string(bytes_used) end end |