Skip to content
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions pkgs/csslib/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 1.0.3-wip

- Fix `TokenKind.decimalToHex` hanging on negative input.
- Speed up named CSS color lookups by indexing the color table.
- Recognize the `rebeccapurple` color keyword.
- Correctly parse unit-like type selectors (`rem`, `vw`, `dpi`, etc.) at the
Expand Down
30 changes: 8 additions & 22 deletions pkgs/csslib/lib/src/token_kind.dart
Original file line number Diff line number Diff line change
Expand Up @@ -579,30 +579,16 @@ class TokenKind {
static String? hexToColorName(Object hexValue) =>
_colorNamesByValue[hexValue];

/// Converts [number] to lowercase hexadecimal, zero-padded to [minDigits].
///
/// A negative [number] keeps its sign in front; only the digits are padded.
static String decimalToHex(int number, [int minDigits = 1]) {
Comment thread
palmoni5 marked this conversation as resolved.
Resolved
final hexDigits = '0123456789abcdef';

var result = <String>[];

var dividend = number >> 4;
var remain = number % 16;
result.add(hexDigits[remain]);
while (dividend != 0) {
remain = dividend % 16;
dividend >>= 4;
result.add(hexDigits[remain]);
final hex = number.toRadixString(16);
if (number < 0) {
// Pad the digits, not the sign.
return '-${hex.substring(1).padLeft(minDigits, '0')}';
}

var invertResult = StringBuffer();
var paddings = minDigits - result.length;
while (paddings-- > 0) {
invertResult.write('0');
}
for (var i = result.length - 1; i >= 0; i--) {
invertResult.write(result[i]);
}

return invertResult.toString();
return hex.padLeft(minDigits, '0');
}

static String kindToString(int kind) => switch (kind) {
Expand Down
21 changes: 21 additions & 0 deletions pkgs/csslib/test/hex_formatting_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:csslib/parser.dart';
import 'package:test/test.dart';

void main() {
test('hex conversion retains color padding', () {
expect(TokenKind.decimalToHex(0), '0');
expect(TokenKind.decimalToHex(0, 6), '000000');
expect(TokenKind.decimalToHex(15, 2), '0f');
expect(TokenKind.decimalToHex(0xabcdef, 6), 'abcdef');
expect(TokenKind.decimalToHex(0xffffff, 6), 'ffffff');
});

test('negative hex conversion terminates safely', () {
expect(TokenKind.decimalToHex(-1), '-1');
expect(TokenKind.decimalToHex(-255, 4), '-00ff');
});
}
Loading