File: buffer.rb

package info (click to toggle)
ruby-httpx 1.7.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,816 kB
  • sloc: ruby: 12,209; makefile: 4
file content (61 lines) | stat: -rw-r--r-- 1,199 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true

require "forwardable"

module HTTPX
  # Internal class to abstract a string buffer, by wrapping a string and providing the
  # minimum possible API and functionality required.
  #
  #     buffer = Buffer.new(640)
  #     buffer.full? #=> false
  #     buffer << "aa"
  #     buffer.capacity #=> 638
  #
  class Buffer
    extend Forwardable

    def_delegator :@buffer, :to_s

    def_delegator :@buffer, :to_str

    def_delegator :@buffer, :empty?

    def_delegator :@buffer, :bytesize

    def_delegator :@buffer, :clear

    def_delegator :@buffer, :replace

    attr_reader :limit

    if RUBY_VERSION >= "3.4.0"
      def initialize(limit)
        @buffer = String.new("", encoding: Encoding::BINARY, capacity: limit)
        @limit = limit
      end

      def <<(chunk)
        @buffer.append_as_bytes(chunk)
      end
    else
      def initialize(limit)
        @buffer = "".b
        @limit = limit
      end

      def_delegator :@buffer, :<<
    end

    def full?
      @buffer.bytesize >= @limit
    end

    def capacity
      @limit - @buffer.bytesize
    end

    def shift!(fin)
      @buffer = @buffer.byteslice(fin..-1) || "".b
    end
  end
end