Skip to content

Commit

Permalink
Merge pull request #14 from getditto/hc/utf8-string-fixes
Browse files Browse the repository at this point in the history
Problem: Strings in the CBOR to JSON conversion code were being appended incorrectly
  • Loading branch information
podkovyrin authored Feb 19, 2020
2 parents 1a234a0 + 82b6473 commit 8e06311
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
13 changes: 13 additions & 0 deletions Example/Tests/DSCborDecodingTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,17 @@ - (void)testEncodingAndDecodingRandomData {
XCTAssertNil(error);
}

- (void)testEncodingAndDecodingADictionaryWithNonAsciiKeys {
NSDictionary<NSString *, NSString *> *dict = @{
@"£test£": @"¡€#¢•©˙∆å߃∫~µç≈Ω"
};
NSData *encoded = [dict ds_cborEncodedObject];
XCTAssertNotNil(encoded);

NSError *error = nil;
id decoded = [encoded ds_decodeCborError:&error];
XCTAssertEqualObjects(decoded, dict);
XCTAssertNil(error);
}

@end
14 changes: 9 additions & 5 deletions TinyCborObjc/cbortojson_nsstring.m
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,8 @@ static CborError map_to_json(NSMutableString *out, CborValue *it, int flags, Con
return err;

/* first, print the key */
[out appendFormat:@"\"%s\":", key];
NSString *utf8Key = [[NSString alloc] initWithCString:key encoding:NSUTF8StringEncoding];
[out appendFormat:@"\"%@\":", utf8Key];

/* then, print the value */
CborType valueType = cbor_value_get_type(it);
Expand All @@ -445,10 +446,10 @@ static CborError map_to_json(NSMutableString *out, CborValue *it, int flags, Con
/* finally, print any metadata we may have */
if (flags & CborConvertAddMetadata) {
if (!err && keyType != CborTextStringType) {
[out appendFormat:@",\"%s$keycbordump\":true", key];
[out appendFormat:@",\"%@$keycbordump\":true", utf8Key];
}
if (!err && status->flags) {
[out appendFormat:@",\"%s$cbor\":{", key];
[out appendFormat:@",\"%@$cbor\":{", utf8Key];
if (add_value_metadata(out, valueType, status) != CborNoError ||
putc_to_nsstring('}', out) < 0)
err = CborErrorIO;
Expand Down Expand Up @@ -532,11 +533,14 @@ static CborError value_to_json(NSMutableString *out, CborValue *it, int flags, C
}
if (err)
return err;

NSString *utf8Str = [[NSString alloc] initWithCString:str encoding:NSUTF8StringEncoding];

if (type == CborByteStringType) {
[out appendFormat:@"\"%@%s\"", DSCborBase64DataMarker, str];
[out appendFormat:@"\"%@%@\"", DSCborBase64DataMarker, utf8Str];
}
else {
[out appendFormat:@"\"%s\"", str];
[out appendFormat:@"\"%@\"", utf8Str];
}
err = CborNoError;
free(str);
Expand Down

0 comments on commit 8e06311

Please sign in to comment.