Class: OpenC3::BufferedFile

Inherits:
File show all
Defined in:
lib/openc3/io/buffered_file.rb,
ext/openc3/ext/buffered_file/buffered_file.c

Constant Summary collapse

BUFFER_SIZE =
16 * 1024

Constants inherited from File

File::NON_ASCII_PRINTABLE

Instance Method Summary collapse

Methods inherited from File

build_timestamped_filename, #delete, find_in_search_path, is_ascii?

Constructor Details

#initialize(*args) ⇒ Object

Initialize the BufferedFile. Takes the same args as File



31
32
33
34
35
# File 'lib/openc3/io/buffered_file.rb', line 31

def initialize(*args)
  super(*args)
  @buffer = ''
  @buffer_index = 0
end

Instance Method Details

#posObject

Get the current file position



78
79
80
81
# File 'lib/openc3/io/buffered_file.rb', line 78

def pos
  parent_pos = super()
  return parent_pos - (@buffer.length - @buffer_index)
end

#read(arg_length) ⇒ Object

Read using an internal buffer to avoid system calls



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/openc3/io/buffered_file.rb', line 38

def read(read_length)
  if read_length <= (@buffer.length - @buffer_index)
    # Return part of the buffer without having to go to the OS
    result = @buffer[@buffer_index, read_length]
    @buffer_index += read_length
    return result
  elsif read_length > BUFFER_SIZE
    # Reading more than our buffer
    if @buffer.length > 0
      if @buffer_index > 0
        @buffer.slice!(0..(@buffer_index - 1))
        @buffer_index = 0
      end
      @buffer << super(read_length - @buffer.length).to_s
      return @buffer.slice!(0..-1)
    else
      return super(read_length)
    end
  else
    # Read into the buffer
    if @buffer_index > 0
      @buffer.slice!(0..(@buffer_index - 1))
      @buffer_index = 0
    end
    @buffer << super(BUFFER_SIZE - @buffer.length).to_s
    if @buffer.length <= 0
      return nil
    end

    if read_length <= @buffer.length
      result = @buffer[@buffer_index, read_length]
      @buffer_index += read_length
      return result
    else
      return @buffer.slice!(0..-1)
    end
  end
end

#seek(*args) ⇒ Object

Seek to a given file position



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/openc3/io/buffered_file.rb', line 84

def seek(*args)
  case args.length
  when 1
    amount = args[0]
    whence = IO::SEEK_SET
  when 2
    amount = args[0]
    whence = args[1]
  else
    # Invalid number of arguments given - let super handle
    return super(*args)
  end

  if whence == IO::SEEK_CUR
    buffer_index = @buffer_index + amount
    if (buffer_index >= 0) && (buffer_index < @buffer.length)
      @buffer_index = buffer_index
      return 0
    end
    super(self.pos, IO::SEEK_SET)
  end

  @buffer.clear
  @buffer_index = 0
  return super(*args)
end