@trust is an encapsulation method, not an escape
Zach the Mystic via Digitalmars-d
digitalmars-d at puremagic.com
Fri Feb 6 22:03:00 PST 2015
On Saturday, 7 February 2015 at 01:43:01 UTC, Andrei Alexandrescu
wrote:
> With the system proposal we're looking at something like:
>
> version (Posix) void[] read(in char[] name, size_t upTo =
> size_t.max) @trusted
> {
> import core.memory;
> // A few internal configuration parameters {
> enum size_t
> minInitialAlloc = 1024 * 4,
> maxInitialAlloc = size_t.max / 2,
> sizeIncrement = 1024 * 16,
> maxSlackMemoryAllowed = 1024;
> // }
>
> @system
> {
> immutable fd =
> core.sys.posix.fcntl.open(name.tempCString(),
> core.sys.posix.fcntl.O_RDONLY);
> }
> cenforce(fd != -1, name);
> scope(exit) core.sys.posix.unistd.close(fd);
>
> stat_t statbuf = void;
> @system
> {
> cenforce(trustedFstat(fd, trustedRef(statbuf)) == 0,
> name);
> }
>
> immutable initialAlloc = to!size_t(statbuf.st_size
> ? min(statbuf.st_size + 1, maxInitialAlloc)
> : minInitialAlloc);
> void[] result = uninitializedArray!(ubyte[])(initialAlloc);
> scope(failure) delete result;
> size_t size = 0;
>
> for (;;)
> {
> @system
> {
> immutable actual = core.sys.posix.unistd.read(fd,
> result.ptr + size),
> min(result.length, upTo) - size);
> }
> cenforce(actual != -1, name);
> if (actual == 0) break;
> size += actual;
> if (size < result.length) continue;
> immutable newAlloc = size + sizeIncrement;
> @system
> {
> result = GC.realloc(result.ptr, newAlloc,
> GC.BlkAttr.NO_SCAN)[0 .. newAlloc];
> }
>
> @system
> {
> return result.length - size >= maxSlackMemoryAllowed
> ? GC.realloc(result.ptr, size,
> GC.BlkAttr.NO_SCAN)[0 .. size]
> : result[0 .. size];
> }
> }
>
> We want to move D forward, folks. This is not it.
>
>
> Andrei
Oh I see. There are three posts, in the latter two of which the
little @trusted functions are already removed. I had thought they
were all identical, but you obviously realized the little
functions should be removed.
More information about the Digitalmars-d
mailing list