Class: Rnp::Output

Inherits:
Object
  • Object
show all
Defined in:
lib/rnp/output.rb

Overview

Note:

When dealing with very large data, prefer Output.to_path which should be the most efficient. Output.to_io is likely to have more overhead.

Class used to feed data out of RNP.

Examples:

output to a string

output = Rnp::Input.to_string('my data')
# ... after performing operations
output.string

output to a file

Rnp::Input.to_path('/path/to/my/file')

output to a Ruby IO object

Rnp::Input.to_io(File.open('/path/to/file', 'wb'))

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.to_io(io) ⇒ Output

Create an Output to write to an IO object.

Parameters:

  • io (IO, #write)

    the IO object

Returns:



85
86
87
# File 'lib/rnp/output.rb', line 85

def self.to_io(io)
  to_callback(io.method(:write))
end

.to_nullOutput

Create an Output to discard all writes.

Returns:



75
76
77
78
79
# File 'lib/rnp/output.rb', line 75

def self.to_null
  pptr = FFI::MemoryPointer.new(:pointer)
  Rnp.call_ffi(:rnp_output_to_null, pptr)
  Output.new(pptr.read_pointer)
end

.to_path(path) ⇒ Output

Create an Output to write to a path.

Parameters:

  • path (String)

    the path

Returns:



66
67
68
69
70
# File 'lib/rnp/output.rb', line 66

def self.to_path(path)
  pptr = FFI::MemoryPointer.new(:pointer)
  Rnp.call_ffi(:rnp_output_to_path, pptr, path)
  Output.new(pptr.read_pointer)
end

.to_string(max_alloc = 0) ⇒ Output

Create an Output to write to a string.

The resulting string can later be retrieved with #string.

Parameters:

  • max_alloc (Integer) (defaults to: 0)

    the maximum amount of memory to allocate, or 0 for unlimited

Returns:



56
57
58
59
60
# File 'lib/rnp/output.rb', line 56

def self.to_string(max_alloc = 0)
  pptr = FFI::MemoryPointer.new(:pointer)
  Rnp.call_ffi(:rnp_output_to_memory, pptr, max_alloc)
  Output.new(pptr.read_pointer)
end

Instance Method Details

#inspectObject



45
46
47
# File 'lib/rnp/output.rb', line 45

def inspect
  Rnp.inspect_ptr(self)
end

#stringString?

Retrieve the data written. Only valid for #to_string.

Returns:

  • (String, nil)


106
107
108
109
110
111
112
# File 'lib/rnp/output.rb', line 106

def string
  pptr = FFI::MemoryPointer.new(:pointer)
  len = FFI::MemoryPointer.new(:size_t)
  Rnp.call_ffi(:rnp_output_memory_get_buf, @ptr, pptr, len, false)
  buf = pptr.read_pointer
  buf.read_bytes(len.read(:size_t)) unless buf.null?
end

#write(*strings) ⇒ Integer

Write to the output.

Parameters:

  • strings (String)

Returns:

  • (Integer)

    the number of bytes written



93
94
95
96
97
98
99
100
101
# File 'lib/rnp/output.rb', line 93

def write(*strings)
  total_written = 0
  pwritten = FFI::MemoryPointer.new(:size_t)
  strings.each do |string|
    Rnp.call_ffi(:rnp_output_write, @ptr, string, string.size, pwritten)
    total_written += pwritten.read(:size_t)
  end
  total_written
end