Skip to content

Instantly share code, notes, and snippets.

@ErnSur
Last active March 2, 2022 11:32
Show Gist options
  • Save ErnSur/96a5bab9c253c6ada55dab359420f75b to your computer and use it in GitHub Desktop.
Save ErnSur/96a5bab9c253c6ada55dab359420f75b to your computer and use it in GitHub Desktop.
[C#] int struct that goes back to 0 when value equals max
/// <summary>
/// int struct that goes back to 0 when value equals max
/// and goes back to max when equals -1
/// </summary>
public struct LoopingInt
{
public int max;
private int _value;
public int Value
{
get => _value;
set => _value = ((value % max) + max) % max;
}
/// <param name="max">Exclusive</param>
public LoopingInt(int max) => (_value, this.max) = (0, max);
/// <param name="max">Exclusive</param>
public LoopingInt(int value, int max) : this(max)
{
Value = value;
}
public static implicit operator int(LoopingInt v)
{
return v._value;
}
public static LoopingInt operator ++(LoopingInt rhs)
{
return new LoopingInt(rhs._value + 1, rhs.max);
}
public static LoopingInt operator --(LoopingInt rhs)
{
return new LoopingInt(rhs._value - 1, rhs.max);
}
}
namespace Tests
{
public class LoopingIntTests
{
[TestCase(0,2)]
[TestCase(0,4)]
public void MaxIsExclusive(int val,int max)
{
var _lint = new LoopingInt(val, max)
{
Value = max
};
Assert.AreEqual(0, _lint.Value);
}
[TestCase(0, 2)]
[TestCase(0, 4)]
[TestCase(0, 462)]
public void WorksBackwards(int val, int max)
{
var _lint = new LoopingInt(val, max);
_lint.Value = -1;
Assert.AreEqual(max-1, _lint.Value);
_lint.Value = -2;
Assert.AreEqual(max-2, _lint.Value);
}
[TestCase(0, 2)]
[TestCase(0, 4)]
public void Operators(int val, int max)
{
var _lint = new LoopingInt(val, max);
_lint++;
Assert.AreEqual(1, _lint.Value);
_lint--;
Assert.AreEqual(0, _lint.Value);
}
}
}
public static int PingPong(int t, int length)
{
t = new LoopingInt(t, length * 2);
return length - Mathf.Abs(t - length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment