From a5a43de26ecda590234341db18f8bb29937eb7fb Mon Sep 17 00:00:00 2001 From: Francisco Ryan Tolmasky I Date: Wed, 8 Jul 2009 11:52:47 -0700 Subject: [PATCH] Fix for objectAtIndex: throwing out of range exceptions. Closes #105. Reviewed by me. --- Foundation/CPArray.j | 4 ++++ Tests/Foundation/CPArrayTest.j | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/Foundation/CPArray.j b/Foundation/CPArray.j index 29139a5f5..efe2e8196 100755 --- a/Foundation/CPArray.j +++ b/Foundation/CPArray.j @@ -26,6 +26,7 @@ @import "CPSortDescriptor.j" @import "CPException.j" + /* @ignore */ @implementation _CPArrayEnumerator : CPEnumerator { @@ -520,6 +521,9 @@ */ - (id)objectAtIndex:(int)anIndex { + if (anIndex >= length) + [CPException raise:CPRangeException reason:@"index (" + anIndex + @") beyond bounds (" + length + @")"]; + return self[anIndex]; } diff --git a/Tests/Foundation/CPArrayTest.j b/Tests/Foundation/CPArrayTest.j index eba367e5c..04ea56486 100644 --- a/Tests/Foundation/CPArrayTest.j +++ b/Tests/Foundation/CPArrayTest.j @@ -115,6 +115,46 @@ equals:2]; } +- (void)testIndexOutOfBounds +{ + try + { + [[] objectAtIndex:0]; + [self assert:false]; + } + catch (anException) + { + [self assert:[anException name] equals:CPRangeException]; + [self assert:[anException reason] equals:@"index (0) beyond bounds (0)"]; + } + + [[0, 1, 2] objectAtIndex:0]; + [[0, 1, 2] objectAtIndex:1]; + [[0, 1, 2] objectAtIndex:2]; + + try + { + [[0, 1, 2] objectAtIndex:3]; + [self assert:false]; + } + catch (anException) + { + [self assert:[anException name] equals:CPRangeException]; + [self assert:[anException reason] equals:@"index (3) beyond bounds (3)"]; + } + + try + { + [[0, 1, 2] objectAtIndex:4]; + [self assert:false]; + } + catch (anException) + { + [self assert:[anException name] equals:CPRangeException]; + [self assert:[anException reason] equals:@"index (4) beyond bounds (3)"]; + } +} + @end @implementation CPArray (reverse)