Flow.Launcher/Flow.Launcher.Infrastructure/TranslationMapping.cs

97 lines
3.1 KiB
C#
Raw Normal View History

2024-06-02 06:18:57 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
namespace Flow.Launcher.Infrastructure
{
public class TranslationMapping
{
private bool constructed;
2025-04-09 12:06:17 +00:00
private readonly List<int> originalIndexes = new();
private readonly List<int> translatedIndexes = new();
2024-06-02 06:18:57 +00:00
private int translatedLength = 0;
public void AddNewIndex(int originalIndex, int translatedIndex, int length)
{
if (constructed)
throw new InvalidOperationException("Mapping shouldn't be changed after constructed");
2025-04-09 12:06:17 +00:00
originalIndexes.Add(originalIndex);
translatedIndexes.Add(translatedIndex);
translatedIndexes.Add(translatedIndex + length);
2024-06-02 06:18:57 +00:00
translatedLength += length - 1;
}
public int MapToOriginalIndex(int translatedIndex)
{
2025-04-09 12:06:17 +00:00
if (translatedIndex > translatedIndexes.Last())
2024-06-02 06:18:57 +00:00
return translatedIndex - translatedLength - 1;
int lowerBound = 0;
2025-04-09 12:06:17 +00:00
int upperBound = originalIndexes.Count - 1;
2024-06-02 06:18:57 +00:00
int count = 0;
// Corner case handle
2025-04-09 12:06:17 +00:00
if (translatedIndex < translatedIndexes[0])
2024-06-02 06:18:57 +00:00
return translatedIndex;
2025-04-09 12:06:17 +00:00
if (translatedIndex > translatedIndexes.Last())
2024-06-02 06:18:57 +00:00
{
int indexDef = 0;
2025-04-09 12:06:17 +00:00
for (int k = 0; k < originalIndexes.Count; k++)
2024-06-02 06:18:57 +00:00
{
2025-04-09 12:06:17 +00:00
indexDef += translatedIndexes[k * 2 + 1] - translatedIndexes[k * 2];
2024-06-02 06:18:57 +00:00
}
return translatedIndex - indexDef - 1;
}
// Binary Search with Range
2025-04-09 12:06:17 +00:00
for (int i = originalIndexes.Count / 2;; count++)
2024-06-02 06:18:57 +00:00
{
2025-04-09 12:06:17 +00:00
if (translatedIndex < translatedIndexes[i * 2])
2024-06-02 06:18:57 +00:00
{
// move to lower middle
upperBound = i;
i = (i + lowerBound) / 2;
}
2025-04-09 12:06:17 +00:00
else if (translatedIndex > translatedIndexes[i * 2 + 1] - 1)
2024-06-02 06:18:57 +00:00
{
lowerBound = i;
// move to upper middle
// due to floor of integer division, move one up on corner case
i = (i + upperBound + 1) / 2;
}
else
2025-04-09 12:06:17 +00:00
{
return originalIndexes[i];
}
2024-06-02 06:18:57 +00:00
if (upperBound - lowerBound <= 1 &&
2025-04-09 12:06:17 +00:00
translatedIndex > translatedIndexes[lowerBound * 2 + 1] &&
translatedIndex < translatedIndexes[upperBound * 2])
2024-06-02 06:18:57 +00:00
{
int indexDef = 0;
for (int j = 0; j < upperBound; j++)
{
2025-04-09 12:06:17 +00:00
indexDef += translatedIndexes[j * 2 + 1] - translatedIndexes[j * 2];
2024-06-02 06:18:57 +00:00
}
return translatedIndex - indexDef - 1;
}
}
}
public void endConstruct()
{
if (constructed)
throw new InvalidOperationException("Mapping has already been constructed");
constructed = true;
}
}
}