Skip to content

Commit

Permalink
Add EncodedString#concat
Browse files Browse the repository at this point in the history
An array-like API to add a bunch of things at once
  • Loading branch information
pointlessone committed Dec 6, 2023
1 parent 362c9d6 commit acddf19
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/ttfunk/encoded_string.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require 'stringio'
require_relative 'placeholder'

module TTFunk
class UnresolvedPlaceholderError < StandardError
Expand All @@ -27,12 +28,19 @@ def <<(obj)
add_placeholder(placeholder.dup, placeholder.position + io.length)
end

self << obj.unresolved_string
io << obj.unresolved_string
end

self
end

def concat(*objs)
objs.each do |obj|
self << obj
end
self
end

def align!(width = 4)
if (length % width).positive?
self << "\0" * (width - length % width)
Expand Down
33 changes: 33 additions & 0 deletions spec/ttfunk/encoded_string_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,24 @@
end
end

describe '#concat' do
it 'adds all arguments' do
encoded_string = described_class.new
encoded_string.concat("\00", "\01", "\02", TTFunk::Placeholder.new(:foo))

expect(encoded_string.__send__(:io).string).to eq("\00\01\02\00")
expect(encoded_string.placeholders[:foo]).to_not be_nil
end

it 'returns self' do
empty_encoded_string = described_class.new
encoded_string = empty_encoded_string.concat("\00", "\01", "\02")

expect(encoded_string.string).to eq("\00\01\02")
expect(encoded_string).to equal(empty_encoded_string)
end
end

describe '#length' do
it 'retrieves the number of bytes written' do
encoded_string << 'foo'
Expand All @@ -71,6 +89,21 @@
end
end

describe '#bytes' do
it 'retrieves the encoded string bytes' do
encoded_string << 'foo'
expect(encoded_string.bytes).to eq([0x66, 0x6f, 0x6f])
end

it "raises an error if any placeholders haven't been resolved" do
encoded_string << 'foo'
encoded_string << TTFunk::Placeholder.new(:name)
expect { encoded_string.bytes }.to(
raise_error(TTFunk::UnresolvedPlaceholderError)
)
end
end

describe '#resolve_placeholder' do
it 'replaces the placeholder bytes' do
encoded_string << '123'
Expand Down

0 comments on commit acddf19

Please sign in to comment.