Skip to content

Commit

Permalink
Refactor fix for removal of sprintf
Browse files Browse the repository at this point in the history
`UuidParsing.parseHexToBytes` can handle Strings without `0x` prefix.
  • Loading branch information
julemand101 authored and daegalus committed Nov 20, 2024
1 parent 615057a commit 77c3a33
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions lib/v8.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ class UuidV8 {
var buf = Uint8List(16);
DateTime time = options?.time ?? DateTime.timestamp();

buf.setRange(0, 2, UuidParsing.parseHexToBytes(_toHexlike(time.year, 4)));
buf.setRange(2, 3, UuidParsing.parseHexToBytes(_toHexlike(time.month, 2)));
buf.setRange(3, 4, UuidParsing.parseHexToBytes(_toHexlike(time.day, 2)));
buf.setRange(4, 5, UuidParsing.parseHexToBytes(_toHexlike(time.hour, 2)));
buf.setRange(5, 6, UuidParsing.parseHexToBytes(_toHexlike(time.minute, 2)));
buf.setRange(0, 2, UuidParsing.parseHexToBytes(_padLeft(time.year, 4)));
buf.setRange(2, 3, UuidParsing.parseHexToBytes(_padLeft(time.month, 2)));
buf.setRange(3, 4, UuidParsing.parseHexToBytes(_padLeft(time.day, 2)));
buf.setRange(4, 5, UuidParsing.parseHexToBytes(_padLeft(time.hour, 2)));
buf.setRange(5, 6, UuidParsing.parseHexToBytes(_padLeft(time.minute, 2)));

var randomBytes = options?.randomBytes ??
(goptions?.rng?.generate() ?? V8State.random.generate());
Expand All @@ -54,18 +54,16 @@ class UuidV8 {
buf.setRange(6, 7, [buf.getRange(6, 7).last & 0x0f | 0x80]);
buf.setRange(8, 9, [buf.getRange(8, 9).last & 0x3f | 0x80]);

buf.setRange(7, 8, UuidParsing.parseHexToBytes(_toHexlike(time.second, 2)));
buf.setRange(7, 8, UuidParsing.parseHexToBytes(_padLeft(time.second, 2)));
var milliBytes = UuidParsing.parseHexToBytes(
_toHexlike(time.millisecond, 4),
_padLeft(time.millisecond, 4),
);
milliBytes[0] = milliBytes[0] & 0x0f | buf.getRange(8, 9).last & 0xf0;
buf.setRange(8, 10, milliBytes);

return UuidParsing.unparse(buf);
}

// Custom hex(like) converting function which converts '2024' into '0x2024'
// and '3' into '0x03' depending on amount of padding.
static String _toHexlike(int value, int padding) =>
'0x${value.toString().padLeft(padding, '0')}';
static String _padLeft(int value, int padding) =>
value.toString().padLeft(padding, '0');
}

0 comments on commit 77c3a33

Please sign in to comment.