1#include "include/pw.h"
 2#include "include/pwlib/file.h"
 3#include "src/types/string/string_internal.h"
 4
 5[[nodiscard]] bool pw_read_file(PwValuePtr file, PwValuePtr content, unsigned max_length)
 6{
 7    unsigned bytes_read = 0;
 8    while (bytes_read < max_length) {
 9        unsigned dest_avail = _pw_string_avail(content);
10        if (dest_avail == 0) {
11            unsigned n_expand = max_length - bytes_read;
12            if (n_expand > 512) {
13                n_expand = 512;
14            }
15            if (!_pw_expand_string(content, n_expand, 1)) {
16                return false;
17            }
18            dest_avail = _pw_string_avail(content);
19        }
20        uint8_t* dest_ptr;
21        _pw_string_start_end(content, &dest_ptr);
22        unsigned n_read;
23        if (!pw_read(file, dest_ptr, dest_avail, &n_read)) {
24            return false;
25        }
26        if (n_read == 0) {
27            // end of file
28            return true;
29        }
30        _pw_string_inc_length(content, n_read);
31        bytes_read += n_read;
32    }
33    return true;
34}
35
36[[nodiscard]] bool pw_load_file(PwValuePtr filename, PwValuePtr content)
37{
38    pw_destroy(content);
39    *content = PwString();
40
41    PwValue f = PW_NULL;
42    if (!pw_file_open_unbuffered(filename, O_RDONLY, 0, &f)) {
43        return false;
44    }
45    bool ret = pw_read_file(&f, content, UINT_MAX);
46    pw_close(&f);
47    return ret;
48}