Update
This commit is contained in:
@@ -3,6 +3,7 @@ namespace HomeAssistant.HistoryReplay.HistoryData;
|
||||
public sealed class HistoryTimeline
|
||||
{
|
||||
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
|
||||
private bool _sorted;
|
||||
|
||||
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
|
||||
{
|
||||
@@ -13,7 +14,41 @@ public sealed class HistoryTimeline
|
||||
}
|
||||
|
||||
list.AddRange(entries);
|
||||
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
||||
_sorted = false;
|
||||
}
|
||||
|
||||
public void AddEntriesBulk(string entityId, List<HistoryStateEntry> entries)
|
||||
{
|
||||
if (entries.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
||||
{
|
||||
_entityTimelines[entityId] = entries;
|
||||
}
|
||||
else
|
||||
{
|
||||
list.AddRange(entries);
|
||||
}
|
||||
|
||||
_sorted = false;
|
||||
}
|
||||
|
||||
public void FinalizeSort()
|
||||
{
|
||||
if (_sorted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var entries in _entityTimelines.Values)
|
||||
{
|
||||
entries.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
||||
}
|
||||
|
||||
_sorted = true;
|
||||
}
|
||||
|
||||
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
|
||||
@@ -23,20 +58,8 @@ public sealed class HistoryTimeline
|
||||
return null;
|
||||
}
|
||||
|
||||
HistoryStateEntry? best = null;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (entry.LastChanged <= timestamp)
|
||||
{
|
||||
best = entry;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
var index = BinarySearchFloor(entries, timestamp);
|
||||
return index >= 0 ? entries[index] : null;
|
||||
}
|
||||
|
||||
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
|
||||
@@ -62,4 +85,34 @@ public sealed class HistoryTimeline
|
||||
}
|
||||
|
||||
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_entityTimelines.Clear();
|
||||
_sorted = false;
|
||||
}
|
||||
|
||||
private static int BinarySearchFloor(List<HistoryStateEntry> entries, DateTimeOffset timestamp)
|
||||
{
|
||||
var lo = 0;
|
||||
var hi = entries.Count - 1;
|
||||
var result = -1;
|
||||
|
||||
while (lo <= hi)
|
||||
{
|
||||
var mid = lo + (hi - lo) / 2;
|
||||
|
||||
if (entries[mid].LastChanged <= timestamp)
|
||||
{
|
||||
result = mid;
|
||||
lo = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user