Skip to content

Commit 1bba1a7

Browse files
committed
Added clamping to textstorage.attributedSubstring to avoid out-of-bounds crashes (#305)
1 parent 4a64c4c commit 1bba1a7

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

Proton/Sources/ObjC/PRTextStorage.m

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,17 @@ - (void)edited:(NSTextStorageEditActions)editedMask range:(NSRange)editedRange c
7373
[self.textStorageDelegate textStorage:self edited:editedMask in:editedRange changeInLength:delta];
7474
}
7575

76+
- (NSAttributedString *)attributedSubstringFromRange:(NSRange)range {
77+
NSRange rangeToUse =[self clampedWithUpperBound:self.length location:range.location length:range.length];
78+
return [super attributedSubstringFromRange: rangeToUse];
79+
}
80+
81+
- (NSRange)clampedWithUpperBound:(NSInteger)upperBound location:(NSInteger)location length:(NSInteger)length {
82+
NSInteger clampedLocation = MAX(MIN(location, upperBound), 0);
83+
NSInteger clampedLength = MAX(MIN(length, upperBound - clampedLocation), 0);
84+
return NSMakeRange(clampedLocation, clampedLength);
85+
}
86+
7687
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString {
7788
// TODO: Add undo behaviour
7889

Proton/Tests/Core/TextStorageTests.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,13 @@ class TextStorageTests: XCTestCase {
131131
XCTAssertEqual(attrs[NSAttributedString.Key("attr2")] as? Int, 2)
132132
XCTAssertEqual(attrs[NSAttributedString.Key("attr3")] as? Int, 3)
133133
}
134+
135+
func testReturnsSubstringWithClampedRange() {
136+
let textStorage = PRTextStorage()
137+
let testString = NSAttributedString(string: "test string")
138+
textStorage.replaceCharacters(in: .zero, with: testString)
139+
140+
let substring = textStorage.attributedSubstring(from: NSRange(location: 5, length: 50))
141+
XCTAssertEqual(substring.string, "string")
142+
}
134143
}

0 commit comments

Comments
 (0)