diff options
author | flywind <xzsflywind@gmail.com> | 2021-08-22 13:40:20 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-08-22 07:40:20 +0200 |
commit | cc08d5c2c641e9390e9e05012defc9616f5d6ba8 (patch) | |
tree | 62317ca7e6c11d16b66677845ba202c642542549 /lib/std/tempfiles.nim | |
parent | 061a9183f7b49289b05cf134893d703760f467a7 (diff) | |
download | Nim-cc08d5c2c641e9390e9e05012defc9616f5d6ba8.tar.gz |
fix #17898(randomPathName called twice in a row can return the same string on windows) (#18729)
* close #17898 * no need to consider js
Diffstat (limited to 'lib/std/tempfiles.nim')
-rw-r--r-- | lib/std/tempfiles.nim | 20 |
1 files changed, 17 insertions, 3 deletions
diff --git a/lib/std/tempfiles.nim b/lib/std/tempfiles.nim index c97db67b6..f1cfd5885 100644 --- a/lib/std/tempfiles.nim +++ b/lib/std/tempfiles.nim @@ -17,7 +17,7 @@ See also: * `mkstemp` (posix), refs https://man7.org/linux/man-pages/man3/mkstemp.3.html ]# -import os, random +import os, random, std/monotimes const @@ -96,11 +96,25 @@ proc safeOpen(filename: string): File = discard posix.close(fileHandle) # TODO handles failure when closing file raiseOSError(osLastError(), filename) + +type + NimTempPathState = object + state: Rand + isInit: bool + +var nimTempPathState {.threadvar.}: NimTempPathState + template randomPathName(length: Natural): string = var res = newString(length) - var state = initRand() + if not nimTempPathState.isInit: + var time = getMonoTime().ticks + when compileOption("threads"): + time = time xor int64(getThreadId()) + nimTempPathState.isInit = true + nimTempPathState.state = initRand(time) + for i in 0 ..< length: - res[i] = state.sample(letters) + res[i] = nimTempPathState.state.sample(letters) res proc getTempDirImpl(dir: string): string {.inline.} = |