Skip to content

Commit

Permalink
Crypto module: make toHex routines use appendCodePointValues()
Browse files Browse the repository at this point in the history
This routine, provided by chapel-lang#24104, makes these string constructions much faster.

---
Signed-off-by: Paul Cassella <gitgitgit@manetheren.bigw.org>
  • Loading branch information
cassella committed Jan 23, 2024
1 parent 77511bf commit 58d2b9a
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions modules/packages/Crypto.chpl
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,11 @@ module Crypto {
proc toHex() throws {
var buffHex: [this.buffDomain] string;
for i in this.buffDomain do {
buffHex[i] = try "%02xu".format(this.buff[i]);
const byte = this.buff[i];
const nib1 = convertNibble((byte>>4)&0xf, uppercase=false);
const nib2 = convertNibble(byte&0xf, uppercase=false);

buffHex[i].appendCodepointValues(nib1, nib2);
}
return buffHex;
}
Expand All @@ -238,7 +242,11 @@ module Crypto {
proc toHexString() throws {
var buffHexString: string;
for i in this.buffDomain do {
buffHexString += try "%02xu".format(this.buff[i]);
const byte = this.buff[i];
const nib1 = convertNibble((byte>>4)&0xf, uppercase=false);
const nib2 = convertNibble(byte&0xf, uppercase=false);

buffHexString.appendCodepointValues(nib1, nib2);
}
return buffHexString;
}
Expand Down Expand Up @@ -1348,4 +1356,24 @@ proc bfEncrypt(plaintext: CryptoBuffer, key: CryptoBuffer, IV: CryptoBuffer, cip

extern proc RAND_seed(const buf: c_ptr(void), num: c_int);
}

/*
* Convert a nibble into a character in its hexadecimal representation.
* Copied from Bytes.chpl.
* TODO: Put this in a shared location both can use.
*/
@chpldoc.nodoc
private proc convertNibble(in nib:uint(8), uppercase: bool): uint(8) {
nib = nib & 0xf;
if 0 <= nib && nib <= 9 {
param zero:uint(8) = b"0"(0); // aka 0x30
return zero + nib;
} else if 10 <= nib && nib <= 15 {
param a:uint(8) = b"a"(0); // aka 0x61
param A:uint(8) = b"A"(0); // aka 0x41
return (if uppercase then A else a) + nib - 10;
}

return 0;
}
}

0 comments on commit 58d2b9a

Please sign in to comment.