Thread overview
[Issue 24355] Slice copy with static arrays incorrect bounds checking
Jan 25, 2024
ryuukk_
Jan 25, 2024
anonymous4
Jan 25, 2024
ryuukk_
Jan 26, 2024
Nick Treleaven
Jan 26, 2024
Nick Treleaven
Jan 26, 2024
Nick Treleaven
January 25, 2024
https://issues.dlang.org/show_bug.cgi?id=24355

ryuukk_ <ryuukk.dev@gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
            Summary|Slice copy with static      |Slice copy with static
                   |arrays incorrect of bounds  |arrays incorrect bounds
                   |checking                    |checking

--
January 25, 2024
https://issues.dlang.org/show_bug.cgi?id=24355

--- Comment #1 from anonymous4 <dfj1esp02@sneakemail.com> ---
In case 1 it's unclear what you want, it can be id[0..6]=str[0..6] or id[0..6]=str[0..6],id[6..12]=str[0..6],... - pattern copy.

--
January 25, 2024
https://issues.dlang.org/show_bug.cgi?id=24355

--- Comment #2 from ryuukk_ <ryuukk.dev@gmail.com> ---
I expect the same as:

```
void main()
{
    char[32] id = "hello";
}
```



left: static array
right: slice

result: slice -> copy -> [0 .. slice.length]

--
January 26, 2024
https://issues.dlang.org/show_bug.cgi?id=24355

Nick Treleaven <nick@geany.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |nick@geany.org

--- Comment #3 from Nick Treleaven <nick@geany.org> ---
    char[32] id = 0;
    const(char)* str = "hello";
    id = str[0 .. 6];

The error is correct by the spec:
> A static array can be assigned from a dynamic array - the data is copied. The lengths must match
https://dlang.org/spec/arrays.html#assignment

    char[4] id;
    id = "hello asdad";

This causes a runtime error. You're right it could be caught at compile-time. Assigning an array literal with excess elements is a compile error.

    char[32] id = "hello";

An array *initializer* is allowed to have fewer elements. If there are excess elements, for an array literal it's a compile error, for a string literal, it's a runtime error as above.

--
January 26, 2024
https://issues.dlang.org/show_bug.cgi?id=24355

--- Comment #4 from Nick Treleaven <nick@geany.org> ---
> An array *initializer* is allowed to have fewer elements.

Actually that only seems to apply when the initializer is a string literal.

char[4] s = [1]; // error
char[4] s = "a"; // OK

--
January 26, 2024
https://issues.dlang.org/show_bug.cgi?id=24355

--- Comment #5 from Nick Treleaven <nick@geany.org> ---
Spec for above:

> A string literal converts to a static array rvalue of the same or longer length
https://dlang.org/spec/expression.html#string_literals

--