Skip to content

Commit

Permalink
4.4.2
Browse files Browse the repository at this point in the history
  • Loading branch information
molicechen committed Dec 23, 2021
1 parent 95c98d5 commit 75aa32b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
18 changes: 10 additions & 8 deletions QMUIKit/UIKitExtensions/QMUIStringPrivate.m
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ + (void)qmuisafety_NSString {

// index 越界
{
BOOL isValidddatedIndex = index < selfObject.length;
BOOL isValidddatedIndex = index <= selfObject.length;
if (!isValidddatedIndex) {
NSString *logString = [NSString stringWithFormat:@"%@ 传入了一个超过字符串长度的 index: %@,原字符串为: %@(%@)", NSStringFromSelector(originCMD), @(index), selfObject, @(selfObject.length)];
NSAssert(NO, logString);
Expand All @@ -171,13 +171,15 @@ + (void)qmuisafety_NSString {

// 保护从 emoji 等 ComposedCharacterSequence 中间裁剪的场景
{
NSRange range = [selfObject rangeOfComposedCharacterSequenceAtIndex:index];
BOOL isValidddatedIndex = range.location == index || NSMaxRange(range) == index;
if (!isValidddatedIndex) {
NSString *logString = [NSString stringWithFormat:@"试图在 ComposedCharacterSequence 中间用 %@ 裁剪字符串,可能导致乱码、crash。原字符串为“%@”(%@),index 为 %@,命中的 ComposedCharacterSequence range 为 %@", NSStringFromSelector(originCMD), selfObject, @(selfObject.length), @(index), NSStringFromRange(range)];
NSAssert(NO, logString);
QMUILogWarn(@"QMUIStringSafety", @"%@", logString);
index = range.location;
if (index < selfObject.length) {
NSRange range = [selfObject rangeOfComposedCharacterSequenceAtIndex:index];
BOOL isValidddatedIndex = range.location == index || NSMaxRange(range) == index;
if (!isValidddatedIndex) {
NSString *logString = [NSString stringWithFormat:@"试图在 ComposedCharacterSequence 中间用 %@ 裁剪字符串,可能导致乱码、crash。原字符串为“%@”(%@),index 为 %@,命中的 ComposedCharacterSequence range 为 %@", NSStringFromSelector(originCMD), selfObject, @(selfObject.length), @(index), NSStringFromRange(range)];
NSAssert(NO, logString);
QMUILogWarn(@"QMUIStringSafety", @"%@", logString);
index = range.location;
}
}
}

Expand Down
3 changes: 2 additions & 1 deletion QMUIKitTests/UIKitExtensions/NSStringTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ - (void)testStringSafety {
NSString *string = @"A😊B";

XCTAssertNoThrow([string substringFromIndex:0]);
XCTAssertThrows([string substringFromIndex:string.length]); // 越界的识别
XCTAssertNoThrow([string substringFromIndex:string.length]); // 系统自身对 length 的参数做了保护,返回空字符串
XCTAssertThrows([string substringFromIndex:5]); // 越界的识别
XCTAssertNoThrow([string substringFromIndex:1]);
XCTAssertThrows([string substringFromIndex:2]); // emoji 中间裁剪的识别
XCTAssertNoThrow([string substringFromIndex:3]);
Expand Down

0 comments on commit 75aa32b

Please sign in to comment.