Skip to content

Commit

Permalink
Add constructor that allows specifying type (#5)
Browse files Browse the repository at this point in the history
That is, allow `MemoryView{Int}([1,2,3])`.
  • Loading branch information
jakobnissen authored Nov 13, 2024
1 parent 18da69e commit 5f5d4db
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/MemoryViews.jl
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,18 @@ is observed to be mutated.
MutableMemoryView(::Unsafe, x::MemoryView{T}) where {T} =
MutableMemoryView{T}(unsafe, x.ref, x.len)

# Constructors that allows users to specify eltype explicitly, e.g.
# ImmutableMemoryView{UInt8}([0x01])
# With mutability specified
function MemoryView{T, M}(x) where {T, M}
(MemoryView{X, M} where X)(x)::MemoryView{T, M}
end

# With mutability unspecified
function MemoryView{T}(x) where T
MemoryView(x)::MemoryView{T}
end

"""
MemoryKind
Expand Down
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ end
s = Test.GenericString("abγδf")
@test codeunits(s) == MemoryView(s)
@test codeunits(s[2:(end - 2)]) == MemoryView(s)[2:(end - 1)]

x = [1,2,3]
@test MemoryView{Int}(x) isa MutableMemoryView{Int}
@test ImmutableMemoryView{Int}(x) isa ImmutableMemoryView{Int}
@test_throws TypeError MemoryView{UInt32}(x)
@test_throws TypeError ImmutableMemoryView{UInt32}(x)
end

@testset "Immutable views are immutable" begin
Expand Down

0 comments on commit 5f5d4db

Please sign in to comment.