Module: NativeBuffer

Includes:
Comparable
Included in:
NativeMallocBuffer, Oinky::Internal::DB_string
Defined in:
lib/oinky/nbuffer.rb

Overview

This is intended to be used by multiple libraries to share large string objects, without having to copy them on/off the ruby heap, via ruby String.

Some ruby implementations (JRuby) move GC memory around, rather than just refcounting it, as MRI does. To keep the string from moving, we need to allocate it on the native heap. However, we still want to manage it, as we want to be abel to share it between components, none of which may be capable of managing it independently.

So, we use the ruby GC to manage an object, which explicitly manages the lifetime of the native object. The native object can be passed between components by reference, rather than always by value.

Defined Under Namespace

Modules: LibC

Instance Method Summary collapse

Instance Method Details

#<=>(other) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/oinky/nbuffer.rb', line 99

def <=>(other)
  if other.is_a? NativeBuffer
    ll = self.length
    ol = other.length
    k = ll - ol
    cl = k < 0 ? ll : ol
    r = LibC.memcmp(self.ptr, other.ptr, cl)
    return r if r != 0
    return k
  else
    return self.to_s <=> other
  end
end

#cloneObject

def ptr

  @ptr
end
def length
  @size
end


57
58
59
# File 'lib/oinky/nbuffer.rb', line 57

def clone
  NativeMallocBuffer.new(self)
end

#each_byteObject



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/oinky/nbuffer.rb', line 74

def each_byte
  e = Enumerator.new { |blk|
    (0..self.length-1).each { |i|
      blk.yield (self.ptr + i).read_uchar
    }
  }
  if block_given?
    e.each {|v| yield v}
    return self
  else
    return e
  end
end

#each_charObject



88
89
90
91
92
93
94
95
96
97
# File 'lib/oinky/nbuffer.rb', line 88

def each_char
  if block_given?
    each_byte { |b| yield(b.chr) }
    return self
  else
    return Enumerator.new { |blk|
      each_byte { |b| blk.yield(b.chr) }
    }
  end
end

#inspectObject



70
71
72
# File 'lib/oinky/nbuffer.rb', line 70

def inspect
  "#<#{self.class}:0x#{self.__id__.to_s(16)} length=#{self.length} ptr=#{self.ptr.inspect}"
end

#rb_strObject Also known as: to_s

Convert native string to a ruby string



62
63
64
65
66
# File 'lib/oinky/nbuffer.rb', line 62

def rb_str
  l = self.length
  return '' unless l > 0
  self.ptr.read_string(l)
end