diff --git a/src/infrastructure/road.zig b/src/infrastructure/road.zig index 81c08d6..0492724 100644 --- a/src/infrastructure/road.zig +++ b/src/infrastructure/road.zig @@ -12,15 +12,24 @@ pub const Road = struct { }; } + /// Unreferences self (road) from both nodes pub fn unreferenceNodes(self: *Road) !void { try self.nodes[0].unreferenceRoad(self); try self.nodes[1].unreferenceRoad(self); } - pub fn updateNodeReference(self: *Road, old_reference: *const Node, new_ref: *const Node) void { - _ = new_ref; // autofix - _ = old_reference; // autofix - _ = self; // autofix + /// Updates reference to the node, returns error if the old reference is invalid + pub fn updateNodeReference(self: *Road, allocator: std.mem.Allocator, old_reference: *Node, new_ref: *Node) !void { + for (0..self.nodes.len) |i| { + if (self.nodes[i].id != old_reference.id) continue; + self.nodes[i] = new_ref; + try old_reference.unreferenceRoad(self); + try new_ref.referenceRoad(allocator, self); + + return; + } + + return error.OldRefNotExists; } }; \ No newline at end of file diff --git a/src/simulator.zig b/src/simulator.zig index 4679bf0..d0c28f1 100644 --- a/src/simulator.zig +++ b/src/simulator.zig @@ -231,10 +231,9 @@ pub const Simulator = struct { const road_old_node = intersection.road.nodes[1]; // The old road that was intersected now borders the new node // and the old node is removed from the road's end node reference, - intersection.road.nodes[1] = new_node; // As is the end node's road reference - road_old_node.unreferenceRoad(intersection.road) catch |err| { - std.debug.panic("Failed to unreference previous road: {}\n", .{err}); + intersection.road.updateNodeReference(self.allocator, road_old_node, new_node) catch |err| { + std.debug.panic("Updating the old road reference failed: {}\n", .{err}); }; // This adds the road (to the road manager) and also references the road at both nodes (pointers)