std.file.read implementation contest
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Mon Feb 16 15:10:39 PST 2009
Steven Schveighoffer wrote:
> "Andrei Alexandrescu" wrote
>> Steven Schveighoffer wrote:
>>> "Andrei Alexandrescu" wrote
>>>> Someone mentioned an old bug in std.file.read here:
>>>>
>>>> http://www.reddit.com/r/programming/comments/7xnty/walter_bright_on_porting_d_to_the_mac/
>>>>
>>>> Two programmers sent in patches for the function. Which is to be
>>>> committed and why? (Linux versions shown. Apologies for noisy line
>>>> breaks.)
>>> Implementation 2, save 1 bug:
>> [snip]
>>
>> Aha, cool. Thanks for the info. I've adapted the code to still only use
>> one loop:
>>
>> void[] read(string name)
>> {
>> immutable fd = std.c.linux.linux.open(toStringz(name), O_RDONLY);
>> cenforce(fd != -1, name);
>> scope(exit) std.c.linux.linux.close(fd);
>>
>> struct_stat statbuf = void;
>> cenforce(std.c.linux.linux.fstat(fd, &statbuf) == 0, name);
>>
>> immutable initialAlloc = statbuf.st_size
>> ? (statbuf.st_size + 16) & 15
>> : 1024;
>
> Hm... won't this allocate only 15 bytes max if st_size is nonzero?
>
> I think you meant:
> (statbuf.st_size + 16) & ~15
Stupid!!!
> Two more points:
>
> if you allocate a size of 16, I think you'll actually get 32 bytes because
> of the sentinel byte. Somehow you should account for that, or you
> automatically double the allocation size each time (or at least a page more
> than you want).
>
> And the increments are not in 16, they are in powers of 2 *starting* with
> 16. For example, if you allocate a size of 80 bytes (16 * 5), you will
> actually get 128 bytes.
>
> Other than that, it looks good.
Guess I'll revert to +1. The effect is likely to be negligible anyway.
Thanks!
Andrei
More information about the Digitalmars-d
mailing list