From d44969769f05a1ffb6df9782b2058c5e9b4477aa Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Wed, 7 Aug 2024 02:31:45 -0700 Subject: [PATCH] darwin: implement node:os.freemem() (#12870) --- src/bun.js/bindings/OsBinding.cpp | 25 +++++++++++++++++++++++++ src/darwin_c.zig | 3 +-- test/js/node/os/os.test.js | 4 ++-- 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 src/bun.js/bindings/OsBinding.cpp diff --git a/src/bun.js/bindings/OsBinding.cpp b/src/bun.js/bindings/OsBinding.cpp new file mode 100644 index 00000000000000..c994fe8d9866d2 --- /dev/null +++ b/src/bun.js/bindings/OsBinding.cpp @@ -0,0 +1,25 @@ +#include "root.h" + +#if OS(DARWIN) +#include +#include +#include +#include +#include +#include + +// Adapted from libuv darwin uv_get_free_memory, MIT +extern "C" uint64_t Bun__Os__getFreeMemory(void) +{ + vm_statistics_data_t info; + mach_msg_type_number_t count = sizeof(info) / sizeof(integer_t); + + if (host_statistics(mach_host_self(), HOST_VM_INFO, + (host_info_t)&info, &count) + != KERN_SUCCESS) { + return 0; + } + + return (uint64_t)info.free_count * sysconf(_SC_PAGESIZE); +} +#endif diff --git a/src/darwin_c.zig b/src/darwin_c.zig index bdf1c9767470b6..dabd819a1dc2bd 100644 --- a/src/darwin_c.zig +++ b/src/darwin_c.zig @@ -553,8 +553,7 @@ pub const kFSEventStreamEventFlagUnmount: c_int = 128; pub const kFSEventStreamEventFlagUserDropped: c_int = 2; pub fn getFreeMemory() u64 { - // NOT IMPLEMENTED YET - return 1024 * 1024; + return @extern(*const fn () callconv(.C) u64, .{ .name = "Bun__Os__getFreeMemory" })(); } pub fn getTotalMemory() u64 { diff --git a/test/js/node/os/os.test.js b/test/js/node/os/os.test.js index f676a4040ed768..2e1655b43f6db2 100644 --- a/test/js/node/os/os.test.js +++ b/test/js/node/os/os.test.js @@ -12,11 +12,11 @@ it("endianness", () => { }); it("freemem", () => { - expect(os.freemem() > 0).toBe(true); + expect(os.freemem()).toBeGreaterThan(1024 * 1024); }); it("totalmem", () => { - expect(os.totalmem() > 0).toBe(true); + expect(os.totalmem()).toBeGreaterThan(1024 * 1024); }); it("getPriority", () => {