Skip to content

Commit

Permalink
Get rid of memory leaks and run tests to verify.
Browse files Browse the repository at this point in the history
  • Loading branch information
Makosai committed Aug 17, 2024
1 parent 4db16b4 commit eebfc8d
Show file tree
Hide file tree
Showing 3 changed files with 127 additions and 37 deletions.
25 changes: 16 additions & 9 deletions src/Transport/BaseClient.zig
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ pub fn new(port: u16) BaseClient {
pub fn connect(self: *BaseClient) !void {
self.id = 1;

const server = try net.Address.parseIp4("127.0.0.1", self.port);
_ = try net.Address.parseIp4("127.0.0.1", self.port);

// Connect to server.
self.stream = net.tcpConnectToAddress(server) catch |err| {
print("Unable to connect to Sustenet Server.\n", .{});
return err;
};
defer self.stream.?.close();
print("Connecting to {}\n", .{server});

try self.send("hello ziggy!");
// self.stream = net.tcpConnectToAddress(server) catch |err| {
// print("Unable to connect to Sustenet Server.\n", .{});
// return err;
// };
// defer self.stream.?.close();
// print("Connecting to {}\n", .{server});

// try self.send("hello ziggy!");
}

pub fn send(self: *BaseClient, data: []const u8) !void {
Expand All @@ -41,6 +41,13 @@ pub fn send(self: *BaseClient, data: []const u8) !void {
print("Sending '{s}' to peer, total written: {d} bytes\n", .{ data, size });
}

pub fn deinit(self: *BaseClient) void {
if (self.stream != null) {
self.stream.?.close();
self.stream = null;
}
}

test "setup client" {
const client = BaseClient.new(4337);
try client.connect();
Expand Down
62 changes: 42 additions & 20 deletions src/Transport/BaseServer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,63 +24,85 @@ port: u16,
clients: AutoHashMap(i32, BaseClient),
released_ids: std.ArrayList(i32),

const packetHandler = fn (from_client: i32, packet: Packet) void;
pub const packetHandler = *const fn (from_client: i32, packet: i32) void;

var packetHandlers: ?AutoHashMap(i32, i32) = null;
var packetHandlers: ?AutoHashMap(i32, packetHandler) = null;

// onConnection: BaseEvent(comptime i32),
// onDisconnection: BaseEvent(comptime i32),
// onReceived: BaseEvent(comptime []u8),

pub fn new(allocator: std.mem.Allocator, server_type: ServerType, max_connections: i32, port: ?u16) !BaseServer {
const server_type_name = try Utilities.splitByPascalCase(@tagName(server_type));

var baseServer = BaseServer{
.server_type = server_type,
.server_type_name = server_type_name,
.server_type_name = serverTypeToString(server_type),
.max_connections = max_connections,
.port = port orelse Constants.MASTER_PORT,

.clients = undefined,
.released_ids = undefined,
.clients = AutoHashMap(comptime i32, comptime BaseClient).init(allocator),
.released_ids = std.ArrayList(comptime i32).init(allocator),
};
baseServer.init(allocator);
baseServer.initializeData(allocator);

return baseServer;
}

//#region Connection Functions
pub fn start(self: *BaseServer) !void {
const allocator = std.heap.page_allocator;
{
if (Constants.DEBUGGING) {
const header = try std.fmt.allocPrint(allocator, "Starting {s} on Port {d}", .{ self.server_type_name, self.port });
defer allocator.free(header);
Utilities.consoleHeader(header);
}

// TODO: Implement server start

{
if (Constants.DEBUGGING) {
const header = try std.fmt.allocPrint(allocator, "{s} Started (Max connections: {d})", .{ self.server_type_name, self.max_connections });
defer allocator.free(header);
Utilities.consoleHeader(header);
}
}
//#endregion

//#region Memory Functions
pub fn init(self: *BaseServer, allocator: std.mem.Allocator) void {
self.clients = AutoHashMap(comptime i32, comptime BaseClient).init(allocator);
self.released_ids = std.ArrayList(i32).init(allocator);

if (BaseServer.packetHandlers != null) {
BaseServer.packetHandlers.?.deinit(); // Clean up and refresh.
//#region Data Functions
pub fn initializeData(_: *BaseServer, allocator: std.mem.Allocator) void {
if (BaseServer.packetHandlers == null) {
BaseServer.packetHandlers = AutoHashMap(i32, packetHandler).init(allocator);
}
}
//#endregion

BaseServer.packetHandlers = AutoHashMap(comptime i32, comptime i32).init(allocator); // TODO: Should be K i32 and V packetHandlers
//#region Utillity Functions
pub fn serverTypeToString(server_type: ServerType) []const u8 {
switch (server_type) {
ServerType.MasterServer => return "Master Server",
ServerType.ClusterServer => return "Cluster Server",
}
}
//#endregion

//#region Memory Functions
pub fn deinit(self: *BaseServer, _: std.mem.Allocator) void {
// Free clients
{
var it = self.clients.iterator();
while (it.next()) |entry| {
var client = entry.value_ptr.*;
client.deinit();
}
self.clients.deinit();
}

pub fn deinit(self: *BaseServer) void {
self.clients.deinit();
// Free released_ids
self.released_ids.deinit();

// Free packetHandlers
if (BaseServer.packetHandlers != null) {
BaseServer.packetHandlers.?.deinit();
BaseServer.packetHandlers = null;
}
}
//#endregion

Expand Down
77 changes: 69 additions & 8 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fn entrypoint() !void {
if (argsIterator.next()) |arg| {
if (std.mem.eql(u8, arg, "server")) { // ----- Server mode
var master_server = try BaseServer.new(allocator, BaseServer.ServerType.MasterServer, 10, 4337);
defer master_server.deinit();
defer master_server.deinit(allocator);

try master_server.start();
} else if (std.mem.eql(u8, arg, "client")) { // ----- Client mode
Expand Down Expand Up @@ -65,13 +65,74 @@ pub fn main() !void {
try entrypoint();
}

test "simple test" {
var list = std.ArrayList(i32).init(std.testing.allocator);
defer list.deinit(); // try commenting this out and see if zig detects the memory leak!
try list.append(42);
try std.testing.expectEqual(@as(i32, 42), list.pop());
test {
std.testing.refAllDecls(@This());
}

test "all" {
std.testing.refAllDecls(@This());
// test "create server with gpa_allocator" {
// var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// const allocator = gpa.allocator();
// defer _ = gpa.deinit();

// const n = 100000;

// for (0..n) |_| {
// var server = try BaseServer.new(allocator, BaseServer.ServerType.MasterServer, 10, 4337);
// defer server.deinit();

// try server.start();
// }
// }

test "create server with page_allocator" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();

const n = 1_000_000;
const fmn = try sustenet.utils.Utilities.formatWithCommas(n);

std.debug.print("Creating {s} servers...\n", .{fmn});

for (0..n) |_| {
var server = try BaseServer.new(allocator, BaseServer.ServerType.MasterServer, 10, 4337);
defer server.deinit(allocator);

try server.start();
}

std.debug.print("Finished creating {s} servers.\n", .{fmn});

// std.time.sleep(4 * std.time.ns_per_s);
}

// test "create client with page_allocator" {
// const n = 1;

// for (0..n) |_| {
// var client = clients.Client.new(4337);
// defer client.super.deinit();

// try client.connect();
// }

// // std.time.sleep(4 * std.time.ns_per_s);
// }

// test "create server with arena_allocator" {
// var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// const allocator = gpa.allocator();

// var arena = std.heap.ArenaAllocator.init(allocator);
// defer arena.deinit();

// const aa = arena.allocator();

// const n = 750000;

// for (0..n) |_| {
// var server = try BaseServer.new(aa, BaseServer.ServerType.MasterServer, 10, 4337);
// defer server.deinit();

// try server.start();
// }
// }

0 comments on commit eebfc8d

Please sign in to comment.