Implement FNV-1a hash extension for String and update key hashing in BinaryTable

This commit is contained in:
ImBenji
2025-09-17 23:23:42 +01:00
parent 5cc86a109f
commit d6262421e7

View File

@@ -17,6 +17,7 @@ This file is part of the Binary Table package for Dart.
*/ */
import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
@@ -453,6 +454,22 @@ extension FreeList on List<BT_FreeListEntry> {
} }
extension fnv1a on String {
int get bt_hash {
List<int> bytes = utf8.encode(this);
int hash = 0xcbf29ce484222325; // FNV offset basis
for (int byte in bytes) {
hash ^= byte;
hash *= 0x100000001b3; // FNV prime
}
return hash;
}
}
class BinaryTable { class BinaryTable {
RandomAccessFile _file; RandomAccessFile _file;
@@ -732,7 +749,7 @@ class BinaryTable {
antiFreeListScope(() { antiFreeListScope(() {
Map<int, BT_Pointer> addressTable = _addressTable; Map<int, BT_Pointer> addressTable = _addressTable;
int keyHash = key.hashCode; int keyHash = key.bt_hash;
if (addressTable.containsKey(keyHash)) { if (addressTable.containsKey(keyHash)) {
throw Exception('Key already exists'); throw Exception('Key already exists');
@@ -757,7 +774,7 @@ class BinaryTable {
operator [](String key) { operator [](String key) {
Map<int, BT_Pointer> addressTable = _addressTable; Map<int, BT_Pointer> addressTable = _addressTable;
int keyHash = key.hashCode; int keyHash = key.bt_hash;
if (!addressTable.containsKey(keyHash)) { if (!addressTable.containsKey(keyHash)) {
throw Exception('Key does not exist'); throw Exception('Key does not exist');
@@ -774,7 +791,7 @@ class BinaryTable {
antiFreeListScope(() { antiFreeListScope(() {
Map<int, BT_Pointer> addressTable = _addressTable; Map<int, BT_Pointer> addressTable = _addressTable;
int keyHash = key.hashCode; int keyHash = key.bt_hash;
if (!addressTable.containsKey(keyHash)) { if (!addressTable.containsKey(keyHash)) {
throw Exception('Key does not exist'); throw Exception('Key does not exist');