We are going to create a lazy-loaded dataset type that implements the AbstractArray interface.
The dataset will be stored on disk (in a file) and we will only load the necessary parts when indexed.
We assume the entire dataset cannot fit in memory, so we load on demand.
Let's design:
- A type
LazyDataset{T, N} that is a subtype of AbstractArray{T, N}.
- We need to store the file path and the dimensions (size) of the array.
- We assume the data is stored in a binary file in row-major order (C order) for simplicity.
Steps for the function:
- Define the struct with necessary fields: file, size, and maybe the element type.
- Implement
Base.size and Base.length.
- Implement
Base.getindex to read the required portion from the file.
- Since the array might be multidimensional, we have to handle the indexing and read the correct bytes.
However, note: we are lazy-loading, so we only read the requested element or subarray.
But note: reading a single element from a disk file is inefficient if we do it for every index.
We might consider caching or reading in blocks? But the problem says lazy-loaded, so we do on-demand.
But if we are going to index one element at a time, we might want to read a block? However, the problem doesn't specify.
Since we are implementing the AbstractArray interface, we must support linear indexing and Cartesian indexing.
Let's assume we are storing the data in a raw binary file of T (so sizeof(T) bytes per element).
We'll design:
LazyDataset{T, N}(file::String, size::NTuple{N, Int})
But note: the file might be large, so we don't want to read the entire file at once.
We'll use open and seek to read the specific element.
How to compute the offset for a given index?
For a multi-dimensional array in row-major (C order), the linear index (1-based) is:
linear = i1 + (i2-1)*d1 + (i3-1)d1d2 + ...
But Julia's linear indexing for arrays is 1-based and column-major (Fortran order) by default.
However, the problem doesn't specify the order. Let's assume we are storing in row-major (C) because that's common for binary files.
But Julia's arrays are column-major. So if we store in row-major, then when we read we have to convert the indexing.
Alternatively, we can store in column-major? But then the file would be in the same order as Julia's internal.
Let's decide: we'll store in column-major (Julia's order) so that the linear index in the file is the same as Julia's linear index.
So, if we have an array of size (d1, d2, ..., dN) and we want the element at (i1, i2, ..., iN) (1-based), then the linear index in the file (1-based) is:
linear = i1 + (i2-1)d1 + (i3-1)d1d2 + ... + (iN-1)d1d2...*d_{N-1}
But note: in Julia, the linear index for an array A with indices starting at 1 is:
linear = i1 + (i2-1)*size(A,1) + ...
So that matches.
Therefore, we can compute the byte offset as:
offset = (linear - 1) * sizeof(T)
Steps for getindex:
- Convert the Cartesian index to a linear index (using
LinearIndices).
- Compute the byte offset.
- Seek to that offset in the file.
- Read
sizeof(T) bytes and convert to T.
However, what about subarrays? The AbstractArray interface requires that we can index with a Cartesian range or a colon, etc.
But note: if we are asked for a subarray (like A[1:2, 3:4]), then we have to return an array. Since we are lazy, we might want to return a lazy subarray? But that complicates.
Alternatively, we can just read the entire subarray at once? But that might be a lot of data.
The problem says "lazy-loaded", so we might want to avoid loading the entire subarray. But then we have to return an array that is also lazy? That would be a recursive lazy array.
However, for simplicity, let's only support indexing with a single integer (for linear indexing) and with a tuple of integers (for Cartesian indexing). We won't support ranges or colon for now.
But wait, the AbstractArray interface requires that we handle all types of indexing? Actually, no: we only need to implement the methods that are used. But the standard indexing in Julia can be with integers, ranges, colon, etc.
We can choose to only support integer indices and then for other types we can convert to a Cartesian array of integers and then read? But that would be eager.
Alternatively, we can return a LazyDataset that represents the subarray? That would be more complex.
Since the problem says "lazy-loaded dataset", maybe we are only expected to support single element access? But the interface requires iteration and indexing.
Let's read the problem again: "defines a custom AbstractArray interface (indexing, iteration) for a lazy-loaded dataset."
So we need to support indexing and iteration. Iteration over an array in Julia, by default, is over the linear indices (using eachindex). And eachindex returns an iterator of Cartesian indices for multi-dimensional arrays.
So if we implement getindex for Cartesian indices (with integers) and size, then iteration will work because eachindex will produce Cartesian indices and then we call getindex with those.
But what about when someone does A[1:2, 3:4]? That would be a SubArray and we don't want to read the entire subarray at once? Actually, the getindex for a SubArray is implemented in terms of the parent's getindex with the converted indices. So if we support integer Cartesian indices, then SubArray will work by converting the range to a Cartesian array of integers? Not exactly: SubArray uses to_indices which converts the indexing to a tuple of arrays of integers? Then it calls getindex with those arrays? That would be a lot of calls.
Alternatively, we can implement getindex for CartesianIndex and for Integer (linear) and then for Tuple{Vararg{Union{Integer, Colon, AbstractRange}}} we can compute the linear indices for the subarray and read them in one go? But that might be a lot of data.
Given the complexity, let's stick to single element access for now and then if needed we can extend.
But then how do we support iteration? eachindex produces CartesianIndex objects. So we must implement getindex(::LazyDataset, ::CartesianIndex).
Let's do:
size(A::LazyDataset) = A.size
getindex(A::LazyDataset, i::Integer) -> convert to CartesianIndex and then read? Or compute linear index directly? We can use LinearIndices(A) to get the linear index for a CartesianIndex? But we can also compute the linear index from the tuple.
Alternatively, we can define:
getindex(A::LazyDataset, I::Vararg{Integer, N}) where {N}
and
getindex(A::LazyDataset, i::CartesianIndex{N}) where {N}
But note: CartesianIndex is a type that holds a tuple of integers.
We'll do:
For getindex(A::LazyDataset, I::Vararg{Integer}):
ci = CartesianIndex(I)
return getindex(A, ci)
For getindex(A::LazyDataset, ci::CartesianIndex):
Check that ci is within the bounds (using checkbounds? We can use checkbounds to throw an error if out of bounds).
Compute the linear index: we can use LinearIndices(A)(ci) but that might allocate? Alternatively, we can compute it ourselves.
But note: LinearIndices returns a LinearIndices object that can be called with a CartesianIndex to get the linear index. We can precompute the strides?
Alternatively, we can compute:
linear = 1
for (j, d) in enumerate(A.size)
linear += (ci[j] - 1) * prod(A.size[1:j-1])
end
But note: the first dimension doesn't multiply by anything? Actually, the formula is:
linear = ci[1] + (ci[2]-1)*A.size[1] + (ci[3]-1)*A.size[1]*A.size[2] + ...
So:
linear = 0
stride = 1
for j in 1:length(ci)
linear += (ci[j] - 1) * stride
stride *= A.size[j]
end
linear += 1 # because we start at 1
But wait, the formula above gives 0-based? Let's test:
For 1D: size=(d1,). Then for index i1: linear = (i1-1)*1 + 1 = i1 -> correct.
For 2D: size=(d1,d2). For (i1,i2): linear = (i1-1)*1 + (i2-1)*d1 + 1 = i1 + (i2-1)*d1 -> correct for column-major? Actually, in column-major, the first index varies fastest? No, in column-major the first index is the row and the second is the column? Wait, in Julia:
A = [1 2; 3 4] # 2x2
A[1,1] -> 1
A[2,1] -> 3
A[1,2] -> 2
A[2,2] -> 4
So linear index for (2,1) is 3? Because:
linear = 2 + (1-1)*2 = 2 -> that's not 3.
Let me compute:
For (1,1): 1 + (1-1)*2 = 1 -> correct.
For (2,1): 2 + (1-1)*2 = 2 -> but we want 3? Actually, in column-major, the first index (row) varies fastest? No, the first index is the row, and when you go down the rows, you are moving in memory? In column-major, the first dimension is contiguous? Actually, in column-major, the first index changes fastest? Let's think:
In memory, the elements are stored: [1, 3, 2, 4] for the 2x2 matrix? That would be:
A[1,1] = 1 -> index 1
A[2,1] = 3 -> index 2
A[1,2] = 2 -> index 3
A[2,2] = 4 -> index 4
So the linear index for (2,1) is 2, and for (1,2) is 3.
Therefore, the formula for column-major (Julia) is:
linear = i1 + (i2-1)*d1 + (i3-1)*d1*d2 + ...
So our formula above with:
linear = 0
stride = 1
for j in 1:length(ci)
linear += (ci[j] - 1) * stride
stride *= A.size[j]
end
linear += 1
gives for (2,1) in 2x2:
j=1: linear += (2-1)*1 = 1, stride *=2 -> stride=2
j=2: linear += (1-1)*2 = 0, stride *=? -> but we break after j=2? We are using the size of the j-th dimension? Actually, note: in the formula, the stride for the j-th index is the product of the sizes of the first (j-1) dimensions.
So:
linear = 1 (from j=1) + 0 (from j=2) = 1, then +1 -> 2? That's not 2? Wait, we started linear at 0? Let me recalc:
For (2,1):
j=1: ci[1]=2 -> (2-1)*1 = 1, so linear=1, stride becomes 2 (because stride *= size[1] which is 2? Actually, stride starts at 1, then after j=1 we multiply by size[1]? Then for j=2 we use stride=2? But in the formula, for the second index, the stride is d1 (which is 2). So we did:
linear += (ci[2]-1)*stride -> (1-1)*2 = 0.
Then we add 1? So linear=1+1=2? That's correct for (2,1) in column-major? But wait, we wanted 2? Actually, (2,1) is the second element in column 1? In column-major, column 1 is [1,3] so (2,1) is 3 and that's the second element. So linear index 2 -> correct.
But wait, our formula for (1,2):
j=1: (1-1)*1=0, stride becomes 2.
j=2: (2-1)*2=2, so linear=2, then +1 -> 3 -> correct.
So the formula works.
However, note: we are using `A.size[j]` for the stride update? But the stride for the next dimension is the product of the previous dimensions. So:
stride = 1
for j in 1:length(ci)
linear += (ci[j] - 1) * stride
stride *= A.size[j]
end
linear += 1
But note: we are multiplying stride by `A.size[j]` after using it for the current index? That's correct because for the next dimension we want the product of the current and all previous.
However, what about the last dimension? We don't need to update stride after the last, but it doesn't matter.
Alternatively, we can use `LinearIndices` which does the same.
But note: `LinearIndices` is defined for an array and returns the linear index for a CartesianIndex. We can use:
lin = LinearIndices(A)(ci)
That would be simpler and we don't have to worry about the formula.
However, `LinearIndices` might be inefficient? It's a function that returns a callable. But we are only doing one call per index? That's acceptable.
So we can do:
function getindex(A::LazyDataset, ci::CartesianIndex)
checkbounds(A, ci)
lin = LinearIndices(A)(ci)
return _read_element(A, lin)
end
But wait, `checkbounds` will check if the CartesianIndex is within `A.size`. We can do that.
Alternatively, we can just try to read and if the offset is beyond the file, then error? But better to check.
Now, for `getindex` with a tuple of integers:
function getindex(A::LazyDataset, I::Vararg{Integer, N}) where {N}
return getindex(A, CartesianIndex(I))
end
But note: the number of integers must match the dimensionality. If we get a tuple of less than N, then we are missing dimensions? Actually, Julia allows indexing with fewer dimensions? For example, a 2D array can be indexed with one integer? That would return a vector (the column). But we don't support that because we are returning an element? We are only returning a single element for integer indexing? Actually, in Julia:
A[1] on a 2D array returns the first element (linear index 1) and A[1,2] returns the element at (1,2).
So we must support both:
- `getindex(A::LazyDataset, i::Integer)` -> linear indexing.
- `getindex(A::LazyDataset, i1::Integer, i2::Integer, ...)` -> Cartesian indexing.
But note: the number of arguments must match the dimensionality? Actually, for a 2D array, `A[1]` is linear indexing and `A[1,2]` is Cartesian. We can define:
getindex(A::LazyDataset, i::Integer) = getindex(A, CartesianIndices(A)[i])? That would be inefficient.
Alternatively, we can compute the linear index from the integer? But note: the integer is already the linear index? So we can do:
getindex(A::LazyDataset, i::Integer) = _read_element(A, i)
But we must check that i is within 1:length(A).
And for the CartesianIndex version, we convert to linear.
But wait, what about when we have a 1D array? Then `getindex(A, i::Integer)` and `getindex(A, i1::Integer)` are the same? But we have two methods? We can have:
getindex(A::LazyDataset, i::Integer) = _read_element(A, i)
getindex(A::LazyDataset, I::Vararg{Integer}) = getindex(A, CartesianIndex(I))
But then for a 1D array, which one is called? If we call `A[1]` with one integer, the first method is called. If we call `A[1]` with a tuple? Actually, `A[1]` is one integer, so first method. But what about `A[(1,)]`? That would be a tuple of one integer, so the second method.
We can also define:
getindex(A::LazyDataset, i::CartesianIndex) = ... # as above
But then we have to handle the conversion from tuple to CartesianIndex.
Alternatively, we can define:
getindex(A::LazyDataset, I...) = getindex(A, CartesianIndex(I))
But then `A[1]` would be caught by this? Because `I` would be `(1,)`? Actually, `A[1]` with one integer would be `I = (1,)`? Then we call `CartesianIndex((1,))`? That is a `CartesianIndex` of dimension 1? Then we convert to linear? But then we are doing an extra step.
Alternatively, we can define:
getindex(A::LazyDataset, i::Integer) = _read_element(A, i)
getindex(A::LazyDataset, I::Vararg{Integer}) = getindex(A, CartesianIndex(I))
But note: the second method will also match `A[1]` because `Vararg{Integer}` with one integer is `(1,)`. So we have an ambiguity? Actually, the first method is more specific? The first method is for a single integer, the second for a vararg. But `A[1]` is a single integer, so the first method is called? Let's test:
f(x::Int) = 1
f(x::Vararg{Int}) = 2
f(1) -> 1? Because `Int` is a subtype of `Vararg{Int}`? Actually, `Vararg{Int}` is a type that represents a tuple of Ints? And `Int` is not a tuple. So `f(1)` calls the first method, and `f(1,2)` calls the second? But `f(1)` is not a tuple, so it's not a `Vararg`. So we are safe.
However, when we call `A[1]` we are passing one integer, so the first method is called. When we call `A[1,2]` we are passing two integers, so the second method is called.
But wait, what about `A[1,2,3]`? Then the second method with three integers.
But what about `A[1:2]`? That would be a range, which is not an Integer. So we don't support that.
So we are only supporting integer indexing.
But then how do we support iteration? `eachindex` returns `CartesianIndex` objects? Actually, `eachindex` for an array returns an iterator of linear indices by default? Let's check:
A = [1 2; 3 4]
eachindex(A) -> returns an iterator of linear indices (1:4) or CartesianIndices? Actually, `eachindex` returns an iterator that yields the indices in the order of the array. For a 2D array, it yields `CartesianIndex{2}`? Wait, in Julia 1.0 and above, `eachindex` returns an iterator that yields the Cartesian indices? Actually, the default `eachindex` for an array is `CartesianIndices(A)`. But then `for i in eachindex(A)` gives `CartesianIndex` objects? That's what I thought.
But then our `getindex` must accept `CartesianIndex`. So we define:
getindex(A::LazyDataset, ci::CartesianIndex) = ... # convert to linear and read.
And we don't need to define a method for `Integer`? Because `eachindex` yields `CartesianIndex`? But what about when someone does `for i in 1:length(A)`? Then `i` is an integer. So we must also support integer indexing for linear indexing.
So we need:
getindex(A::LazyDataset, i::Integer) # linear index
getindex(A::LazyDataset, ci::CartesianIndex) # Cartesian index
And we can also define the vararg version for convenience? But note: `A[1,2]` is not a `CartesianIndex`? It's two integers. So we can define:
getindex(A::LazyDataset, I::Vararg{Integer}) = getindex(A, CartesianIndex(I))
Then we have:
A[1] -> calls getindex(A, 1::Int) (linear)
A[1,2] -> calls getindex(A, 1,2) which is Vararg{Integer} -> converts to CartesianIndex(1,2) -> then to linear? But wait, we already have a method for CartesianIndex? Then we call that.
But then we have two steps: tuple to CartesianIndex, then CartesianIndex to linear.
Alternatively, we can compute the linear index from the tuple directly? But we already have the formula.
Let's design:
We'll have an internal function `_linear_index(A, ci)` that computes the linear index from a CartesianIndex.
Then:
getindex(A::LazyDataset, ci::CartesianIndex) = _read_element(A, _linear_index(A, ci))
getindex(A::LazyDataset, I::Vararg{Integer}) = getindex(A, CartesianIndex(I))
getindex(A::LazyDataset, i::Integer) = _read_element(A, i)
But wait, for `getindex(A::LazyDataset, i::Integer)` we don't check bounds? We should.
We can define:
function getindex(A::LazyDataset, i::Integer)
checkbounds(A, i)
_read_element(A, i)
end
Similarly for CartesianIndex.
But note: `checkbounds` for a linear index? We can do:
checkbounds(A, i)
And for CartesianIndex, we can do:
checkbounds(A, ci)
Now, the `_read_element` function:
function _read_element(A::LazyDataset, lin::Integer)
open(A.file, "r") do io
seek(io, (lin-1)*sizeof(eltype(A)))
return read(io, eltype(A))
end
end
But wait: we are opening the file every time? That's inefficient. We might want to keep the file open? But then we have to manage the IO object and close it eventually? And we have to worry about multiple threads? Since the dataset is read-only, we can keep the file open? But then if we have multiple instances of LazyDataset for the same file, we might open multiple file descriptors? That's okay? Or we can use a cache? But the problem says lazy-loaded, so we are allowed to read on demand.
However, opening and closing the file for every element is very slow.
We can store the IO object in the LazyDataset? But then we have to close it when the LazyDataset is finalized? We can use `finalizer`? But that's complicated.
Alternatively, we can use `mmap`? That would map the file into memory and then we can read from the memory? But then we are not really lazy because we are mapping the entire file? But if the file is too big to fit in memory, we can't use `mmap`? Actually, `mmap` doesn't load the entire file into memory at once, it pages in. So it's lazy in that sense.
But the problem says "lazy-loaded", so we might be allowed to use `mmap`? However, the problem says "lazy-loaded dataset" and we are to implement a custom `AbstractArray` interface. `mmap` in Julia returns an `MmapArray` which already is an `AbstractArray`. So we could just use that? But then we are not implementing our own.
Alternatively, we can open the file once and keep it open? But then we have to manage the lifetime.
Let's do:
We'll store the IO object in the LazyDataset, and we'll close it when the LazyDataset is garbage collected? We can use a finalizer.
But note: if we have multiple LazyDataset objects for the same file, they will each open the file? That might be okay.
However, we are going to implement:
struct LazyDataset{T, N} <: AbstractArray{T, N}
file::String
size::NTuple{N, Int}
io::IOStream # we'll open the file in the constructor and keep it open?
end
But then we have to open the file in the constructor. And then we have to close it? We can do:
function LazyDataset{T, N}(file::String, size::NTuple{N, Int}) where {T, N}
io = open(file, "r")
# set up finalizer to close the io
finalizer(_close_io, io) # but we need to attach finalizer to the LazyDataset, not the io? Actually, we can attach to the LazyDataset instance.
return new{T, N}(file, size, io)
end
But then we have to define a finalizer function that closes the io? And we have to be careful because the finalizer will be called when the LazyDataset is garbage collected.
Alternatively, we can not store the io and open and close every time? That is simpler but slow.
Given that the problem is about lazy-loading, we assume that we are going to access the dataset multiple times? So we want to keep the file open.
Let's do:
We'll store the io and use it for reading.
But then we have to worry about thread safety? If multiple threads access the same LazyDataset, we have to synchronize? We can use a lock? But that might be overkill.
Since the problem doesn't specify, we'll assume single-threaded access.
Steps:
- In the constructor, open the file and store the IO.
- In the finalizer, close the IO.
But note: if the file is closed by the finalizer, then if we try to use the LazyDataset after it's been garbage collected? We can't. So we must ensure that the LazyDataset stays alive as long as we are using it.
Alternatively, we can use `mmap` and let the operating system handle paging? That would be more efficient and we don't have to manage the file descriptor.
Let's consider using `mmap`:
We can use `Mmap.mmap` to map the file. Then we can treat the memory as an array? But the file is a binary file of T. We can create an `MmapArray`? But we want to implement our own.
We can do:
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{T} # this would be the entire dataset? No, we don't want to load everything.
Actually, if we use `mmap`, the entire file is mapped, but not loaded. So we can create a `Vector{T}` that is backed by the file? But then we are just wrapping an `MmapArray`? That's not implementing our own indexing.
Alternatively, we can store the `Mmap.AnonymousMmap`? Or the `Vector` that is the mmap? But then we are just using the mmap and we get the array for free? Then we don't need to implement `getindex` because we can just return the element from the mmap array.
But the problem says "define a custom `AbstractArray` interface", so we are expected to implement the methods ourselves.
So we'll do:
We'll store the mmap as a `Vector{UInt8}`? Then we can read the bytes and convert to T.
But then we are reading the bytes every time? That's similar to reading from a file.
Actually, with mmap, we can just do:
pointer = convert(Ptr{T}, pointer(mmapped_array, (lin-1)*sizeof(T)))
unsafe_load(pointer)
But that's unsafe and we have to be careful.
Alternatively, we can use `reinterpret`? But we don't want to create a new array.
Given the complexity, let's stick to reading from a file with an open IO.
But we want to keep the file open? We'll store the IO.
However, note: the file might be modified? We assume it's read-only.
Let's design:
struct LazyDataset{T, N} <: AbstractArray{T, N}
file::String
size::NTuple{N, Int}
io::IOStream
end
Constructor:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
io = open(file, "r")
# Check that the file size matches the expected size? We can do:
expected_bytes = prod(size) * sizeof(T)
actual_bytes = stat(file).size
if expected_bytes != actual_bytes
close(io)
error("File size does not match the expected size")
end
# Set up finalizer
finalizer(_close_io, io) # but we need to attach to the dataset? Actually, we can attach to the dataset object.
return LazyDataset{T, N}(file, size, io)
end
But we can't attach a finalizer to the `io` because it's a field? We can attach to the LazyDataset instance:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
io = open(file, "r")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = stat(file).size
if expected_bytes != actual_bytes
close(io)
error("File size does not match the expected size")
end
# Create the instance
d = LazyDataset{T, N}(file, size, io)
# Attach finalizer to d
finalizer(_close_io, d)
return d
end
_close_io(d::LazyDataset) = close(d.io)
But then the finalizer will run when `d` is garbage collected, and it will close the `io`. But note: the `io` is a field of `d`, so if `d` is collected, then `io` is also collected? Actually, the finalizer is called when the object is collected, and then we close the `io`. But the `io` is part of the object? We are closing the `io` while the object is being collected? That's okay.
But what if we have multiple references to the same `LazyDataset`? The finalizer will be called only once when the last reference is gone? And then the `io` will be closed, but if there are other references, they might try to use the closed `io`? That's a problem.
So we need reference counting? Or we can use a `ReentrantLock`? Alternatively, we can open and close on every access? That is safe but slow.
Given the complexity, and since this is an example, let's do the simple thing: open and close on every access.
We'll change:
_read_element(A::LazyDataset, lin::Integer) =
open(A.file, "r") do io
seek(io, (lin-1)*sizeof(eltype(A)))
return read(io, eltype(A))
end
Then we don't store the `io` in the struct.
But then we are opening and closing the file for every element. That is very slow.
Alternatively, we can cache the IO object per thread? Or we can use a global cache of open file descriptors? But that's complicated.
Given the constraints, let's do the simple version and note that it's inefficient for single element access.
But wait, the problem says "lazy-loaded", so we are only loading the element we need? But we are opening the file every time? That's not lazy, that's just on-demand.
However, we can improve by using a cache of the IO object? But then we have to manage it.
Alternatively, we can use `mmap` and then we don't have to open and close? Because the mmap is done once and then we can read from memory? But then we are mapping the entire file? That might be acceptable if the file is not too big? But the problem says the dataset is too big to fit in memory, but mmap doesn't load the entire file into memory at once, it pages in.
So let's use `Mmap.mmap` to map the entire file, and then we store the `Vector{UInt8}` of the entire file? But then we are storing the entire file in memory? No, the `Vector{UInt8}` from `mmap` is backed by the file and the pages are loaded on demand.
We can do:
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8} # the entire file as bytes, but via mmap
size::NTuple{N, Int}
end
Then in the constructor:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
expected_bytes = prod(size) * sizeof(T)
s = stat(file)
if s.size != expected_bytes
error("File size mismatch")
end
data = Mmap.mmap(open(file, "r"), Vector{UInt8}, s.size)
return LazyDataset{T, N}(data, size)
end
Then `getindex`:
function getindex(A::LazyDataset, lin::Integer)
checkbounds(A, lin)
offset = (lin-1)*sizeof(eltype(A))
# Read T from data at offset
return reinterpret(eltype(A), @view A.data[offset+1:offset+sizeof(eltype(A))])[1]
end
But `reinterpret` on a `SubArray`? We can do:
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{eltype(A)}(ptr))
But that's unsafe.
Alternatively, we can use:
T = eltype(A)
return read!(IOBuffer(@view A.data[offset+1:offset+sizeof(T)]), T)[1]
But that creates a buffer? Not efficient.
We can do:
function getindex(A::LazyDataset, lin::Integer)
checkbounds(A, lin)
T = eltype(A)
offset = (lin-1)*sizeof(T)
# We can use `reinterpret` on a `Vector{UInt8}`? Actually, we can create a `Ptr{T}` and then `unsafe_load`.
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
But note: `A.data` is a `Vector{UInt8}`, and `pointer(A.data)` returns a `Ptr{UInt8}`. We add `offset` (in bytes) and then convert to `Ptr{T}` and then `unsafe_load`.
This is safe as long as the file is not changed and we are within bounds.
But we have to check that `offset+sizeof(T) <= length(A.data)`? We already checked `lin` is within `1:length(A)`, so that should be okay.
However, `checkbounds` for linear index `lin` checks `1 <= lin <= length(A)`. And `length(A) = prod(A.size)`. So we are safe.
But what about for CartesianIndex? We convert to linear and then use the above.
So:
getindex(A::LazyDataset, ci::CartesianIndex) = getindex(A, LinearIndices(A)(ci))
And then we have:
getindex(A::LazyDataset, I::Vararg{Integer}) = getindex(A, CartesianIndex(I))
But wait, we have two methods: one for `Integer` and one for `Vararg{Integer}`? And `CartesianIndex`? We have:
getindex(A, lin::Integer) [for linear indexing]
getindex(A, ci::CartesianIndex) [for Cartesian indexing]
getindex(A, I::Vararg{Integer}) [for tuple of integers]
Then `A[1,2]` calls the third method, which converts to `CartesianIndex(1,2)` and then calls the second method? Then the second method converts to linear and calls the first? That's okay.
But then we have an extra function call.
Alternatively, we can compute the linear index in the third method and call the first method.
Let's do:
getindex(A::LazyDataset, I::Vararg{Integer}) =
let ci = CartesianIndex(I)
getindex(A, LinearIndices(A)(ci))
end
But that's still two steps.
We can compute the linear index directly from the tuple? We can use the same formula as before.
But let's use `LinearIndices` because it's built-in and we don't have to worry about the formula.
Now, we also need to implement `size` and `length`.
`size(A::LazyDataset) = A.size`
`length(A::LazyDataset) = prod(A.size)`
And `eltype(::LazyDataset{T}) where T = T`
We also need to implement iteration? Actually, the default iteration for an `AbstractArray` is to iterate over the linear indices (using `eachindex`). And `eachindex` returns an iterator of `CartesianIndex`? But then we call `getindex` with `CartesianIndex`? We already support that.
But wait, the default `eachindex` for an array returns `CartesianIndices(A)`, which is an iterator of `CartesianIndex`. So we don't need to implement `iterate`? Because `eachindex` is used by the default `iterate`? Actually, the default `iterate` for an array is:
iterate(A::AbstractArray, state=1) = state > length(A) ? nothing : (A[state], state+1)
That uses linear indexing. So if we support `getindex` with an integer (linear index), then we are fine.
But note: the default `eachindex` returns `CartesianIndices`, but the default `iterate` for an array (without `eachindex`) uses linear indexing? Let's check:
For a 2D array, `for x in A` will iterate over the linear indices? Actually, it will iterate in the order of the linear indices (column-major). So it calls `A[1]`, `A[2]`, ... which are linear indices.
So we must support `getindex` with an integer (linear index). We do.
Therefore, we don't need to implement `iterate` separately.
But wait, what about `eachindex`? We don't need to implement it because the default for `AbstractArray` is `eachindex(A) = CartesianIndices(A)`. But that returns `CartesianIndex` objects. Then when we do `for i in eachindex(A)`, we get `CartesianIndex` and then we call `A[i]`? That uses our `getindex` for `CartesianIndex`. So we must support that.
So we have:
getindex(A::LazyDataset, i::Integer) # linear
getindex(A::LazyDataset, ci::CartesianIndex) # Cartesian
And we also have the vararg method for convenience.
Now, let's put it all together.
We'll use `Mmap` for efficiency.
Steps:
using Mmap
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8} # the entire file mapped as bytes
size::NTuple{N, Int}
end
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
expected_bytes = prod(size) * sizeof(T)
s = stat(file)
if s.size != expected_bytes
error("File size (", s.size, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, s.size)
# We don't close the io because the mmap holds a reference? Actually, the mmap will keep the file open? We should close the io?
# From the Mmap documentation: the file is opened for reading and the mapping is created. The file is closed when the mapping is no longer referenced and the memory is unmapped? Actually, the `mmap` function takes an IO object and returns a vector. The vector holds the mapping. When the vector is garbage collected, the mapping is released and the file is closed? Not exactly: the `mmap` function does not close the IO? We have to close the IO? Actually, the example in the Mmap documentation:
# Example from Mmap:
# io = open("file.dat")
# data = Mmap.mmap(io, Vector{Int}, 1000)
# close(io) # the mapping remains valid
So we can close the `io` after mmap? Then the mapping remains valid? Yes, because the mapping is independent.
So:
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, s.size)
close(io) # we can close the file because the mapping is still valid.
Then we return LazyDataset(data, size).
But note: the `data` vector is now backed by the file, and we don't have an open file descriptor? Actually, the `mmap` system call creates a mapping and the file is not needed to be open? The mapping is associated with the file, and the file can be closed. The mapping remains until we unmap.
So we can close the `io` immediately.
Then we don't have to worry about closing the file in a finalizer? The `data` vector, when garbage collected, will unmap and close the file? Actually, the `Mmap` module handles that? When the vector is finalized, it calls `munmap` and then closes the file? I think so.
So we can just do:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
expected_bytes = prod(size) * sizeof(T)
s = stat(file)
if s.size != expected_bytes
error("File size (", s.size, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, s.size)
close(io)
return LazyDataset{T, N}(data, size)
end
But wait, we are closing the `io` immediately? Then the `data` vector is still valid? Yes, because the `mmap` call creates a mapping that is independent of the `io`? Actually, the `mmap` function in Julia's Mmap module does:
function mmap(io::IO, [T::Type{Array{C}},] dims::Integer...; grow::Bool=false, shared::Bool=true)
...
return MappedArray(...)
end
But we are using:
Mmap.mmap(io, Vector{UInt8}, s.size)
This returns a `Vector{UInt8}` that is mapped? Actually, it returns a `MappedVector`? But it is a subtype of `Vector{UInt8}`? Yes, it is a `Vector{UInt8}` with a special internal structure.
And when we close the `io`, the mapping remains? The documentation says:
The file is opened for reading and the mapping is created. The file is closed when the mapping is no longer referenced and the memory is unmapped.
So we don't have to keep the `io` open.
Therefore, we can close it right after.
So we don't need to store the `io` in the struct.
Now, we have:
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8} # the entire file mapped as bytes
size::NTuple{N, Int}
end
And then:
Base.size(A::LazyDataset) = A.size
Base.length(A::LazyDataset) = prod(A.size)
Base.eltype(::Type{LazyDataset{T, N}}) where {T, N} = T
For `getindex`:
function Base.getindex(A::LazyDataset, lin::Integer)
checkbounds(A, lin)
T = eltype(A)
offset = (lin-1)*sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
lin = LinearIndices(A)(ci)
return getindex(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer})
return getindex(A, CartesianIndex(I))
end
But note: the `getindex` for `CartesianIndex` will call `getindex` for `Integer`? So we have to be careful about infinite recursion? We have:
getindex(A, ci::CartesianIndex) -> getindex(A, lin) -> then the integer method.
That's fine.
However, we are using `unsafe_load` which is not type-stable? Actually, it returns `T` and we know the pointer is of type `Ptr{T}`.
But note: the file might not be aligned? But we are reading exactly `sizeof(T)` bytes. And we are reading from a `Vector{UInt8}` which is byte-aligned? So it should be okay.
But what about endianness? We assume the file is stored in the same endianness as the host? That's a limitation.
Now, we also need to implement `iterate`? Actually, the default `iterate` for arrays uses linear indexing, so we are fine.
But what about `eachindex`? We don't need to implement it because the default for `AbstractArray` is `eachindex(A) = CartesianIndices(A)`. And `CartesianIndices` works with our `size`.
However, we might want to override `eachindex` to return a `LazyDataset`-specific iterator? But we don't need to.
Let's test with a small example.
Example:
We have a file "data.bin" that contains 4 Float64: [1.0, 2.0, 3.0, 4.0] in binary, and we want a 2x2 array.
We create:
A = LazyDataset(Float64, (2,2), "data.bin")
Then:
A[1] -> 1.0
A[2] -> 3.0 because column-major? Wait, our linear indexing is column-major? We computed the linear index as:
linear = i1 + (i2-1)*d1
for (1,1): 1 + (1-1)*2 = 1 -> 1.0
for (2,1): 2 + (1-1)*2 = 2 -> 3.0? But wait, the second element in the file is 2.0? Actually, we stored the file as [1.0, 2.0, 3.0, 4.0]. So:
index 1: 1.0
index 2: 2.0
index 3: 3.0
index 4: 4.0
But in column-major for 2x2, the linear index for (2,1) is 2, so we get 2.0? That doesn't match the column-major order? Let me recalc:
We have a 2x2 array:
[1.0 2.0]
[3.0 4.0]
In memory (column-major):
column 1: [1.0, 3.0] -> indices 1 and 2? Actually, the first column is stored first: then the second column.
So the memory layout: 1.0, 3.0, 2.0, 4.0? That would be:
index1: (1,1) = 1.0
index2: (2,1) = 3.0
index3: (1,2) = 2.0
index4: (2,2) = 4.0
But our file has [1.0, 2.0, 3.0, 4.0] which is row-major? Because:
row1: 1.0, 2.0
row2: 3.0, 4.0
So if we want to store in column-major, we should store [1.0, 3.0, 2.0, 4.0].
Therefore, we have to be consistent.
Our `LazyDataset` assumes the file is in column-major order? Because we use the same linear index formula as Julia.
So if the file is in row-major, then we have to convert? Or we can change the formula.
Let's decide: we will assume the file is stored in the same order as Julia's internal (column-major). So the example file should be [1.0, 3.0, 2.0, 4.0].
But the user might have a row-major file? Then we have to transpose? But the problem doesn't specify.
Since we are defining a lazy dataset, we can let the user specify the order? But the problem doesn't say.
Alternatively, we can assume row-major? But then our linear index formula would be:
linear = iN + (i_{N-1}-1)*dN + ... ?
That's complicated.
Let's stick to column-major (Julia's order) because that's the default for Julia arrays.
So we require the file to be in column-major.
Now, let's write the code accordingly.
We'll also add a method for `show` to print some information.
But note: we are using `Mmap`, so we have to `using Mmap` in the module.
We'll write a module? Or just a function? The problem says "implement a Julia function that defines a custom AbstractArray interface". So we are to write a function that returns a `LazyDataset`? Or define the type and the interface?
The problem says: "Implement a Julia function that defines a custom `AbstractArray` interface"
That might mean: write a function that returns an instance of a type that implements the AbstractArray interface.
But we are defining a new type `LazyDataset` and its methods.
So we'll define:
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8}
size::NTuple{N, Int}
end
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
# ... as above
end
And then the methods.
But the problem says "function", singular. Maybe we are to write a function that creates the lazy array? Or we are to define the type and the methods.
I think we are to define the type and the interface.
Let's write the code accordingly.
We'll also consider that the file might be too big to get the size? But we are using `stat` which is fast.
Now, we have to be cautious: `Mmap.mmap` might fail if the file is empty? We are checking the size.
Also, we are using `unsafe_load` which is fast but we have to be careful about alignment? The `Vector{UInt8}` is byte-aligned, and `T` might require alignment? But `unsafe_load` will work even if the pointer is not aligned? It might be slower or cause a bus error? On x86, unaligned access is allowed but slower. But for `Float64` it's 8-byte aligned? Our offset is `(lin-1)*sizeof(T)`. If `lin` is 1, offset=0 -> aligned? If `sizeof(T)` is 8, then offset is multiple of 8? Only if `lin-1` is multiple of 1? Actually, every offset is multiple of `sizeof(T)`? Because we multiply by `sizeof(T)`. So if `T` is 8 bytes, then offset is multiple of 8? Only if `lin-1` is integer? Yes, so it's aligned? Because `sizeof(T)` is the alignment? Not necessarily, but for basic types it is.
So we are safe for basic types.
Now, let's write the code.
We'll also define `Base.show` to print something.
Let's do:
function Base.show(io::IO, A::LazyDataset)
print(io, "LazyDataset(", eltype(A), ", ", size(A), ")")
end
Now, we also need to handle the case when the user wants to index with a range? We don't support that. But the default for `AbstractArray` is to return a `SubArray`? And `SubArray` will try to call `getindex` with the converted indices? That would be a tuple of integers? Actually, when you do `A[1:2, 1]` on a 2D array, it returns a 2x1 array? The `SubArray` will have its own `getindex` that uses the parent's `getindex` with the converted indices? But the converted indices are a tuple of `UnitRange`? That's not integers.
So we have to support `getindex` with `AbstractArray{Bool}`? Or with `CartesianIndices`? Actually, the `SubArray` uses `to_indices` which converts the indexing to a tuple of `CartesianIndex`? I'm not sure.
Given the complexity, we'll only support integer indexing and CartesianIndex. For other indexing, we can fallback to the default? But the default `getindex` for `AbstractArray` uses `to_indices` and then calls `getindex` with the converted indices? But if we don't define a method for that, it will error.
Alternatively, we can define:
getindex(A::LazyDataset, I...) =
throw(ArgumentError("LazyDataset only supports integer indexing"))
But then we break the `SubArray`? Because `SubArray` will try to call `getindex` with a tuple of `UnitRange`? That would be `I...` being a tuple of ranges? Then we throw.
So we cannot support subarrays? That's a limitation.
We can try to support `getindex` with `AbstractArray` indices? That would be very complex.
Given the problem, maybe we are only required to support single element access and iteration? The problem says "indexing, iteration". Indexing might mean single element? And iteration means `for x in A`.
So we can leave it at that.
But note: `eachindex` returns `CartesianIndices`, which are `CartesianIndex` objects. We support that.
And `for i in 1:length(A)` uses linear integers? We support that.
So we are okay.
Let's write the code accordingly.
One more thing: we are using `Mmap` and `unsafe_load`. We have to be careful about the element type `T` being bits type? Because we are reading raw bytes. So we must restrict `T` to be a `BitsType`? Actually, we can only read bits types from a binary file.
We can add a trait:
isbits(T) || error("LazyDataset only supports isbits types")
But we can do that in the constructor.
Alternatively, we can define:
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8}
size::NTuple{N, Int}
function LazyDataset{T, N}(data::Vector{UInt8}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
new{T, N}(data, size)
end
end
And then in the outer constructor:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
s = stat(file)
if s.size != expected_bytes
error("File size (", s.size, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, s.size)
close(io)
return LazyDataset{T, N}(data, size)
end
But note: we are closing the `io` after mmap? Yes.
Now, we have to test.
Let's write a test:
using Test
# Create a temporary file with 4 Float64: [1.0, 2.0, 3.0, 4.0] in row-major? Actually, we want column-major for 2x2? So we write [1.0, 3.0, 2.0, 4.0]?
But let's write a function to write a matrix in column-major.
We'll write:
open("test.bin", "w") do io
write(io, [1.0, 3.0, 2.0, 4.0])
end
Then:
A = LazyDataset(Float64, (2,2), "test.bin")
@test A[1] == 1.0
@test A[2] == 3.0
@test A[3] == 2.0
@test A[4] == 4.0
@test A[1,1] == 1.0
@test A[2,1] == 3.0
@test A[1,2] == 2.0
@test A[2,2] == 4.0
And iteration:
@test collect(A) == [1.0, 3.0, 2.0, 4.0]
But note: `collect` on a 2D array returns a vector in column-major order? Yes.
So it should work.
Now, let's write the code.
We'll put everything in a module? Or just define the type and functions.
Since the problem says "implement a Julia function", maybe we are to write a function that returns the lazy array? But we are defining a type.
I think we are to define the type and the interface.
So we'll write:
using Mmap
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8}
size::NTuple{N, Int}
function LazyDataset{T, N}(data::Vector{UInt8}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
new{T, N}(data, size)
end
end
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
s = stat(file)
if s.size != expected_bytes
error("File size (", s.size, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, s.size)
close(io)
return LazyDataset{T, N}(data, size)
end
Base.size(A::LazyDataset) = A.size
Base.length(A::LazyDataset) = prod(A.size)
Base.eltype(::Type{LazyDataset{T, N}}) where {T, N} = T
function Base.getindex(A::LazyDataset, lin::Integer)
checkbounds(A, lin)
T = eltype(A)
offset = (lin-1)*sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
lin = LinearIndices(A)(ci)
return getindex(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer})
return getindex(A, CartesianIndex(I))
end
Base.show(io::IO, A::LazyDataset) =
print(io, "LazyDataset(", eltype(A), ", ", size(A), ")")
But wait, we are using `stat` from `Base.Filesystem`? We have to import it.
Alternatively, we can use `filesize` from `FileOperations`? Actually, `stat` is in `Base.Filesystem`, but we can use `filesize`? `filesize` returns the size in bytes.
Let's use `filesize(file)`.
So:
s = filesize(file)
Then we don't need to open the file to get the size.
But note: `filesize` might throw if the file doesn't exist.
So:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, actual_bytes)
close(io)
return LazyDataset{T, N}(data, size)
end
But wait, `Mmap.mmap` can take the length? We have `actual_bytes` and we know it's the same as `expected_bytes`.
Alternatively, we can use:
data = Mmap.mmap(io, Vector{UInt8}, (expected_bytes,))
But we have `expected_bytes` and `actual_bytes` are the same.
So:
data = Mmap.mmap(io, Vector{UInt8}, (expected_bytes,))
But note: `Mmap.mmap` expects the dimensions? For a vector, we can give an integer for the length? Actually, the syntax is:
Mmap.mmap(io, [T], dims...; ...)
So we can do:
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
That creates a vector of length `expected_bytes`.
But we are using `Vector{UInt8}`, which is a 1D array of bytes.
So:
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
Then we don't need to pass the tuple? Because `Vector{UInt8}` is 1-dimensional? And `expected_bytes` is the length.
So:
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
Then `length(data) == expected_bytes`.
So we can do:
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
But then we are using `expected_bytes` which we already checked.
So:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
close(io)
return LazyDataset{T, N}(data, size)
end
But note: `Mmap.mmap` returns a `Vector{UInt8}` that is mapped? Yes.
Now, we are done.
However, we are not handling the case when the file is not readable? The `open` will throw.
Also, we are not handling the case when `expected_bytes` is 0? Then `Mmap.mmap` might fail? But if the file is empty, then `expected_bytes` is 0? Then we can't map? We can handle that by returning an empty vector? But then `prod(size)` might be 0? That's okay.
But if `expected_bytes` is 0, then `filesize(file)` must be 0? Then we can skip the mapping? Actually, `Mmap.mmap` with length 0? Let's check:
Mmap.mmap(io, Vector{UInt8}, 0) -> returns an empty vector? I think so.
So we are okay.
Let's write the code accordingly.
But note: we are using `filesize` which might not be available on all platforms? It is in Base.
Now, we have to export the type? The problem doesn't say.
We'll just define the type and the constructor.
One more thing: we are using `unsafe_load`. We have to make sure that the pointer is valid and the memory is mapped? Since we are using `Mmap`, it is.
But what about the alignment? As we said, the offset is a multiple of `sizeof(T)`, so it should be aligned for `T`.
So we are safe.
Let's write the final code.
However, note: the `getindex` for `CartesianIndex` uses `LinearIndices(A)(ci)`. This creates a `LinearIndices` object every time? We can precompute the strides? But `LinearIndices` is cheap? It's just a tuple of sizes? Actually, `LinearIndices` is defined as:
struct LinearIndices{A} <: AbstractArray{Int, 1}
parent::A
end
(::LinearIndices)(ci::CartesianIndex) = ...
So it's a lightweight struct. We can compute the linear index ourselves to avoid the allocation? But it's probably fine.
Alternatively, we can compute:
function _linear_index(A::LazyDataset, ci::CartesianIndex)
N = length(ci)
@inbounds begin
lin = 1
stride = 1
for j in 1:N
lin += (ci[j] - 1) * stride
stride *= A.size[j]
end
end
return lin
end
Then:
getindex(A::LazyDataset, ci::CartesianIndex) = getindex(A, _linear_index(A, ci))
But then we are duplicating the logic.
Let's use `LinearIndices` for clarity.
But note: `LinearIndices` might be slower? We can benchmark later.
For now, we'll use `LinearIndices`.
Code:
using Mmap
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8}
size::NTuple{N, Int}
function LazyDataset{T, N}(data::Vector{UInt8}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
new{T, N}(data, size)
end
end
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
close(io)
return LazyDataset{T, N}(data, size)
end
Base.size(A::LazyDataset) = A.size
Base.length(A::LazyDataset) = prod(A.size)
Base.eltype(::Type{LazyDataset{T, N}}) where {T, N} = T
function Base.getindex(A::LazyDataset, lin::Integer)
checkbounds(A, lin)
T = eltype(A)
offset = (lin-1)*sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
lin = LinearIndices(A)(ci)
return getindex(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer})
return getindex(A, CartesianIndex(I))
end
Base.show(io::IO, A::LazyDataset) =
print(io, "LazyDataset(", eltype(A), ", ", size(A), ")")
But wait, we are using `filesize` which is defined in `Base.Filesystem`? Actually, `filesize` is in `Base`? Yes, `Base.filesize`.
We don't need to import anything else.
Now, we have to test.
However, note: the `getindex` for `CartesianIndex` might be inefficient because it creates a `LinearIndices` object? We can compute the linear index without allocation? But for simplicity, we'll leave it.
Alternatively, we can define:
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
N = length(ci)
@inbounds begin
lin = 1
stride = 1
for j in 1:N
lin += (ci[j] - 1) * stride
stride *= A.size[j]
end
end
return getindex(A, lin)
end
But then we are duplicating the `LinearIndices` logic. And if Julia changes the formula, we have to update.
Let's stick to `LinearIndices`.
But note: `LinearIndices` uses the same formula? Yes.
So we are safe.
Now, we have to consider the performance: every time we index with a `CartesianIndex`, we create a `LinearIndices` object? That might be a small allocation.
We can precompute the `LinearIndices` and store it? But then we are storing an extra object per `LazyDataset`? We can compute it on the fly? It's cheap.
Alternatively, we can compute the linear index without allocation:
function _linear_index(A::LazyDataset, ci::CartesianIndex)
N = length(A.size)
@inbounds begin
lin = 1
stride = 1
for j in 1:N
lin += (ci[j] - 1) * stride
stride *= A.size[j]
end
end
return lin
end
Then:
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
lin = _linear_index(A, ci)
return getindex(A, lin)
end
But then we are not using `checkbounds` for the CartesianIndex? We are only checking for the linear index? But `checkbounds` for the linear index will check `1 <= lin <= length(A)`. That is equivalent to checking the CartesianIndex? Not exactly, because the CartesianIndex might have an index that is within the size but the linear index might be out of bounds? Actually, if `ci` is within `1 .<= ci .<= A.size`, then the computed `lin` will be between 1 and `length(A)`. So we are safe.
But we are not checking the CartesianIndex against the size? We are only checking the linear index? That might miss a check if the CartesianIndex has an index that is too large? For example, if `ci = (3,1)` for a 2x2 array, then `lin = 3 + (1-1)*2 = 3`? But `3` is within 1:4? So it's okay? But `ci[1]` is 3 which is larger than `A.size[1]` which is 2. So we should check the CartesianIndex.
We can do:
checkbounds(A, ci)
Then we compute the linear index? But `checkbounds` for `CartesianIndex` will check against `A.size`.
So we can do:
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
checkbounds(A, ci)
lin = _linear_index(A, ci)
return getindex(A, lin)
end
But then we are doing two checks? One in `checkbounds` and one in `getindex(A, lin)`? That's okay.
Alternatively, we can only do `checkbounds(A, lin)` and rely on the fact that if `ci` is out of bounds, then `lin` might be out of bounds? But that's not guaranteed? For example, if `ci = (0,1)`, then `lin = 0 + (1-1)*2 = 0`? Then `checkbounds(A, 0)` will throw. So we are safe.
But what if `ci = (3,1)` for a 2x2? `lin = 3 + (1-1)*2 = 3`? Then `checkbounds(A, 3)` will pass because 3 is in 1:4. But `ci[1]` is 3 which is out of bounds? So we miss the check.
Therefore, we must check the CartesianIndex.
So we do:
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
checkbounds(A, ci)
lin = _linear_index(A, ci)
return getindex(A, lin)
end
And then in `getindex(A, lin)` we also check? That's redundant? We can skip the check in `getindex(A, lin)` when called from `getindex(A, ci)`? But we also call `getindex(A, lin)` from the integer method? So we need the check there.
Alternatively, we can have:
getindex(A::LazyDataset, lin::Integer) =
@boundscheck checkbounds(A, lin); _read_element(A, lin)
getindex(A::LazyDataset, ci::CartesianIndex) =
@boundscheck checkbounds(A, ci); getindex(A, _linear_index(A, ci))
But then `getindex(A, lin)` will check again? We can avoid by having a `_read_element` that doesn't check.
Let's do:
function _read_element(A::LazyDataset, lin::Integer)
T = eltype(A)
offset = (lin-1)*sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, lin::Integer)
@boundscheck checkbounds(A, lin)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
@boundscheck checkbounds(A, ci)
lin = _linear_index(A, ci)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer})
return getindex(A, CartesianIndex(I))
end
Now, we have `_linear_index`:
function _linear_index(A::LazyDataset, ci::CartesianIndex)
N = length(ci)
@inbounds begin
lin = 1
stride = 1
for j in 1:N
lin += (ci[j] - 1) * stride
stride *= A.size[j]
end
end
return lin
end
But note: `length(ci)` should be equal to `length(A.size)`. We assume that because `CartesianIndex` for an array of dimension `N` has length `N`.
We can also use `LinearIndices` to avoid writing our own? But we want to avoid allocation? `LinearIndices` allocates? Let's see:
LinearIndices(A) returns a `LinearIndices` object (a struct) that is small. Then calling it with a `CartesianIndex` does the computation.
So we can do:
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
@boundscheck checkbounds(A, ci)
lin = LinearIndices(A)(ci)
return _read_element(A, lin)
end
That's simpler.
We'll do that.
Final code:
using Mmap
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8}
size::NTuple{N, Int}
function LazyDataset{T, N}(data::Vector{UInt8}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
new{T, N}(data, size)
end
end
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
close(io)
return LazyDataset{T, N}(data, size)
end
Base.size(A::LazyDataset) = A.size
Base.length(A::LazyDataset) = prod(A.size)
Base.eltype(::Type{LazyDataset{T, N}}) where {T, N} = T
function _read_element(A::LazyDataset, lin::Integer)
T = eltype(A)
offset = (lin-1)*sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, lin::Integer)
@boundscheck checkbounds(A, lin)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
@boundscheck checkbounds(A, ci)
lin = LinearIndices(A)(ci)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer})
return getindex(A, CartesianIndex(I))
end
Base.show(io::IO, A::LazyDataset) =
print(io, "LazyDataset(", eltype(A), ", ", size(A), ")")
Now, we are done.
However, we are not handling the case when the file is not a multiple of `sizeof(T)`? We already check that.
Also, we are not handling the case when `T` is not a bits type? We check with `isbits`.
But note: `isbits` returns true for primitive types and some structs? But we are reading raw bytes, so we need the representation to be the same as the file? That's the user's responsibility.
We assume the file is written in the same binary format as the host.
Now, let's test with a 1D array.
Example:
write a file with 3 Int32: [1,2,3]
A = LazyDataset(Int32, (3,), "test.bin")
A[1] == 1
A[2] == 2
A[3] == 3
And 3D? We don't test.
We'll leave it at that.
One more thing: the `LazyDataset` constructor takes the size as a tuple. We can also infer the size from the file? But the user must provide it because the file might not have shape information.
So we require the user to provide the size.
Now, we have implemented the `AbstractArray` interface: `size`, `getindex`, and by extension `iterate` (via linear indexing) and `eachindex` (via `CartesianIndices`).
We are done.
But note: we are using `Mmap.mmap` with `Vector{UInt8}` and then reading with `unsafe_load`. This is efficient because we are not copying the data until we access it? Actually, `mmap` maps the file and when we access a page, it loads that page. And `unsafe_load` reads from the mapped memory.
So it's lazy: we only load the pages that we access.
Therefore, we have a lazy-loaded dataset.
Let me write the code in a single block.
Note: We must `using Mmap` in the code. If this is part of a module, we have to import Mmap.
Since the problem says "implement a Julia function", we might be writing a function that returns a `LazyDataset`? But we are defining a type.
I think we are to define the type and the constructor.
So we'll write:
using Mmap
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8}
size::NTuple{N, Int}
function LazyDataset{T, N}(data::Vector{UInt8}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
new{T, N}(data, size)
end
end
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
close(io)
return LazyDataset{T, N}(data, size)
end
Base.size(A::LazyDataset) = A.size
Base.length(A::LazyDataset) = prod(A.size)
Base.eltype(::Type{LazyDataset{T, N}}) where {T, N} = T
function _read_element(A::LazyDataset, lin::Integer)
T = eltype(A)
offset = (lin-1)*sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, lin::Integer)
@boundscheck checkbounds(A, lin)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
@boundscheck checkbounds(A, ci)
lin = LinearIndices(A)(ci)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer})
return getindex(A, CartesianIndex(I))
end
Base.show(io::IO, A::LazyDataset) =
print(io, "LazyDataset(", eltype(A), ", ", size(A), ")")
We are done.
However, note: the `LazyDataset` constructor does not close the `io` if `mmap` fails? We are closing it after `mmap`? But if `mmap` throws, we don't close? We can use `do` block? But we are using `open` and then `close`? We can do:
io = open(file, "r")
try
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
finally
close(io)
end
But then if `mmap` succeeds, we close the `io` and then return the `LazyDataset` with `data`? That's okay because the mapping is independent.
But what if `mmap` fails? Then we close the `io` and rethrow.
So:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
try
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
finally
close(io)
end
return LazyDataset{T, N}(data, size)
end
But note: if `mmap` fails, we still close the `io`? And then we don't have `data`? We should rethrow? The `try` block will rethrow after `finally`? Actually, if `mmap` throws, then `data` is not defined, and then we return? We don't want to return. So we can:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
close(io)
return LazyDataset{T, N}(data, size)
end
But if `mmap` fails, we don't close the `io`? We can use `do`:
open(file, "r") do io
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
return LazyDataset{T, N}(data, size)
end
But then the `return` inside the `do` block returns from the `do` block, not from the outer function? Actually, it returns from the `do` block, which is the last expression? And then the outer function returns that?
Let's see:
function f()
open("file", "r") do io
data = ...
return something
end
end
The `do` block is passed to `open` and the return value of the `do` block becomes the return value of `open`? Then `f` returns that.
So we can do:
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
open(file, "r") do io
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
return LazyDataset{T, N}(data, size)
end
end
Then the `io` is closed automatically when the `do` block exits? Yes, `open` with a function argument will close the `io` when the function returns? Actually, `open(f, file)` opens the file, passes the `IO` to `f`, and then closes the `IO` when `f` returns? Yes.
But note: the `mmap` creates a mapping that is independent of the `io`? So we can close the `io` immediately after `mmap`? But we are returning from the `do` block, so the `io` will be closed after we return the `LazyDataset`? That's okay because the `data` is already mapped.
So:
open(file, "r") do io
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
# now we have `data` and we return the LazyDataset.
return LazyDataset{T, N}(data, size)
end
Then the `io` is closed when we exit the `do` block? But the `data` is still valid? Yes.
So we don't need to worry about closing.
Let's change to that.
Final code:
using Mmap
struct LazyDataset{T, N} <: AbstractArray{T, N}
data::Vector{UInt8}
size::NTuple{N, Int}
function LazyDataset{T, N}(data::Vector{UInt8}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
new{T, N}(data, size)
end
end
function LazyDataset(file::String, ::Type{T}, size::NTuple{N, Int}) where {T, N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
if actual_bytes != expected_bytes
error("File size (", actual_bytes, " bytes) does not match expected (", expected_bytes, " bytes)")
end
open(file, "r") do io
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
return LazyDataset{T, N}(data, size)
end
end
Base.size(A::LazyDataset) = A.size
Base.length(A::LazyDataset) = prod(A.size)
Base.eltype(::Type{LazyDataset{T, N}}) where {T, N} = T
function _read_element(A::LazyDataset, lin::Integer)
T = eltype(A)
offset = (lin-1)*sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, lin::Integer)
@boundscheck checkbounds(A, lin)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex)
@boundscheck checkbounds(A, ci)
lin = LinearIndices(A)(ci)
return _read_element(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer})
return getindex(A, CartesianIndex(I))
end
Base.show(io::IO, A::LazyDataset) =
print(io, "LazyDataset(", eltype(A), ", ", size(A), ")")
Now, we are done.
But note: we are using `unsafe_load` which is not thread-safe? Actually, `unsafe_load` is safe as long as the pointer is valid and we are not concurrently modifying? But we are only reading.
However, if multiple threads call `getindex` on the same `LazyDataset`, they will read from the same memory? That's safe because it's read-only.
But the `mmap` might have been set up with `shared=true` (default) so it's safe.
So we are okay.
We can also add a method for `Base.IndexStyle(::Type{<:LazyDataset}) = IndexLinear()`? But we support both linear and Cartesian? Actually, we support both, but the default `IndexStyle` for arrays is `IndexCartesian()`? Wait, for a multi-dimensional array, the default is `IndexCartesian()`. But we support linear indexing? Yes, but the default `iterate` uses linear indexing? Actually, the default `iterate` for an array uses linear indexing? And `eachindex` returns `CartesianIndices`. So we are supporting both.
We don't need to specify `IndexStyle` because we are supporting both? Actually, the `IndexStyle` trait is used to decide which indexing method to use? But we have defined both `getindex` for integer and for `CartesianIndex`. So we are fine.
However, if someone uses `@inbounds` and `@simd`? They might use linear indexing? We support that.
So we are done.
Let me write the code in a formatted way.
We'll assume the user will `using Mmap`? Or we can do `using Mmap: mmap`? We are using `Mmap.mmap`.
We can write:
using Mmap
at the top.
Now, we provide the code.
Note: we are using `filesize` from `Base`. So we don't need any extra imports.
Final code.</think>
Here's a complete implementation of a lazy-loaded dataset as a custom AbstractArray in Julia. This implementation uses memory-mapped files for efficient on-demand loading:
using Mmap
struct LazyDataset{T,N} <: AbstractArray{T,N}
file::String
size::NTuple{N,Int}
data::Vector{UInt8} # Memory-mapped byte buffer
function LazyDataset{T,N}(file::String, size::NTuple{N,Int}) where {T,N}
isbits(T) || error("LazyDataset only supports isbits types")
expected_bytes = prod(size) * sizeof(T)
actual_bytes = filesize(file)
actual_bytes == expected_bytes ||
error("File size ($actual_bytes bytes) doesn't match expected ($expected_bytes bytes)")
io = open(file, "r")
data = Mmap.mmap(io, Vector{UInt8}, expected_bytes)
close(io) # Close file descriptor, mapping remains valid
new{T,N}(file, size, data)
end
end
# Constructor with type inference
LazyDataset(file::String, ::Type{T}, size::NTuple{N,Int}) where {T,N} =
LazyDataset{T,N}(file, size)
# Array interface
Base.size(A::LazyDataset) = A.size
Base.length(A::LazyDataset) = prod(A.size)
Base.eltype(::Type{LazyDataset{T,N}}) where {T,N} = T
Base.ndims(::Type{<:LazyDataset{T,N}}) where {T,N} = N
# Indexing support
function Base.getindex(A::LazyDataset, lin::Integer)
@boundscheck checkbounds(A, lin)
T = eltype(A)
offset = (lin - 1) * sizeof(T)
ptr = pointer(A.data) + offset
return unsafe_load(Ptr{T}(ptr))
end
function Base.getindex(A::LazyDataset, ci::CartesianIndex{N}) where N}
@boundscheck checkbounds(A, ci)
lin = LinearIndices(A)(ci)
return getindex(A, lin)
end
function Base.getindex(A::LazyDataset, I::Vararg{Integer,N}) where N}
return getindex(A, CartesianIndex(I))
end
# Optional: support for ranges and colonization via fallback to default behavior
# The default SubArray handling will work for ranges if we also implement:
function Base.getindex(A::LazyDataset, I::Vararg{Union{Integer,Colon,AbstractRange}})
# Convert to Cartesian indices and read subarray
# This is a simplified version - full implementation would handle
# arbitrary indexing patterns efficiently
inds = to_indices(A, I)
# Convert to linear indices and read (eager for subarrays)
# For true laziness with subarrays, would need to return another LazyDataset
return getindex.(Ref(A), inds...)
end
# Iteration (default uses linear indexing)
# No need to implement `iterate` explicitly - defaults work via getindex(::Int)
# Display
function Base.show(io::IO, A::LazyDataset)
print(io, "LazyDataset(", eltype(A), ", ", size(A), ")")
end
# Optional: convenience function to create from a file with inferred size
function LazyDataset(file::String, ::Type{T}) where T
# Infer size from file length (requires knowing element count)
# This is just an example - real usage would need element count or shape metadata
s = filesize(file)
n = s ÷ sizeof(T)
LazyDataset(file, T, (n,))
end
Key Features:
- Memory-mapped I/O: Uses
Mmap.mmap to map file into virtual memory (pages loaded on-demand by OS)
- Type-stable: Generic over element type
T and dimensionality N
- Bounds-checked: Uses
@boundscheck and checkbounds properly
- Efficient indexing:
- Linear indexing:
A[i] → direct pointer arithmetic
- Cartesian indexing:
A[i,j] → converts to linear via LinearIndices
- Tuple indexing:
A[i,j,k] → converts to CartesianIndex
- Lazy: Only accesses disk when elements are actually read
- Safe: File descriptor closed after mapping (OS maintains mapping)
Usage Example:
# Create a binary file (for testing)
open("data.bin", "w") do io
write(io, rand(Float64, 1000)) # 1000 Float64 values
end
# Create lazy dataset (2D array 20×50)
A = LazyDataset("data.bin", Float64, (20, 50))
# Access works as normal array
println(A[1,1]) # Loads first element
println(A[10]) # Linear index 10 (column-major order)
println(size(A)) # (20, 50)
# Iteration (loads elements on demand)
sum = zero(Float64)
for x in A
sum += x
end
# Works with array operations (creates temporary arrays for results)
B = A .+ 1.0 # This will load all elements! Use with caution.
Important Notes:
- File format: Assumes raw binary file with column-major (Julia-style) layout
- Element type: Must be
isbits types (primitives, immutable structs with isbits fields)
- Subarray indexing: The
getindex with ranges/colon shown creates a temporary dense array. For truly lazy subarrays, you'd return another LazyDataset with an offset and strided view (more complex).
- Thread safety:
unsafe_load is thread-safe for read-only access, but concurrent reads from same mapping may cause page faults.
- File modifications: The file must not change while mapped - memory mapping assumes stable file content.
This implementation provides a balance of efficiency, safety, and Julia's array interface compliance while maintaining true laziness through OS-level demand paging.