webui-dev / nim-webui

Use any web browser as GUI, with Nim in the backend and HTML5 in the frontend.
https://webui.me
MIT License
130 stars 9 forks source link

Use `malloc` in `fileHandlerImpl` #24

Closed clzls closed 11 months ago

clzls commented 11 months ago

As a further work after issue #15 , I think it's our binding developers' responsibility to provide memory safe packages to other developers. So I wrote this very first PR of this project.

  1. string in Nim may contain '\0', not like null-terminating cstring. so

    let str: string = "Hi,\0binary"
    assert str.len == 10
    assert (cstring str).len == 3
    assert $(cstring str) == "Hi," # Anything after '\0' is dropped!
    assert (cstring str)[4] == 'b'

    If content that currHandler returned contains '\0', it was not processed properly. So I turned to use original string's len function. For similar reason, it is required, not optional, to tell WebUI library exact length of the content when content contains nulls.

  2. The memory of temporary cstring object may be GC'ed unexpectedly before it is used by WebUI library. We may use other mechanism to prevent so, but using webui_malloc is encouraged by WebUI document and seems to be a simpler, easier and safer solution.

  3. Return type of proc malloc* is missing. Is there something wrong with binding generation mechanism?

clzls commented 11 months ago

Note: Tested using a test fixture that requires a file at a speed of 10 requests per second. It worked fine for several thousands of iterations. Further tests are going to be designed. (If I make requests much quicker than 10 req/s, for example 1000 req/s, the backend could not keep up the pace.)

setInterval(() => {
  fetch('./getUuid').then(
    resp => resp.text().then(
      txt => {
        let k = document.createElement('span')
        k.innerText = txt + ' ';
        document.getElementById('logs').append(k);
      })
  );
}, 100);