#include "pisharedmemory.h"

#include "gtest/gtest.h"

#ifdef WINDOWS
#  include <process.h>
#else
#  include <unistd.h>
#endif

TEST(PISharedMemory_Test, ReadWriteBounds) {
	PISharedMemory shm("pip_bughunt_shm_bounds_" + PIString::fromNumber(int(getpid())), 64);
	ASSERT_TRUE(shm.open());

	const char payload[32] = "0123456789abcdef";
	ASSERT_EQ(32, shm.write(payload, 32));
	ASSERT_EQ(16, shm.write(payload, 16, 10));

	// Out-of-bounds writes must be rejected, not silently overflow the mapping.
	EXPECT_EQ(-1, shm.write(payload, 100));    // exceeds size
	EXPECT_EQ(-1, shm.write(payload, 32, 97)); // offset + size exceeds size
	EXPECT_EQ(-1, shm.write(payload, 16, -5)); // negative offset

	// Out-of-bounds reads must be rejected.
	char dst[128];
	EXPECT_EQ(-1, shm.read(dst, 200));    // exceeds size
	EXPECT_EQ(-1, shm.read(dst, 32, 97)); // offset + size exceeds size
	EXPECT_EQ(-1, shm.read(dst, 32, -1));

	// In-bounds reads must still succeed.
	EXPECT_EQ(16, shm.read(dst, 16, 10));
	ASSERT_EQ(0, memcmp(dst, "0123456789abcdef", 16));

	ASSERT_TRUE(shm.close());
}