From e44ffdc7f4f3dce94700ff26cc66accef4faf152 Mon Sep 17 00:00:00 2001 From: Alexander Ljungberg Date: Sun, 10 Apr 2011 21:20:22 -0400 Subject: [PATCH] CPString subtringWithRange: and rangeOfString:options:range now throws CPRangeException for out of bounds ranges. --- Foundation/CPString.j | 5 +++++ Tests/Foundation/CPStringTest.j | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/Foundation/CPString.j b/Foundation/CPString.j index 2a6607dc7..768dd9cfc 100644 --- a/Foundation/CPString.j +++ b/Foundation/CPString.j @@ -28,6 +28,8 @@ @import "CPURL.j" @import "CPValue.j" +#define _CPMaxRange(aRange) ((aRange).location + (aRange).length) + /*! A case insensitive search @global @@ -297,6 +299,9 @@ var CPStringRegexSpecialCharacters = [ */ - (CPString)substringWithRange:(CPRange)aRange { + if (aRange.location < 0 || _CPMaxRange(aRange) > length) + [CPException raise:CPRangeException reason:"aRange out of bounds"]; + return substr(aRange.location, aRange.length); } diff --git a/Tests/Foundation/CPStringTest.j b/Tests/Foundation/CPStringTest.j index b84b45606..1389d493b 100644 --- a/Tests/Foundation/CPStringTest.j +++ b/Tests/Foundation/CPStringTest.j @@ -417,6 +417,18 @@ hitRange = [testString rangeOfString:@"i" options:0 range:CPMakeRange(10, 20)]; [self assert:12 equals:hitRange.location message:@"search for 'i' in partial range (location)"]; [self assert:1 equals:hitRange.length message:@"search for 'i' in partial range (position)"]; + + var sawException = false; + try + { + hitRange = [testString rangeOfString:@"i" options:0 range:CPMakeRange(50, 60)]; + } + catch (anException) + { + sawException = true; + [self assert:CPRangeException equals:[anException name]]; + } + [self assertTrue:sawException message:"expected CPRangeException"]; } @end