* Check whether a name is unique, and otherwise try to make it unique. * @param new_name The name to check/modify. * @return True if an unique name was achieved. */
| 1606 | * @return True if an unique name was achieved. |
| 1607 | */ |
| 1608 | bool NetworkMakeClientNameUnique(std::string &name) |
| 1609 | { |
| 1610 | bool is_name_unique = false; |
| 1611 | std::string original_name = name; |
| 1612 | |
| 1613 | for (uint number = 1; !is_name_unique && number <= MAX_CLIENTS; number++) { // Something's really wrong when there're more names than clients |
| 1614 | is_name_unique = true; |
| 1615 | for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) { |
| 1616 | if (ci->client_name == name) { |
| 1617 | /* Name already in use */ |
| 1618 | is_name_unique = false; |
| 1619 | break; |
| 1620 | } |
| 1621 | } |
| 1622 | /* Check if it is the same as the server-name */ |
| 1623 | const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER); |
| 1624 | if (ci != nullptr) { |
| 1625 | if (ci->client_name == name) is_name_unique = false; // name already in use |
| 1626 | } |
| 1627 | |
| 1628 | if (!is_name_unique) { |
| 1629 | /* Try a new name (<name> #1, <name> #2, and so on) */ |
| 1630 | name = fmt::format("{} #{}", original_name, number); |
| 1631 | |
| 1632 | /* The constructed client name is larger than the limit, |
| 1633 | * so... bail out as no valid name can be created. */ |
| 1634 | if (name.size() >= NETWORK_CLIENT_NAME_LENGTH) return false; |
| 1635 | } |
| 1636 | } |
| 1637 | |
| 1638 | return is_name_unique; |
| 1639 | } |
| 1640 | |
| 1641 | /** |
| 1642 | * Change the client name of the given client |
no test coverage detected