[wpilib] Refactor Alert (#7279)

This refactors Alert in both c++ and java to fix the issues with the current c++ implementation and improve performance.

Currently, constructing an Alert adds it to a list of Alerts with the same group and type. Activating an alert sets a flag on the alert. When the SendableAlerts is polled (GetStrings), the entire list is iterated over, filtered, and the filtered list is sorted by timestamp. This leads to a worst case O(m + nlog(n)) time complexity for GetStrings, where m and n are the count of total constructed alerts active alerts respectively. It also allocates intermediate data structures to hold the active alert strings for sorting.

This changes the implementation to improve the performance of GetStrings, by shifting the sorting overhead to Alert.Set
Constructing the Alert only initializes the alert's initial state, and initializes the SendableAlerts for the group if it is not already initialized.
Activating or deactivating an alert sets an internal flag for state tracking, and inserts or removes a structure containing the timestamp and text into a self-sorting data structure (std::set, TreeSet) containing other active alerts with the same group and type. (worst case O(log(n))
Now, SendableAlerts.GetStrings only has to iterate over the structure and copy the strings to the returned array. (amortized O(n))

This also fixes the c++ implementation by removing the need for SendableAlerts to directly access the Alert.

This also adds a helper method to SendableRegistry to force initialization of the instance to prevent static initialization ordering issues.
This commit is contained in:
Ryan Blue
2024-11-06 18:09:06 -05:00
committed by GitHub
parent 71c050389a
commit 5a16b0e108
7 changed files with 832 additions and 147 deletions

View File

@@ -81,6 +81,10 @@ void ResetSendableRegistry() {
} // namespace wpi::impl
#endif
void SendableRegistry::EnsureInitialized() {
GetInstance();
}
void SendableRegistry::SetLiveWindowBuilderFactory(
std::function<std::unique_ptr<SendableBuilder>()> factory) {
GetInstance().liveWindowFactory = std::move(factory);