Skip to content

Commit f15a73b

Browse files
authored
transcode data without copying (#11)
* transcode data without copying * test reusability of encoder and decoder
1 parent 7493d9c commit f15a73b

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

src/buffer.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,15 @@ function copymarked(buf::Buffer)
182182
return buf.data[buf.markpos:buf.marginpos-1]
183183
end
184184

185+
# Take the ownership of the marked data.
186+
function takemarked!(buf::Buffer)
187+
@assert buf.markpos > 0
188+
sz = buf.marginpos - buf.markpos
189+
copy!(buf.data, 1, buf.data, buf.markpos, sz)
190+
initbuffer!(buf)
191+
return resize!(buf.data, sz)
192+
end
193+
185194
# Read as much data as possbile from `input` to the margin of `output`.
186195
# This function will not block if `input` has buffered data.
187196
function readdata!(input::IO, output::Buffer)

src/stream.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ function Base.transcode(codec::Codec, data::Vector{UInt8})
327327
mark!(buffer2)
328328
stream = TranscodingStream(codec, DevNull, State(Buffer(data), buffer2))
329329
write(stream, TOKEN_END)
330-
transcoded = copymarked(buffer2)
330+
transcoded = takemarked!(buffer2)
331331
changestate!(stream, :idle)
332332
return transcoded
333333
end

src/testtools.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,11 @@ end
2626

2727
function test_roundtrip_transcode(encode, decode)
2828
srand(12345)
29+
encoder = encode()
30+
decoder = decode()
2931
for n in vcat(0:30, sort!(rand(500:100_000, 30))), alpha in (0x00:0xff, 0x00:0x0f)
3032
data = rand(alpha, n)
31-
Base.Test.@test hash(transcode(decode(), transcode(encode(), data))) == hash(data)
33+
Base.Test.@test hash(transcode(decoder, transcode(encoder, data))) == hash(data)
3234
end
3335
end
3436

0 commit comments

Comments
 (0)