December 15, 2020
On Monday, 14 December 2020 at 23:55:09 UTC, Steven Schveighoffer wrote:
> Yes, you can use .ptr to avoid bounds checks, and it's safe if you do it correctly.

Though doing it correctly may be harder than you'd think:

https://gist.github.com/pbackus/39b13e8a2c6aea0e090e4b1fe8046df5#example-short-string
December 15, 2020
On Monday, 14 December 2020 at 20:53:39 UTC, Jackson22 wrote:
> On Monday, 14 December 2020 at 01:36:02 UTC, Mike Parker wrote:
>> On Sunday, 13 December 2020 at 20:03:46 UTC, Jackson22 wrote:
>>>
>>> There's a reason .ptr exist, I wish people would stop pretending that using it where it is appropriate is somehow going to lead to failure when there are more successful programming languages that have zero automatic bounds checking.
>>>
>>
>> There's no pretending here. What the OP is doing *is* dangerous.
>
> If someone writes a wrapper around .ptr which checks. It'd be literally no different than the implementation in druntime.

Of course. I'm not arguing otherwise. I don't see that anyone else is either. I'm talking about the specific case raised by the OP, where the issue isn't just a lack of automatic bounds checking, but the lack of any bounds checking at all.

Bounds checking before resizing has one of two possible outcomes: a reallocation, or no resizing occurs. The OP explicitly asked how to resize an array *without* reallocation, which implies that neither outcome of bounds checking is what he's looking for. So yes, arbitrarily slicing a pointer beyond its length in that situation is asking for trouble.

I mean, if there were more to the story, e.g., the array is backed by a block of malloced memory that's large enough for newLength, as manual bounds checking would verify, then the question of how to resize without reallocating is a moot one, no?



December 15, 2020
On Saturday, 12 December 2020 at 00:53:09 UTC, Jonathan Levi wrote:
> Wow, there went several hours of debugging.
>
> Increasing the length of a slice, by setting its length, will initialize the new elements and reallocate if necessary.
>
> I did not realize length was "smart", I guess I should have guessed.
>
> Anyway, to work around this, and probably also be more clear, create a new slice from the same pointer.
>
> `array = array.ptr[0..newLength];`

D and Go have both messed up the concept of a view of an array and owning the backing store of an array. I suggest using slices like c++ spans, only make them smaller, then create you own dynamic array ADT wrapper for explicit array ownership of the full array.
1 2 3
Next ›   Last »