Skip to content

Commit

Permalink
Added clamping to textstorage.attributedSubstring to avoid out-of-bou…
Browse files Browse the repository at this point in the history
…nds crashes (#305)
  • Loading branch information
rajdeep committed Apr 8, 2024
1 parent 4a64c4c commit 1bba1a7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Proton/Sources/ObjC/PRTextStorage.m
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ - (void)edited:(NSTextStorageEditActions)editedMask range:(NSRange)editedRange c
[self.textStorageDelegate textStorage:self edited:editedMask in:editedRange changeInLength:delta];
}

- (NSAttributedString *)attributedSubstringFromRange:(NSRange)range {
NSRange rangeToUse =[self clampedWithUpperBound:self.length location:range.location length:range.length];
return [super attributedSubstringFromRange: rangeToUse];
}

- (NSRange)clampedWithUpperBound:(NSInteger)upperBound location:(NSInteger)location length:(NSInteger)length {
NSInteger clampedLocation = MAX(MIN(location, upperBound), 0);
NSInteger clampedLength = MAX(MIN(length, upperBound - clampedLocation), 0);
return NSMakeRange(clampedLocation, clampedLength);
}

- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString {
// TODO: Add undo behaviour

Expand Down
9 changes: 9 additions & 0 deletions Proton/Tests/Core/TextStorageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,13 @@ class TextStorageTests: XCTestCase {
XCTAssertEqual(attrs[NSAttributedString.Key("attr2")] as? Int, 2)
XCTAssertEqual(attrs[NSAttributedString.Key("attr3")] as? Int, 3)
}

func testReturnsSubstringWithClampedRange() {
let textStorage = PRTextStorage()
let testString = NSAttributedString(string: "test string")
textStorage.replaceCharacters(in: .zero, with: testString)

let substring = textStorage.attributedSubstring(from: NSRange(location: 5, length: 50))
XCTAssertEqual(substring.string, "string")
}
}

0 comments on commit 1bba1a7

Please sign in to comment.