Add use_threads option to loadUri.

This commit is contained in:
Alberto Torres 2024-09-05 16:48:35 +02:00
parent 41c7c7092a
commit 83011ea344

View file

@ -231,11 +231,14 @@ func escapeUTF8*(s: string): string =
else: else:
result &= '%' & c.byte.toHex result &= '%' & c.byte.toHex
# TODO: automatically disable threads when not in main thread
proc loadUri*( proc loadUri*(
uri: string, uri: string,
onload_func: proc(ok: bool, err: string, data: SliceMem[byte]) = nil, onload_func: proc(ok: bool, err: string, data: SliceMem[byte]) = nil,
range = (-1,-1), range = (-1,-1),
auto_start = true, auto_start = true,
use_threads = true,
): Fetch {.discardable.} = ): Fetch {.discardable.} =
echo "fetching ", uri echo "fetching ", uri
@ -243,7 +246,7 @@ proc loadUri*(
var start_func: proc(self: LoadableResource) var start_func: proc(self: LoadableResource)
var self: Fetch var self: Fetch
var uri = uri var uri = uri
var use_threads = false var use_threads = use_threads
when not defined(onlyLocalFiles): when not defined(onlyLocalFiles):
when defined(emscripten): when defined(emscripten):
const is_remote = true const is_remote = true
@ -253,6 +256,7 @@ proc loadUri*(
if is_remote: if is_remote:
uri = uri.escapeUTF8 uri = uri.escapeUTF8
when defined(emscripten): when defined(emscripten):
use_threads = false # API is already threaded
start_func = proc(self: LoadableResource) = start_func = proc(self: LoadableResource) =
var attr: emscripten_fetch_attr_t var attr: emscripten_fetch_attr_t
emscripten_fetch_attr_init(attr) emscripten_fetch_attr_init(attr)
@ -273,7 +277,6 @@ proc loadUri*(
self.onload(false, &"Error fetching {fetch.url}: {err_msg}") self.onload(false, &"Error fetching {fetch.url}: {err_msg}")
discard emscripten_fetch(attr, uri.cstring) discard emscripten_fetch(attr, uri.cstring)
else: else:
use_threads = true
var client = newHttpClient() var client = newHttpClient()
var response: string var response: string
start_func = proc(self: LoadableResource) = start_func = proc(self: LoadableResource) =
@ -290,6 +293,8 @@ proc loadUri*(
)) ))
if not is_remote: if not is_remote:
use_threads = false # TODO: detect networked file system?
# TODO: also test if there's better perf in local
start_func = proc(self: LoadableResource) = start_func = proc(self: LoadableResource) =
try: try:
var memfile = memfiles.open(uri, mode=fmRead) var memfile = memfiles.open(uri, mode=fmRead)