NumberInterval, DataNormalizer, ScopedRunner and TimeMeasurement
Four small H.Necessaire building blocks: numeric intervals, range mapping, scoped start/stop blocks and timing.
Applies to H.Necessaire 4.0.5.
Four small building blocks that show up everywhere once you know them: intervals, range mapping, scoped start/stop blocks and timing.
Install
dotnet add package H.NecessaireNumberInterval
A struct describing a numeric interval, with optional open ends and per-end inclusivity.
var closed = new NumberInterval(0, 10); // [ 0 ; 10 ]
var halfOpen = new NumberInterval(0, 10, isMaxIncluded: false); // [ 0 ; 10 )
var atLeast = new NumberInterval(5, null); // [ 5 ; ∞ )
closed.Contains(10); // true
halfOpen.Contains(10); // false
atLeast.IsInfinite; // true
NumberInterval pct = NumberInterval.Percent; // [ 0 ; 100 ]If you pass the bounds in the wrong order they are swapped. IsSingle is true when min equals max.
DataNormalizer
Maps a value from one interval onto another: the arithmetic behind progress bars, scaling and gauges.
// 0..1200 processed items -> 0..100 percent
var toPercent = DataNormalizer.Percent(new NumberInterval(0, 1200));
toPercent.Do(300); // 25
toPercent.Do(1200); // 100
toPercent.Do(5000); // 100 (values outside the source range are clamped)
// Any interval to any interval, and back again
var celsiusToKelvin = new DataNormalizer(new NumberInterval(0, 100), new NumberInterval(273.15, 373.15));
var backwards = celsiusToKelvin.Reverse();Do throws InvalidOperationException if either interval is infinite. If the source interval is a single point it returns that point; if the target is a single point it returns the target.
ScopedRunner
Runs an action when created and another when disposed, so a using block guarantees the pair.
using (new ScopedRunner(
() => spinner.Show(),
() => spinner.Hide()))
{
await LoadDataAsync();
}An overload takes Action<bool> callbacks that receive true on start and false on stop, handy for toggling a flag. Both callbacks are run safely, so an exception inside them won't escape. ScopedRunner.Null is a no-op instance.
TimeMeasurement
using (new TimeMeasurement(elapsed => log.Info($"Import took {elapsed}")))
{
await ImportAsync();
}
using (new PreciseTimeMeasurement(elapsed => metrics.Record(elapsed)))
{
HotPath();
}TimeMeasurement uses a Stopwatch; PreciseTimeMeasurement uses raw timestamps and converts them to a TimeSpan, which is more accurate for very short operations. Both are built on ScopedRunner.