Open shirleyquirk opened 3 years ago
silly me. sizeof(UncheckedArray[T])
== 0
Solution:
proc create[T](x:typedesc[UncheckedArray[T]],size:int):ptr UncheckedArray[T]{.inline,benign,raises:[].} =
cast[ptr UncheckedArray[T]](alloc0(sizeof(T)*size))
or make sizeof(UncheckedArray[T]) == sizeof(T) ??? don't know what that would break
Documentation comment of create
says:
Allocates a new memory block with at least T.sizeof * size bytes.
So I think when create
is called with T such that sizeof(T) == 0,
it should be compile time error.
Because T.sizeof * size is always 0 and create
cannot allocate a new memory block that you actually needs.
Making sizeof(UncheckedArray[T]) != 0 can be a breaking change.
For example, payloadCheck()
proc in tests/misc/tsizeof.nim
become failed.
From https://nim-lang.org/docs/manual.html#types-unchecked-arrays
Additionally, an unchecked array is translated into a C array of undetermined size:
In C, C array of undetermined size in a struct is count as 0 bytes.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int len;
int cap;
int data[];
} MySeq;
int main(void)
{
printf("sizeof(int): %ld, sizeof(MySeq):%ld\n", sizeof(int), sizeof(MySeq));
return EXIT_SUCCESS;
}
Output:
sizeof(int): 4, sizeof(MySeq): 8
I think you should create a new proc like proc createUncheckedArray(T: typedesc; size = 1.Positive): ptr UncheckedArray[T]
if you really need such a proc.
Aha, put like that it's very clear that sizeof(UncheckedArray[T])
should be 0
Having just shot myself in the foot, I'm pro a static assert that create
isn't returning a footgun, but I guess that would be a breaking change too. Maybe a warning?
If a proc returning a ptr UncheckedArray
were to exist in the stdlib, my bike shedding stance is that an overload on create
could never be ambiguous, and would be intuitive.
cast[ptr UncheckedArray[float]](create(float, degree))
should be another workaround, maybe even the intended way? Maybe create
with a size
parameter should return ptr UncheckedArray[T]
instead?
Should have at least 1 test.
Example
Current Output
Expected Output
with --gc:arc the above work