Permalink
Browse files

Add Range.FromStartEnd, Range.Contains and Range.Intersect together w…

…ith unit tests.
  • Loading branch information...
vivek
vivek committed Apr 9, 2014
1 parent 9b6952b commit 9811707bbf95b54d9ead4072ba4c278d6ff8a200
Showing with 67 additions and 0 deletions.
  1. +35 −0 Source/Eto.Test/Eto.Test/UnitTests/Forms/RangeTests.cs
  2. +32 −0 Source/Eto/Forms/Range.cs
@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Eto.Forms;
+using NUnit.Framework;
+
+namespace Eto.Test.UnitTests.Forms
+{
+ [TestFixture]
+ public class RangeTests
+ {
+ [TestCase(100, 200, 100, 101)]
+ [TestCase(100, 100, 100, 1)]
+ [TestCase(100, 99, 100, 0)]
+ public void Range_FromStartEnd(int s, int e, int start, int length)
+ {
+ var a = Range.FromStartEnd(s, e);
+ var b = new Range(start, length);
+ Assert.AreEqual(a, b);
+ }
+
+ [TestCase(100, 200, 300, 400, 0, -1)] // nonintersecting
+ [TestCase(100, 200, 150, 300, 150, 200)]
+ [TestCase(150, 300, 100, 200, 150, 200)] // opposite order
+ public void Range_Intersect_Intersects(int s1, int e1, int s2, int e2, int s, int e)
+ {
+ var r1 = Range.FromStartEnd(s1, e1);
+ var r2 = Range.FromStartEnd(s2, e2);
+ var r = Range.FromStartEnd(s, e);
+ Assert.AreEqual(r, r1.Intersect(r2));
+ Assert.AreEqual(r, r2.Intersect(r1));
+ }
+ }
+}
View
@@ -3,6 +3,10 @@
namespace Eto.Forms
{
+ /// <summary>
+ /// A range defined by a start index and a length.
+ /// Start and End are inclusive, so End = Start + Length -1.
+ /// </summary>
public struct Range : IEquatable<Range>
{
[Obsolete("Use Start instead")]
@@ -15,20 +19,48 @@ public struct Range : IEquatable<Range>
public int Length { get; set; }
+ public bool IsEmpty { get { return Length == 0; } }
+
public Range (int start, int length)
: this ()
{
this.Start = start;
this.Length = length;
}
+ public static Range FromStartEnd(int start, int end)
+ {
+ return new Range(start, end - start + 1);
+ }
+
public int End {
get { return Start + Length - 1; }
set {
Length = value - Start + 1;
}
}
+ public bool Contains(int value)
+ {
+ return Start <= value && value <= End;
+ }
+
+ public Range Intersect(Range range)
+ {
+ if (range != null &&
+ Start != null &&
+ End != null &&
+ range.Start != null &&
+ range.End != null)
+ {
+ var start = Start >= range.Start ? Start : range.Start;
+ var end = End <= range.End ? End : range.End;
+ if (start <= end)
+ return Range.FromStartEnd(start, end);
+ }
+ return default(Range);
+ }
+
public override bool Equals (object obj)
{
return obj is Range && (Range)obj == this;

0 comments on commit 9811707

Please sign in to comment.