Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# 0.3.3
## New features
* Add `Base.take!(::VecWriter)`, which returns the written data as a mutable view,
emptying the input writer.

# 0.3.2
## New features
* Export `buffer_until(::AbstractBufReader, ::UInt8)`, which fetches a buffer with
Expand Down
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "BufferIO"
uuid = "ff366017-094f-4144-bd70-a828a0d67152"
version = "0.3.2"
version = "0.3.3"
authors = ["Jakob Nybo Andersen <jnandersen@proton.me>"]

[deps]
Expand Down
67 changes: 62 additions & 5 deletions src/vecwriter.jl
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,23 @@ end
# The vector's elements are stored in `get_memory(ref)`, starting at `memindex(ref)`
memory_ref(v::Vector{UInt8}) = getfield(v, :ref)

# Make `v` use `mem` as its memory, starting at the first element of `mem`.
# The elements of `v` are not copied.
# Callers must ensure `length(v) ≤ length(mem)`.
function unsafe_set_memory!(v::Vector{UInt8}, mem::Memory{UInt8})
setfield!(v, :ref, memoryref(mem))
return nothing
end

# Set the length of `v` without initializing or reallocating memory.
# Callers must ensure `n` is in `0:(length(v) + unused_space(v))`.
unsafe_set_length!(v::Vector{UInt8}, n::Int) = setfield!(v, :size, (n,))

# A vector whose memory is owned by a `String`, such that `String(v)` can take ownership
# of the memory instead of copying it. Base keeps this property when the vector grows.
# Memory owned by a `String`, such that `String(v)` of a vector using the memory can take
# ownership of the memory instead of copying it. Base keeps this property when the vector
# grows, but only if the memory is nonempty: Empty string memory is Base's shared empty
# memory, which is not owned by a string.
string_memory(len::Int) = Base.StringMemory(len)
string_vector(len::Int) = Base.StringVector(len)

################################
Expand All @@ -55,6 +66,13 @@ end
# N.B: `sizehint!` is not used, since it does not guarantee unused space
# if the vector has a nonzero offset into its memory.
function add_unused_space!(v::Vector{UInt8}, space::UInt)
# Base would grow empty memory into memory not owned by a string, so `String(v)`
# would copy. Allocate string memory instead. This lets vectors, and therefore
# `VecWriter()`, start without allocating memory.
if isempty(get_memory(v))
unsafe_set_memory!(v, string_memory(max(space, DEFAULT_VECWRITER_SIZE % UInt) % Int))
return nothing
end
len = length(v)
# Growing reallocates (with overallocation), or moves the elements to the start of the memory
resize!(v, len + space)
Expand All @@ -80,7 +98,7 @@ implicit (non-semantic) behaviour (e.g. memory reallocations or efficiency) of t
Mutating `vec` invalidates buffers previously obtained from `io` with e.g. `get_buffer`.

Create with one of the following constructors:
* `VecWriter()`
* `VecWriter()`: Create an empty vector.
* `VecWriter(undef, n::Int)`: Create an empty vector with space for at least `n` bytes
* `VecWriter(vec::Vector{UInt8})`: Append to `vec`, which is not copied.

Expand Down Expand Up @@ -112,9 +130,10 @@ struct VecWriter <: AbstractBufWriter
VecWriter(v::Vector{UInt8}) = new(v)
end

# Number of bytes allocated when a `VecWriter` with no memory is first written to
const DEFAULT_VECWRITER_SIZE = 32

VecWriter() = VecWriter(undef, DEFAULT_VECWRITER_SIZE)
VecWriter() = VecWriter(UInt8[])

function VecWriter(::UndefInitializer, len::Int)
return VecWriter(empty!(string_vector(len)))
Expand Down Expand Up @@ -155,7 +174,15 @@ Base.isopen(::VecWriter) = true
Base.flush(::VecWriter) = nothing

## Optimised write implementations
Base.write(io::VecWriter, x::UInt8) = (push!(io.vec, x); 1)
# Not `push!`, since Base would grow empty memory into memory not owned by a string
function Base.write(io::VecWriter, x::UInt8)
vec = io.vec
ensure_unused_space!(vec, UInt(1))
len = length(vec) + 1
unsafe_set_length!(vec, len)
@inbounds vec[len] = x
return 1
end

function Base.unsafe_write(io::VecWriter, ptr::Ptr{UInt8}, n_bytes::UInt)
iszero(n_bytes) && return 0
Expand All @@ -172,3 +199,33 @@ else
# Base defines this method from Julia 1.13
takestring!(v::Vector{UInt8}) = String(v)
end

"""
take!(io::VecWriter)::MutableMemoryView{UInt8}

Return the previous written ([`consume`](@ref)d) bytes without copying.
Leave `io` empty, and backed by a different `Memory`.

# Examples
```jldoctest
julia> io = VecWriter();

julia> write(io, "Hello, world!")
13

julia> v = take!(io); v == b"Hello, world!"
true

julia> write(io, "Other data")
10

julia> v == b"Hello, world!" # unchanged
true
```
"""
function Base.take!(io::VecWriter)
result = get_unflushed(io)
unsafe_set_length!(io.vec, 0)
unsafe_set_memory!(io.vec, Memory{UInt8}())
return result
end
107 changes: 107 additions & 0 deletions test/vecwriter.jl
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,113 @@ end
@test takestring!(vw) == "ghi"
end

@testset "Memory is string-owned when starting with empty memory" begin
function test_reuses_memory(vw::VecWriter, expected::String)
p = pointer(vw.vec)
s = takestring!(vw)
@test s == expected
return @test pointer(s) == p
end
writes = [
vw -> write(vw, 0x61),
vw -> write(vw, "a"),
vw -> write(vw, "a"^100),
vw -> (buf = get_nonempty_buffer(vw); buf[1] = 0x61; consume(vw, 1)),
vw -> (grow_buffer(vw); buf = get_buffer(vw); buf[1] = 0x61; consume(vw, 1)),
]
for f in writes, make in [VecWriter, () -> VecWriter(undef, 0), () -> VecWriter(UInt8[])]
vw = make()
f(vw)
expected = String(copy(vw.vec))
test_reuses_memory(vw, expected)
# After takestring!, the vector has empty memory again
f(vw)
test_reuses_memory(vw, expected)
end

# Growing far beyond the initial size
vw = VecWriter()
for i in 1:1000
write(vw, i % UInt8)
end
test_reuses_memory(vw, String([i % UInt8 for i in 1:1000]))
end

@testset "take!" begin
# Basic use: Returns the written bytes, and leaves the writer empty
io = VecWriter()
write(io, "Hello, world!")
v = take!(io)
@test v isa MutableMemoryView{UInt8}
@test v == b"Hello, world!"
@test isempty(io.vec)
@test isempty(get_unflushed(io))

# The bytes are not copied
io = VecWriter()
write(io, "abc")
p = pointer(io.vec)
v = take!(io)
@test pointer(v) == p

# Writes after take! do not affect the result, whether or not the writes
# would fit in the memory of the taken bytes
for s in ["xyz", "x"^1000]
io = VecWriter(undef, 100)
write(io, "abc")
v = take!(io)
write(io, s)
@test v == b"abc"
@test io.vec == codeunits(s)
# Neither do other mutations of the vector
fill!(io.vec, 0x00)
empty!(io.vec)
append!(io.vec, b"def")
@test v == b"abc"
end

# The writer is usable after take!, and memory is still string-owned
io = VecWriter()
write(io, "abc")
take!(io)
write(io, "def")
p = pointer(io.vec)
s = takestring!(io)
@test s == "def"
@test pointer(s) == p

# Repeated take!
io = VecWriter()
results = map(["a", "bc", "", "def"]) do s
write(io, s)
take!(io)
end
@test results == [b"a", b"bc", b"", b"def"]

# Empty writers
for io in [VecWriter(), VecWriter(undef, 0), VecWriter(undef, 100)]
v = take!(io)
@test isempty(v)
@test isempty(io.vec)
write(io, "abc")
@test isempty(v)
@test io.vec == b"abc"
end

# Takes from a wrapped vector, including bytes not written by the writer,
# and with a nonzero offset into its memory
vec = collect(b"_abc")
popfirst!(vec)
io = VecWriter(vec)
write(io, "def")
v = take!(io)
@test v == b"abcdef"
@test isempty(vec)
push!(vec, 0x01)
@test v == b"abcdef"
@test io.vec === vec
end

@testset "Construction" begin
vw = VecWriter()
@test vw isa VecWriter
Expand Down
Loading