Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up BTCHexFromData by 5.5x (-85%) #114

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 31 additions & 15 deletions CoreBitcoin/BTCData.m
Original file line number Diff line number Diff line change
Expand Up @@ -183,20 +183,36 @@ static inline int BTCFairCoinFlip() {
return [[NSData alloc] initWithBytesNoCopy:buf length:len/2];
}


NSString* BTCHexFromDataWithFormat(NSData* data, const char* format) {
if (!data) return nil;

NSUInteger length = data.length;
if (length == 0) return @"";

NSMutableData* resultdata = [NSMutableData dataWithLength:length * 2];
char *dest = resultdata.mutableBytes;
unsigned const char *src = data.bytes;
for (int i = 0; i < length; ++i) {
sprintf(dest + i*2, format, (unsigned int)(src[i]));
static const char hexValues[16] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f',
};

static const char upperHexValues[16] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F',
};

static NSString* BTCHexFromDataWithCharset(NSData* data, const char* charset) {
size_t inLength = data.length;
size_t length = inLength * 2;
uint8_t *outString = malloc(length);
const unsigned char *bytes = data.bytes;
for (uint32_t i = 0; i < inLength; i++) {
unsigned char byte = bytes[i];
outString[i*2] = charset[byte >> 4];
outString[i*2+1] = charset[byte & 0x0F];
}
return [[NSString alloc] initWithData:resultdata encoding:NSASCIIStringEncoding];
return [[NSString alloc]
initWithBytesNoCopy:outString
length:length
encoding:NSASCIIStringEncoding
freeWhenDone:YES
];
}

NSString* BTCHexStringFromData(NSData* data) { // deprecated
Expand All @@ -208,11 +224,11 @@ static inline int BTCFairCoinFlip() {
}

NSString* BTCHexFromData(NSData* data) {
return BTCHexFromDataWithFormat(data, "%02x");
return BTCHexFromDataWithCharset(data, hexValues);
}

NSString* BTCUppercaseHexFromData(NSData* data) {
return BTCHexFromDataWithFormat(data, "%02X");
return BTCHexFromDataWithCharset(data, upperHexValues);
}


Expand Down