An important pull request: accessing shared affix for immutable data
ZombineDev via Digitalmars-d
digitalmars-d at puremagic.com
Sat Feb 13 10:44:36 PST 2016
On Friday, 12 February 2016 at 23:29:58 UTC, Timon Gehr wrote:
> The first thing that comes to mind is that accessing a global
> associative array is not 'pure'.
Not necessarily. Purity depends on the allocator and how you
access it (via parameter or through a static/shared instance).
I have this code in my project: (note **pure** unittest)
/// UniqueRef is encapsulates T* or T (if (is(T == A[], A))
/// It is designed to ensure unique ownership and to
/// provide transparent access to its payload
struct UniqueRef(T, alias Allocator = Mallocator)
if (isScalarValueType!T || isDynamicArray!T)
{ /* ... */ }
///
pure nothrow @safe
// not @nogc because the alias template parameter cause GC
context allocation :(
// Maybe make the Allocator a ctor parameter of UniqueRef?
unittest
{
// Test forwarding of operators for arrays of user defined
types
auto allocator = MyStackAllocator!1024();
assert (allocator.usedBytes == 0);
assert (allocator.allocationCount == 0);
{
auto arr = UniqueRef!(Vec3[], allocator)(4);
assert (arr.length == 4);
assert (arr.ptr !is null);
assert (arr.ptr == allocator.bytes.ptr);
assert (allocator.usedBytes == 4 * Vec3.sizeof);
assert (allocator.allocationCount == 1);
arr[] = Vec3(3, 2, 1);
Vec3[4] expected1 = [
Vec3(3, 2, 1), Vec3(3, 2, 1),
Vec3(3, 2, 1), Vec3(3, 2, 1)
];
assert (arr[] == expected1);
arr[] += Vec3(1, 1, 1);
Vec3[4] expected2 = [
Vec3(4, 3, 2), Vec3(4, 3, 2),
Vec3(4, 3, 2), Vec3(4, 3, 2)
];
assert (arr[] == expected2);
}
assert (allocator.usedBytes == 0);
assert (allocator.allocationCount == 0);
}
I think I can accomodate a SharedRef that uses the proposed affix
allocator fairly easily in my current design. And it would still
be conditionally pure (depending on the payload). I just haven't
found the need to share ownership in my project yet.
More information about the Digitalmars-d
mailing list