Branch data Line data Source code
1 : : #include "precizer.h"
2 : :
3 : : #ifdef TESTITALL
4 : : #include "testmocking.h"
5 : :
6 : : /* In test builds route only this file's sysconf() calls through testmocking.
7 : : This avoids overriding the libc symbol globally because sanitizers and
8 : : runtime helpers may rely on the real sysconf() behavior */
9 : : #define sysconf(name) testmocking_sysconf(name)
10 : : #endif
11 : :
12 : : /**
13 : : * @brief Estimate the file-read buffer size
14 : : *
15 : : * Uses one percent of currently available physical memory when the platform
16 : : * reports it. On platforms that only expose total physical pages, the estimate
17 : : * is based on total memory instead. If page-count or page-size queries fail,
18 : : * the function falls back to a 1 MB buffer
19 : : *
20 : : * @note The one-percent heuristic may still be too large for constrained
21 : : * embedded or IoT devices
22 : : *
23 : : * @return Selected buffer size in bytes
24 : : */
25 : 356 : size_t file_buffer_memory(void)
26 : : {
27 : : // Default value is 1MB buffer. Is it too big for embedded and IoT?
28 : 356 : const size_t buffer_size = 1024*1024;
29 : :
30 : : #if (defined(_SC_AVPHYS_PAGES) || defined(_SC_PHYS_PAGES)) && (defined(_SC_PAGESIZE) || defined(_SC_PAGE_SIZE))
31 : : // Number of actually free pages
32 : : long pages;
33 : :
34 : : #ifdef _SC_AVPHYS_PAGES
35 : 356 : pages = sysconf(_SC_AVPHYS_PAGES);
36 : : #elif defined(_SC_PHYS_PAGES)
37 : : // Fallback for platforms without _SC_AVPHYS_PAGES — use total pages
38 : : pages = sysconf(_SC_PHYS_PAGES);
39 : : #endif
40 : :
41 [ + + ]: 356 : if(pages == -1)
42 : : {
43 : 1 : return(buffer_size);
44 : : }
45 : :
46 : : /* Page size in bytes */
47 : : #ifdef _SC_PAGESIZE
48 : 355 : long page_size = sysconf(_SC_PAGESIZE);
49 : : #else
50 : : long page_size = sysconf(_SC_PAGE_SIZE);
51 : : #endif
52 : :
53 [ + + ]: 355 : if(page_size == -1)
54 : : {
55 : 1 : return(buffer_size);
56 : : }
57 : :
58 : : // Only 1% of available RAM
59 : 354 : size_t avail_bytes = (size_t)pages * (size_t)page_size;
60 : :
61 : 354 : size_t one_percent = avail_bytes / 100;
62 : :
63 : 354 : slog(TRACE,"Bytes that can be allocated for the file buffer: %s\n",bkbmbgbtbpbeb(one_percent,FULL_VIEW));
64 : :
65 : 354 : return(one_percent);
66 : : #else
67 : : return(buffer_size);
68 : : #endif
69 : : }
|