From acddf195de28627d32772ca5c668fada674c4de7 Mon Sep 17 00:00:00 2001 From: Alexander Mankuta Date: Wed, 6 Dec 2023 12:16:16 +0200 Subject: [PATCH] Add EncodedString#concat An array-like API to add a bunch of things at once --- lib/ttfunk/encoded_string.rb | 10 ++++++++- spec/ttfunk/encoded_string_spec.rb | 33 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/lib/ttfunk/encoded_string.rb b/lib/ttfunk/encoded_string.rb index ed92c2bf..3b92a303 100644 --- a/lib/ttfunk/encoded_string.rb +++ b/lib/ttfunk/encoded_string.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require 'stringio' +require_relative 'placeholder' module TTFunk class UnresolvedPlaceholderError < StandardError @@ -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) diff --git a/spec/ttfunk/encoded_string_spec.rb b/spec/ttfunk/encoded_string_spec.rb index 203fada9..8242b23a 100644 --- a/spec/ttfunk/encoded_string_spec.rb +++ b/spec/ttfunk/encoded_string_spec.rb @@ -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' @@ -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'