Last active
December 6, 2020 17:51
-
-
Save Vindaar/731b0469a48f7c1a4039a2e9dfb5459f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # compile without (!) `--gc:arc` to get a SIGSEGV | |
| import typetraits | |
| type | |
| RawMutableView*[T] = distinct ptr UncheckedArray[T] | |
| CpuStorage*[T] = ref CpuStorageObj[T] | |
| CpuStorageObj[T] = object | |
| raw_buffer*: seq[T] | |
| Tensor[T] = object | |
| buf*: CpuStorage[T] # if tensor stores a `seq` itself it works fine | |
| proc allocCpuStorage[T](s: var CpuStorage[T], size: int) = | |
| new(s) | |
| s.raw_buffer = newSeq[T](size) | |
| proc newTensor[T](size: int): Tensor[T] = | |
| allocCpuStorage(result.buf, size) | |
| template `[]=`*[T](v: RawMutableView[T], idx: int, val: T) = | |
| bind distinctBase | |
| distinctBase(type v)(v)[idx] = val | |
| proc `[]`[T](t: Tensor[T], idx: int): T = t.buf.raw_buffer[idx] | |
| proc `[]=`[T](t: Tensor[T], idx: int, val: T) = | |
| var dat: RawMutableView[T] | |
| dat = cast[RawMutableView[T]](t.buf.raw_buffer[0].addr) | |
| dat[idx] = val | |
| # works if we use: | |
| #t.buf.raw_buffer[idx] = val | |
| # also works if we manually unref the `dat[idx]`: | |
| # GC_unref(dat[idx]) | |
| proc toTensor[T](s: seq[T]): Tensor[T] = | |
| result = newTensor[T](s.len) | |
| for i, x in s: | |
| result[i] = x | |
| proc main() = | |
| var s: seq[string] | |
| for i in 0 ..< 1000: # works for small numbers | |
| s.add $i | |
| var y = s.toTensor | |
| for i in 0 ..< 1000: | |
| y[i] = "iae " & $i | |
| echo y.buf.raw_buffer | |
| main() | |
| #[ | |
| Traceback (most recent call last) | |
| /home/basti/org/Misc/gc_assign_bug.nim(46) gc_assign_bug | |
| /home/basti/org/Misc/gc_assign_bug.nim(44) main | |
| /home/basti/src/nim/nim_git_repo/lib/system/dollars.nim(170) $ | |
| /home/basti/src/nim/nim_git_repo/lib/system/dollars.nim(153) collectionToString | |
| /home/basti/src/nim/nim_git_repo/lib/system.nim(2853) addQuoted | |
| /home/basti/src/nim/nim_git_repo/lib/system.nim(2815) addEscapedChar | |
| /home/basti/src/nim/nim_git_repo/lib/system/gc.nim(435) newObjNoInit | |
| SIGSEGV: Illegal storage access. (Attempt to read from nil?) | |
| Error: execution of an external program failed: '/home/basti/org/Misc/gc_assign_bug ' | |
| ]# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment