updateRoutes method

RoutingTable<T> updateRoutes(
  1. RoutingTable<T> currentTable,
  2. Map<T, RouteEntry<T>> advertisements,
  3. T neighbor,
  4. int neighborCost,
)

Updates routing table based on received route advertisements

currentTable - Current routing table advertisements - Route advertisements from neighbors neighborCost - Cost to reach the advertising neighbor

Returns updated routing table with new routes

Implementation

RoutingTable<T> updateRoutes(
  RoutingTable<T> currentTable,
  Map<T, RouteEntry<T>> advertisements,
  T neighbor,
  int neighborCost,
) {
  final updatedRoutes = Map<T, RouteEntry<T>>.from(currentTable.routes);
  final now = DateTime.now();
  bool hasChanges = false;

  for (final entry in advertisements.entries) {
    final dest = entry.key;
    final advRoute = entry.value;
    final totalCost = advRoute.cost + neighborCost;

    // Skip if cost exceeds maximum hops
    if (totalCost > _maxHops) continue;

    // Check if we have a better route
    if (!updatedRoutes.containsKey(dest) ||
        totalCost < updatedRoutes[dest]!.cost) {
      updatedRoutes[dest] = RouteEntry<T>(
        destination: dest,
        nextHop: neighbor,
        cost: totalCost,
        lastUpdate: now,
        isDirectlyConnected: false,
      );
      hasChanges = true;
    }
  }

  // Update neighbor route if we have a better path
  if (!updatedRoutes.containsKey(neighbor) ||
      neighborCost < updatedRoutes[neighbor]!.cost) {
    updatedRoutes[neighbor] = RouteEntry<T>(
      destination: neighbor,
      nextHop: neighbor,
      cost: neighborCost,
      lastUpdate: now,
      isDirectlyConnected: true,
    );
    hasChanges = true;
  }

  return RoutingTable<T>(
    sourceNode: currentTable.sourceNode,
    routes: Map.unmodifiable(updatedRoutes),
    lastUpdate: hasChanges ? now : currentTable.lastUpdate,
  );
}