//! system/services/shared-memory-server — the receiving half of the shared-memory test (docs/display-v2.md V2).
//! It registers under `ServiceId.shared_memory_test`; when `shared-memory-client` calls it carrying a
//! shared-memory capability, it `shared_memory_map`s that capability and checks the client's pattern
//! is visible through the mapping — proving the two processes share the same physical pages
//! (not a copy). On success it prints `shared-memory: shared 4096 bytes ok`, the test's marker.

const runtime = @import("runtime");
const system = runtime.system;
const shared_memory = runtime.shared_memory;
const ipc = runtime.ipc;

const pattern_len = 4096;

/// The pattern the client writes — must match shared-memory-client.zig.
fn expected(i: usize) u8 {
    return @truncate(i *% 7 +% 3);
}

fn onMessage(message: []const u8, reply: []u8, sender: u32, capability: ?ipc.Handle) usize {
    _ = message;
    _ = reply;
    _ = sender;
    const cap = capability orelse {
        _ = system.write("shared-memory: shared FAILED (no capability)\n");
        return 0;
    };
    const ptr = shared_memory.map(cap) orelse {
        _ = system.write("shared-memory: shared FAILED (map)\n");
        return 0;
    };
    var i: usize = 0;
    while (i < pattern_len) : (i += 1) {
        if (ptr[i] != expected(i)) {
            _ = system.write("shared-memory: shared FAILED (mismatch)\n");
            return 0;
        }
    }
    _ = system.write("shared-memory: shared 4096 bytes ok\n");
    return 0; // empty reply — the client only needs the round trip to unblock
}

pub fn main() void {
    runtime.service.run(64, .{ .service = .shared_memory_test, .on_message = onMessage });
}
