diff --git a/pkgs/csslib/CHANGELOG.md b/pkgs/csslib/CHANGELOG.md index 7248531c7..8d70a85d7 100644 --- a/pkgs/csslib/CHANGELOG.md +++ b/pkgs/csslib/CHANGELOG.md @@ -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 diff --git a/pkgs/csslib/lib/src/token_kind.dart b/pkgs/csslib/lib/src/token_kind.dart index 541e0bbcb..801f896bb 100644 --- a/pkgs/csslib/lib/src/token_kind.dart +++ b/pkgs/csslib/lib/src/token_kind.dart @@ -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]) { - final hexDigits = '0123456789abcdef'; - - var result = []; - - 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) { diff --git a/pkgs/csslib/test/hex_formatting_test.dart b/pkgs/csslib/test/hex_formatting_test.dart new file mode 100644 index 000000000..80270da17 --- /dev/null +++ b/pkgs/csslib/test/hex_formatting_test.dart @@ -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'); + }); +}