Skip to content

Commit

Permalink
Merge pull request #24 from clzls/use_malloc
Browse files Browse the repository at this point in the history
Use `malloc` in `fileHandlerImpl`
  • Loading branch information
hassandraga committed Sep 28, 2023
2 parents a38a2cf + 9239de9 commit c74224f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
14 changes: 8 additions & 6 deletions webui.nim
Original file line number Diff line number Diff line change
Expand Up @@ -371,17 +371,19 @@ proc `bind`*(window: Window; element: string; `func`: proc (e: Event): bool) =
)

proc fileHandlerImpl(filename: cstring, length: ptr cint): pointer {.cdecl.} =
let content = cstring currHandler($filename)
let content = currHandler($filename)

#? maybe use webui_malloc
if content.len == 0:
return nil

# setting length is optional apparently
# Always set length for memory safety, especially binarys with '\0' inside
length[] = cint content.len

if len($content) == 0:
return nil
# Use webui_malloc to ensure memory safety
let mem = bindings.malloc(csize_t content.len)
copyMem(mem, cstring content, content.len)

return cast[pointer](content)
return mem

proc `fileHandler=`*(window: Window; handler: proc (filename: string): string) =
## Set a custom handler to serve files.
Expand Down
2 changes: 1 addition & 1 deletion webui/bindings.nim
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ proc free*(`ptr`: pointer) {.cdecl, importc: "webui_free".}
## Safely free a buffer allocated by WebUI, for example when using
## `encode()`.

proc malloc*(size: csize_t) {.cdecl, importc: "webui_malloc".}
proc malloc*(size: csize_t): pointer {.cdecl, importc: "webui_malloc".}
## Safely allocate memory using the WebUI memory management system.
## It can be safely free using `free()`.

Expand Down

0 comments on commit c74224f

Please sign in to comment.