1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-24 15:19:26 -05:00

fix(ext/node): fix os.freemem (#21347)

This commit is contained in:
Yoshiya Hinosawa 2023-11-30 22:06:01 +09:00 committed by GitHub
parent 595a2be024
commit 3591ba8578
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 41 additions and 2 deletions

View file

@ -289,3 +289,23 @@ Deno.test({
await child.status;
},
});
Deno.test({
name:
"os.freemem() is equivalent of Deno.systemMemoryInfo().free except on linux",
ignore: Deno.build.os === "linux",
fn() {
const diff = Math.abs(os.freemem() - Deno.systemMemoryInfo().free);
assert(diff < 10_000);
},
});
Deno.test({
name:
"os.freemem() is equivalent of Deno.systemMemoryInfo().available on linux",
ignore: Deno.build.os !== "linux",
fn() {
const diff = Math.abs(os.freemem() - Deno.systemMemoryInfo().available);
assert(diff < 10_000);
},
});

View file

@ -159,7 +159,14 @@ export function endianness(): "BE" | "LE" {
/** Return free memory amount */
export function freemem(): number {
return Deno.systemMemoryInfo().free;
if (Deno.build.os === "linux") {
// On linux, use 'available' memory
// https://github.com/libuv/libuv/blob/a5c01d4de3695e9d9da34cfd643b5ff0ba582ea7/src/unix/linux.c#L2064
return Deno.systemMemoryInfo().available;
} else {
// Use 'free' memory on other platforms
return Deno.systemMemoryInfo().free;
}
}
/** Not yet implemented */

View file

@ -27,6 +27,6 @@
| Target family | Syscall | Description |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| Linux | sysinfo | - |
| Linux | sysinfo and `/proc/meminfo` | - |
| Windows | `sysinfoapi::GlobalMemoryStatusEx` | - |
| macOS | <br> <pre> sysctl([CTL_HW, HW_MEMSIZE]); <br> sysctl([CTL_VM, VM_SWAPUSAGE]); <br> host_statistics64(mach_host_self(), HOST_VM_INFO64) </pre> | - |

View file

@ -211,8 +211,20 @@ pub fn mem_info() -> Option<MemInfo> {
mem_info.swap_free = info.freeswap * mem_unit;
mem_info.total = info.totalram * mem_unit;
mem_info.free = info.freeram * mem_unit;
mem_info.available = mem_info.free;
mem_info.buffers = info.bufferram * mem_unit;
}
// Gets the available memory from /proc/meminfo in linux for compatibility
#[allow(clippy::disallowed_methods)]
if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
let line = meminfo.lines().find(|l| l.starts_with("MemAvailable:"));
if let Some(line) = line {
let mem = line.split_whitespace().nth(1);
let mem = mem.and_then(|v| v.parse::<u64>().ok());
mem_info.available = mem.unwrap_or(0);
}
}
}
#[cfg(target_vendor = "apple")]
{