diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml
index c07f7bffe..a32586d85 100644
--- a/.github/workflows/coverage.yml
+++ b/.github/workflows/coverage.yml
@@ -20,7 +20,7 @@ jobs:
pub global activate test_coverage
pub global run test_coverage --exclude "**/js/**"
working-directory: hive
- - uses: codecov/codecov-action@v1.0.0
+ - uses: codecov/codecov-action@v1.0.0
with:
- token: ${{ secrets.CODECOV_TOKEN }}
+ token: ${{ secrets.CODECOV_TOKEN }}
file: hive/coverage/lcov.info
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 55b7e48d4..f36b6e0f9 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -5,12 +5,10 @@ on: [push, pull_request]
jobs:
test-hive:
runs-on: ubuntu-latest
-
strategy:
matrix:
test-platform: [vm, chrome]
- dart-channel: [stable, unstable]
-
+ dart-channel: [unstable]
steps:
- uses: actions/checkout@v1
- name: Install Dart
@@ -25,15 +23,18 @@ jobs:
run: |
export PATH="$PATH:/usr/lib/dart/bin"
pub get
- pub run test -p ${{ matrix.test-platform }}
+ pub run --no-sound-null-safety test -p ${{ matrix.test-platform }}
working-directory: hive
check-score:
- if: false
runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ package: [hive, hive_generator, hive_flutter]
steps:
- uses: actions/checkout@v1
- - uses: axel-op/dart_package_analyzer@stable
+ - uses: axel-op/dart-package-analyzer@v3
with:
githubToken: ${{ secrets.GITHUB_TOKEN }}
+ relativePath: ${{ matrix.package }}
minAnnotationLevel: warning
diff --git a/hive/CHANGELOG.md b/hive/CHANGELOG.md
index ae0f28dd1..76f07bbf2 100644
--- a/hive/CHANGELOG.md
+++ b/hive/CHANGELOG.md
@@ -1,16 +1,45 @@
+# 2.0.0
+
+### Fixes
+
+- Stable null-safety version
+
+# 1.6.0-nullsafety.2
+
+### Fixes
+
+- Added `defaultValue` property to `@HiveField()` annotation - [#557](https://github.com/hivedb/hive/pull/557)
+
+# 1.6.0-nullsafety.1
+
+### Fixes
+
+- Changed `meta` dependency version to `^1.3.0-nullsafety` to support null-safety
+
+# 1.6.0-nullsafety.0
+
+### Breaking changes
+
+- Migrate to null-safety - [#521](https://github.com/hivedb/hive/pull/521)
+- Update minimum Dart sdk constraint to 2.12.0-0.
+- In order to generate null-safe code use hive_generator >= 0.9.0-nullsafety.0
+
# 1.5.0-pre
### Enhancements
+
- Timezone support for DateTime - [#419](https://github.com/hivedb/hive/issues/419)
# 1.4.4+1
### Fixes
+
- Browser support for `BackendManager.boxExists(boxName, path)` - [#451](https://github.com/hivedb/hive/issues/451)
# 1.4.4
### Fixes
+
- Edge browser support - [#357](https://github.com/hivedb/hive/issues/357)
# 1.4.3
@@ -27,70 +56,85 @@
# 1.4.2
### Fixes
+
- Fixed dependency issues and minor improvements
# 1.4.1+1
### Other
+
- Added docs to all public members
# 1.4.1
### Enhancements
+
- Minor performance improvements
### Fixes
+
- When a database operation failed, subsequent operations would not be performed
### Other
+
- Fixed GitHub homepage path
# 1.4.0+1
### Enhancements
+
- Minor performance improvements
### Fixes
+
- Allow more versions of `crypto`
# 1.4.0
### Enhancements
+
- ~1000% encryption / decryption performance improvement
- Added option to implement custom encryption algorithm
- Added `box.valuesBetween(startKey, endKey)`
- Allow tree shaking to drop encryption engine if no encryption is used
### Fixes
+
- `Hive.deleteBoxFromDisk()` did not work for boxes with upper-case names
### More
+
- Deprecated `encryptionKey` parameter. Use `Hive.openBox('name', encryptionCipher: HiveAesCipher(yourKey))`.
- Dropped `pointycastle` dependency
- Dropped `path` dependency
# 1.3.0
-*Use latest version of `hive_generator`*
+_Use latest version of `hive_generator`_
### Breaking changes
+
- `TypeAdapters` and `@HiveType()` now require a `typeId`
- `Hive.registerAdapter()` does not need a `typeId` anymore.
- Removed `BinaryReader.readAsciiString()`
- Removed `BinaryWriter.writeAsciiString()`
### Enhancements
+
- New documentation with tutorials and live code
### Fixes
+
- `box.clear()` resets auto increment counter
### More
+
- Not calling `Hive.init()` results in better exception
# 1.2.0
### Breaking changes
+
- Removed the `Hive.path` getter
- Removed `Hive.openBoxFromBytes()` (use the `bytes` parameter of `Hive.openBox()` instead)
- `LazyBox` and `Box` now have a common parent class: `BoxBase`
@@ -99,6 +143,7 @@
- Box name bug resolved (more information below)
### Enhancements
+
- Support for relationships, `HiveLists` (see docs for details)
- Support for inheritance
- Lazy boxes can now have a type argument `LazyBox`
@@ -107,6 +152,7 @@
- Improved documentation
### Fixes
+
- `HiveObjects` have not been initialized correctly in lazy boxes
- Fixed bug where uppercase box name resulted in an uppercase filename
- Fixed compaction bug which caused corrupted boxes
@@ -114,9 +160,11 @@
- Fixed bug where not all `BoxEvent`s have been broadcasted
### More
+
- Changed type of `encryptionKey` from `Uint8List` to `List`
### Important:
+
Due to a bug in previous Hive versions, boxes whose name contains uppercase characters were stored in a file that also contains upper case characters (e.g. 'myBox' -> 'myBox.hive').
To avoid different behavior on case sensitive file systems, Hive should store files with lower case names. This bug has been resolved in version 1.2.0.
@@ -127,52 +175,63 @@ This also applies to the web version.
# 1.1.1
### Breaking changes
+
- `object.delete()` now throws exception if object is not stored in a box
### Fixes
+
- Fixed bug where `object.save()` would fail on subsequent calls
# 1.1.0+2
### Fixes
+
- Fixed bug that it was not possible to open typed boxes (`Box`)
# 1.1.0+1
### Fixes
+
- Fixed bug that corrupted boxes were not detected
# 1.1.0
### Breaking changes
+
- Changed return type of `addAll()` from `List` to `Iterable`.
- Removed the option to register `TypeAdapters` for a specific box. E.g. `box.registerTypeAdapter()`.
- `getAt()`, `putAt()`, `deleteAt()` and `keyAt()` no longer allow indices out of range.
### Enhancements
+
- Added `HiveObject`
- Boxes have now an optional type parameter `Box`
- Support opening boxes from assets
### Fixes
+
- Fixed bug which was caused by not awaiting write operations
- Fixed bug where custom compaction strategy was not applied
- Hive now locks box files while they are open to prevent concurrent access from multiple processes
### More
+
- Improved performance of `putAll()`, `deleteAll()`, `add()`, `addAll()`
- Changed `values` parameter of `addAll()` from `List` to `Iterable`
- Improved documentation
- Preparation for queries
# 1.0.0
+
- First stable release
# 0.5.1+1
+
- Change `keys` parameter of `deleteAll` from `List` to `Iterable`
- Fixed bug in `BinaryWriter`
# 0.5.1
+
- Fixed `Hive.init()` bug in browser
- Fixed a bug with large lists or strings
- Improved box opening time in the browser
@@ -181,6 +240,7 @@ This also applies to the web version.
- Added integration tests
# 0.5.0
+
- Added `keyComparator` parameter for custom key order
- Added `isEmpty` and `isNotEmpty` getters to box
- Added support for reading and writing subclasses
@@ -194,13 +254,16 @@ This also applies to the web version.
- **Breaking:** Binary format changed
# 0.4.1+1
+
- Document all public APIs
- Fixed flutter_web error
# 0.4.1
+
- Allow different versions of the `path` package
# 0.4.0
+
- Added `BigInt` support
- Added `compactionStrategy` parameter
- Added automatic crash recovery
@@ -217,9 +280,11 @@ This also applies to the web version.
- **Breaking:** API changes
# 0.3.0+1
+
- Bugfix: `Hive['yourBox']` didn't work with uppercase box names
# 0.3.0
+
- Big step towards stable API
- Support for transactions
- Annotations for hive_generator
@@ -229,6 +294,7 @@ This also applies to the web version.
- **Breaking:** Binary format changed
# 0.2.0
+
- Support for dart2js
- Improved performance
- Added `inMemory` option
@@ -237,7 +303,9 @@ This also applies to the web version.
- **Breaking:** Removed Migrator
# 0.1.1
+
- Downgrade to `meta: ^1.1.6` to support flutter
# 0.1.0
+
- First release
diff --git a/hive/README.md b/hive/README.md
index 731135956..a77f2c8e1 100644
--- a/hive/README.md
+++ b/hive/README.md
@@ -3,7 +3,7 @@
Fast, Enjoyable & Secure NoSQL Database
-[![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/hivedb/hive/Dart%20CI/master?label=tests&labelColor=333940&logo=github)](https://github.com/hivedb/hive/actions) [![Codecov branch](https://img.shields.io/codecov/c/github/hivedb/hive/master?labelColor=333940&logo=codecov&logoColor=white)](https://codecov.io/gh/hivedb/hive) [![Pub Version](https://img.shields.io/pub/v/hive?label=pub.dev&labelColor=333940&logo=dart)](https://pub.dev/packages/hive) [![GitHub](https://img.shields.io/github/license/hivedb/hive?color=%23007A88&labelColor=333940&logo=apache)](https://github.com/hivedb/hive/blob/master/LICENSE)
+[![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/hivedb/hive/Dart%20CI/nndb?label=tests&labelColor=333940&logo=github)](https://github.com/hivedb/hive/actions) [![Codecov branch](https://img.shields.io/codecov/c/github/hivedb/hive/nndb?labelColor=333940&logo=codecov&logoColor=white)](https://codecov.io/gh/hivedb/hive) [![Pub Version](https://img.shields.io/pub/v/hive?label=pub.dev&labelColor=333940&logo=dart)](https://pub.dev/packages/hive) [![GitHub](https://img.shields.io/github/license/hivedb/hive?color=%23007A88&labelColor=333940&logo=apache)](https://github.com/hivedb/hive/blob/master/LICENSE)
Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by [Bitcask](https://en.wikipedia.org/wiki/Bitcask).
@@ -18,8 +18,8 @@ Hive is a lightweight and blazing fast key-value database written in pure Dart.
- 🎈 **NO** native dependencies
- 🔋 Batteries included
-
## Getting Started
+
Check out the [Quick Start](https://docs.hivedb.dev) documentation to get started.
## Usage
@@ -71,6 +71,7 @@ print(box.getAt(0)) // Dave - 30
```
## Hive ❤️ Flutter
+
Hive was written with Flutter in mind. It is a perfect fit if you need a lightweight datastore for your app. After adding the required dependencies and initializing Hive, you can use Hive in your project:
```dart
@@ -97,18 +98,16 @@ class SettingsPage extends StatelessWidget {
Boxes are cached and therefore fast enough to be used directly in the `build()` method of Flutter widgets.
-
## Benchmark
-|1000 read iterations |1000 write iterations|
-|:------------:|:------------:|
-| ![](https://raw.githubusercontent.com/hivedb/hive/master/.github/benchmark_read.png) | ![](https://raw.githubusercontent.com/hivedb/hive/master/.github/benchmark_write.png) |
+| 1000 read iterations | 1000 write iterations |
+| :--------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------: |
+| ![](https://raw.githubusercontent.com/hivedb/hive/master/.github/benchmark_read.png) | ![](https://raw.githubusercontent.com/hivedb/hive/master/.github/benchmark_write.png) |
| SharedPreferences is on par with Hive when it comes to read performance. SQLite performs much worse. | Hive greatly outperforms SQLite and SharedPreferences when it comes to writing or deleting. |
The benchmark was performed on a Oneplus 6T with Android Q. You can [run the benchmark yourself](https://github.com/hivedb/hive_benchmark).
-*Take this benchmark with a grain of salt. It is very hard to compare databases objectively since they were made for different purposes.
-
+\*Take this benchmark with a grain of salt. It is very hard to compare databases objectively since they were made for different purposes.
### Licence
diff --git a/hive/example/lib/main.dart b/hive/example/lib/main.dart
index 45a479186..25c8564cb 100644
--- a/hive/example/lib/main.dart
+++ b/hive/example/lib/main.dart
@@ -6,6 +6,8 @@ part 'main.g.dart';
@HiveType(typeId: 1)
class Person {
+ Person({required this.name, required this.age, required this.friends});
+
@HiveField(0)
String name;
@@ -29,10 +31,11 @@ void main() async {
var box = await Hive.openBox('testBox');
- var person = Person()
- ..name = 'Dave'
- ..age = 22
- ..friends = ['Linda', 'Marc', 'Anne'];
+ var person = Person(
+ name: 'Dave',
+ age: 22,
+ friends: ['Linda', 'Marc', 'Anne'],
+ );
await box.put('dave', person);
diff --git a/hive/example/lib/main.g.dart b/hive/example/lib/main.g.dart
index 98875ee53..5c486bddf 100644
--- a/hive/example/lib/main.g.dart
+++ b/hive/example/lib/main.g.dart
@@ -8,18 +8,19 @@ part of 'main.dart';
class PersonAdapter extends TypeAdapter {
@override
- final typeId = 1;
+ final int typeId = 1;
@override
Person read(BinaryReader reader) {
- var numOfFields = reader.readByte();
- var fields = {
- for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
+ final numOfFields = reader.readByte();
+ final fields = {
+ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
- return Person()
- ..name = fields[0] as String
- ..age = fields[1] as int
- ..friends = (fields[2] as List)?.cast();
+ return Person(
+ name: fields[0] as String,
+ age: fields[1] as int,
+ friends: (fields[2] as List).cast(),
+ );
}
@override
@@ -33,4 +34,14 @@ class PersonAdapter extends TypeAdapter {
..writeByte(2)
..write(obj.friends);
}
+
+ @override
+ int get hashCode => typeId.hashCode;
+
+ @override
+ bool operator ==(Object other) =>
+ identical(this, other) ||
+ other is PersonAdapter &&
+ runtimeType == other.runtimeType &&
+ typeId == other.typeId;
}
diff --git a/hive/example/pubspec.yaml b/hive/example/pubspec.yaml
index 91ee7a1bb..497bea585 100644
--- a/hive/example/pubspec.yaml
+++ b/hive/example/pubspec.yaml
@@ -5,4 +5,13 @@ dependencies:
dev_dependencies:
hive_generator: any
- build_runner: any
\ No newline at end of file
+ build_runner: any
+
+environment:
+ sdk: '>=2.12.0-0 <3.0.0'
+
+dependency_overrides:
+ hive:
+ path: ../
+ hive_generator:
+ path: ../../hive_generator
\ No newline at end of file
diff --git a/hive/lib/src/adapters/ignored_type_adapter.dart b/hive/lib/src/adapters/ignored_type_adapter.dart
index 69f07e24e..c4cabfaf6 100644
--- a/hive/lib/src/adapters/ignored_type_adapter.dart
+++ b/hive/lib/src/adapters/ignored_type_adapter.dart
@@ -1,14 +1,14 @@
import 'package:hive/hive.dart';
/// Not part of public API
-class IgnoredTypeAdapter implements TypeAdapter {
+class IgnoredTypeAdapter implements TypeAdapter {
const IgnoredTypeAdapter([this.typeId = 0]);
@override
final int typeId;
@override
- T read(BinaryReader reader) => null;
+ T? read(BinaryReader reader) => null;
@override
void write(BinaryWriter writer, obj) {}
diff --git a/hive/lib/src/annotations/hive_field.dart b/hive/lib/src/annotations/hive_field.dart
index 29c5966d9..f49498c0e 100644
--- a/hive/lib/src/annotations/hive_field.dart
+++ b/hive/lib/src/annotations/hive_field.dart
@@ -5,5 +5,24 @@ class HiveField {
/// The index of this field.
final int index;
- const HiveField(this.index);
+ /// Set `true` to use this enum value as default value instead of null in
+ /// null-safety.
+ ///
+ /// This property currently only used for enum types. In future might be used
+ /// for other properties too. If the defaultValue is not provided the first
+ /// enum will be used as default value.
+ ///
+ /// ```dart
+ /// @HiveType(typeId: 1)
+ /// enum MyEnum {
+ /// @HiveField(0)
+ /// apple,
+ ///
+ /// @HiveField(1, defaultValue: true)
+ /// pear
+ /// }
+ /// ```
+ final bool defaultValue;
+
+ const HiveField(this.index, {this.defaultValue = false});
}
diff --git a/hive/lib/src/annotations/hive_type.dart b/hive/lib/src/annotations/hive_type.dart
index 23fba7ecb..6b4c9c6d4 100644
--- a/hive/lib/src/annotations/hive_type.dart
+++ b/hive/lib/src/annotations/hive_type.dart
@@ -6,7 +6,7 @@ class HiveType {
final int typeId;
/// The name of the generated adapter.
- final String adapterName;
+ final String? adapterName;
/// This parameter can be used to keep track of old fieldIds which must not
/// be reused. The generator will throw an error if a legacy fieldId is
@@ -15,7 +15,7 @@ class HiveType {
/// If [adapterName] is not set, it'll be `"YourClass" + "Adapter"`.
const HiveType({
- @required this.typeId,
+ required this.typeId,
this.adapterName,
//this.legacyFieldIds,
});
diff --git a/hive/lib/src/backend/js/backend_manager.dart b/hive/lib/src/backend/js/backend_manager.dart
index c755860a5..b86d8f9b2 100644
--- a/hive/lib/src/backend/js/backend_manager.dart
+++ b/hive/lib/src/backend/js/backend_manager.dart
@@ -9,11 +9,11 @@ import 'package:hive/src/backend/storage_backend.dart';
class BackendManager implements BackendManagerInterface {
@override
Future open(
- String name, String path, bool crashRecovery, HiveCipher cipher) async {
+ String name, String? path, bool crashRecovery, HiveCipher? cipher) async {
var db =
- await window.indexedDB.open(name, version: 1, onUpgradeNeeded: (e) {
+ await window.indexedDB!.open(name, version: 1, onUpgradeNeeded: (e) {
var db = e.target.result as Database;
- if (!db.objectStoreNames.contains('box')) {
+ if (!db.objectStoreNames!.contains('box')) {
db.createObjectStore('box');
}
});
@@ -22,17 +22,17 @@ class BackendManager implements BackendManagerInterface {
}
@override
- Future deleteBox(String name, String path) {
- return window.indexedDB.deleteDatabase(name);
+ Future deleteBox(String name, String? path) {
+ return window.indexedDB!.deleteDatabase(name);
}
@override
- Future boxExists(String name, String path) async {
+ Future boxExists(String name, String? path) async {
// https://stackoverflow.com/a/17473952
try {
var _exists = true;
- await window.indexedDB.open(name, version: 1, onUpgradeNeeded: (e) {
- e.target.transaction.abort();
+ await window.indexedDB!.open(name, version: 1, onUpgradeNeeded: (e) {
+ e.target.transaction!.abort();
_exists = false;
});
return _exists;
diff --git a/hive/lib/src/backend/js/storage_backend_js.dart b/hive/lib/src/backend/js/storage_backend_js.dart
index 77a9d53fd..92bf9b257 100644
--- a/hive/lib/src/backend/js/storage_backend_js.dart
+++ b/hive/lib/src/backend/js/storage_backend_js.dart
@@ -1,8 +1,8 @@
import 'dart:async';
import 'dart:html';
import 'dart:indexed_db';
-import 'dart:typed_data';
import 'dart:js_util';
+import 'dart:typed_data';
import 'package:hive/hive.dart';
import 'package:hive/src/backend/storage_backend.dart';
@@ -10,21 +10,23 @@ import 'package:hive/src/binary/binary_reader_impl.dart';
import 'package:hive/src/binary/binary_writer_impl.dart';
import 'package:hive/src/binary/frame.dart';
import 'package:hive/src/box/keystore.dart';
+import 'package:hive/src/registry/type_registry_impl.dart';
import 'package:meta/meta.dart';
/// Handles all IndexedDB related tasks
class StorageBackendJs extends StorageBackend {
static const _bytePrefix = [0x90, 0xA9];
final Database _db;
- final HiveCipher _cipher;
+ final HiveCipher? _cipher;
TypeRegistry _registry;
/// Not part of public API
- StorageBackendJs(this._db, this._cipher, [this._registry]);
+ StorageBackendJs(this._db, this._cipher,
+ [this._registry = TypeRegistryImpl.nullImpl]);
@override
- String get path => null;
+ String? get path => null;
@override
bool supportsCompaction = false;
@@ -62,7 +64,7 @@ class StorageBackendJs extends StorageBackend {
if (_cipher == null) {
frameWriter.write(value);
} else {
- frameWriter.writeEncrypted(value, _cipher);
+ frameWriter.writeEncrypted(value, _cipher!);
}
var bytes = frameWriter.toBytes();
@@ -81,7 +83,7 @@ class StorageBackendJs extends StorageBackend {
if (_cipher == null) {
return reader.read();
} else {
- return reader.readEncrypted(_cipher);
+ return reader.readEncrypted(_cipher!);
}
} else {
return bytes;
@@ -108,10 +110,10 @@ class StorageBackendJs extends StorageBackend {
var completer = Completer>();
var request = getStore(false).getAllKeys(null);
request.onSuccess.listen((_) {
- completer.complete(request.result as List);
+ completer.complete(request.result as List?);
});
request.onError.listen((_) {
- completer.completeError(request.error);
+ completer.completeError(request.error!);
});
return completer.future;
} else {
@@ -132,7 +134,7 @@ class StorageBackendJs extends StorageBackend {
completer.complete(values);
});
request.onError.listen((_) {
- completer.completeError(request.error);
+ completer.completeError(request.error!);
});
return completer.future;
} else {
@@ -197,6 +199,6 @@ class StorageBackendJs extends StorageBackend {
@override
Future deleteFromDisk() {
- return window.indexedDB.deleteDatabase(_db.name);
+ return window.indexedDB!.deleteDatabase(_db.name!);
}
}
diff --git a/hive/lib/src/backend/storage_backend.dart b/hive/lib/src/backend/storage_backend.dart
index f89b9dc85..61786e6f4 100644
--- a/hive/lib/src/backend/storage_backend.dart
+++ b/hive/lib/src/backend/storage_backend.dart
@@ -9,7 +9,7 @@ export 'package:hive/src/backend/stub/backend_manager.dart'
/// Abstract storage backend
abstract class StorageBackend {
/// The path where the database is stored
- String get path;
+ String? get path;
/// Whether the database can be compacted
bool get supportsCompaction;
@@ -43,8 +43,8 @@ abstract class BackendManagerInterface {
String name, String path, bool crashRecovery, HiveCipher cipher);
/// Deletes database
- Future deleteBox(String name, String path);
+ Future deleteBox(String name, String? path);
/// Checks if box exists
- Future boxExists(String name, String path);
+ Future boxExists(String name, String? path);
}
diff --git a/hive/lib/src/backend/storage_backend_memory.dart b/hive/lib/src/backend/storage_backend_memory.dart
index 2fb5bc96e..55ec4e2a3 100644
--- a/hive/lib/src/backend/storage_backend_memory.dart
+++ b/hive/lib/src/backend/storage_backend_memory.dart
@@ -8,26 +8,32 @@ import 'package:hive/src/box/keystore.dart';
/// In-memory Storage backend
class StorageBackendMemory extends StorageBackend {
- final HiveCipher _cipher;
+ final HiveCipher? _cipher;
final FrameHelper _frameHelper;
- Uint8List _bytes;
+ Uint8List? _bytes;
/// Not part of public API
- StorageBackendMemory(this._bytes, this._cipher)
- : _frameHelper = FrameHelper();
+ StorageBackendMemory(Uint8List? bytes, this._cipher)
+ : _bytes = bytes,
+ _frameHelper = FrameHelper();
@override
- String get path => null;
+ String? get path => null;
@override
bool supportsCompaction = false;
@override
- Future initialize(TypeRegistry registry, Keystore keystore, bool lazy) {
- var recoveryOffset =
- _frameHelper.framesFromBytes(_bytes, keystore, registry, _cipher);
+ Future initialize(
+ TypeRegistry registry, Keystore? keystore, bool lazy) {
+ var recoveryOffset = _frameHelper.framesFromBytes(
+ _bytes!, // Initialized at constructor and nulled after initialization
+ keystore,
+ registry,
+ _cipher,
+ );
if (recoveryOffset != -1) {
throw HiveError('Wrong checksum in bytes. Box may be corrupted.');
diff --git a/hive/lib/src/backend/stub/backend_manager.dart b/hive/lib/src/backend/stub/backend_manager.dart
index 84502ec4d..5723ac930 100644
--- a/hive/lib/src/backend/stub/backend_manager.dart
+++ b/hive/lib/src/backend/stub/backend_manager.dart
@@ -5,17 +5,17 @@ import 'package:hive/src/backend/storage_backend.dart';
class BackendManager implements BackendManagerInterface {
@override
Future open(
- String name, String path, bool crashRecovery, HiveCipher cipher) {
+ String name, String? path, bool crashRecovery, HiveCipher? cipher) {
throw UnimplementedError();
}
@override
- Future deleteBox(String name, String path) {
+ Future deleteBox(String name, String? path) {
throw UnimplementedError();
}
@override
- Future boxExists(String name, String path) {
+ Future boxExists(String name, String? path) {
throw UnimplementedError();
}
}
diff --git a/hive/lib/src/backend/vm/backend_manager.dart b/hive/lib/src/backend/vm/backend_manager.dart
index 8dc92fccc..9c19effe6 100644
--- a/hive/lib/src/backend/vm/backend_manager.dart
+++ b/hive/lib/src/backend/vm/backend_manager.dart
@@ -11,7 +11,7 @@ class BackendManager implements BackendManagerInterface {
@override
Future open(
- String name, String path, bool crashRecovery, HiveCipher cipher) async {
+ String name, String? path, bool crashRecovery, HiveCipher? cipher) async {
if (path == null) {
throw HiveError('You need to initialize Hive or '
'provide a path to store the box.');
@@ -50,7 +50,8 @@ class BackendManager implements BackendManagerInterface {
}
@override
- Future deleteBox(String name, String path) async {
+ Future deleteBox(String name, String? path) async {
+ ArgumentError.checkNotNull(path, 'path');
await _deleteFileIfExists(File('$path$_delimiter$name.hive'));
await _deleteFileIfExists(File('$path$_delimiter$name.hivec'));
await _deleteFileIfExists(File('$path$_delimiter$name.lock'));
@@ -63,7 +64,8 @@ class BackendManager implements BackendManagerInterface {
}
@override
- Future boxExists(String name, String path) async {
+ Future boxExists(String name, String? path) async {
+ ArgumentError.checkNotNull(path, 'path');
return await File('$path$_delimiter$name.hive').exists() ||
await File('$path$_delimiter$name.hivec').exists() ||
await File('$path$_delimiter$name.lock').exists();
diff --git a/hive/lib/src/backend/vm/storage_backend_vm.dart b/hive/lib/src/backend/vm/storage_backend_vm.dart
index 8010ca65f..07a9ca956 100644
--- a/hive/lib/src/backend/vm/storage_backend_vm.dart
+++ b/hive/lib/src/backend/vm/storage_backend_vm.dart
@@ -18,22 +18,26 @@ class StorageBackendVm extends StorageBackend {
final File _file;
final File _lockFile;
final bool _crashRecovery;
- final HiveCipher _cipher;
+ final HiveCipher? _cipher;
final FrameIoHelper _frameHelper;
final ReadWriteSync _sync;
/// Not part of public API
+ ///
+ /// Not `late final` for testing
@visibleForTesting
- RandomAccessFile readRaf;
+ late RandomAccessFile readRaf;
/// Not part of public API
+ ///
+ /// Not `late final` for testing
@visibleForTesting
- RandomAccessFile writeRaf;
+ late RandomAccessFile writeRaf;
/// Not part of public API
@visibleForTesting
- RandomAccessFile lockRaf;
+ late RandomAccessFile lockRaf;
/// Not part of public API
@visibleForTesting
@@ -41,7 +45,7 @@ class StorageBackendVm extends StorageBackend {
/// Not part of public API
@visibleForTesting
- TypeRegistry registry;
+ late final TypeRegistry registry;
bool _compactionScheduled = false;
@@ -100,7 +104,7 @@ class StorageBackendVm extends StorageBackend {
return _sync.syncRead(() async {
await readRaf.setPosition(frame.offset);
- var bytes = await readRaf.read(frame.length);
+ var bytes = await readRaf.read(frame.length!);
var reader = BinaryReaderImpl(bytes, registry);
var readFrame = reader.readFrame(cipher: _cipher, lazy: false);
@@ -132,7 +136,7 @@ class StorageBackendVm extends StorageBackend {
for (var frame in frames) {
frame.offset = writeOffset;
- writeOffset += frame.length;
+ writeOffset += frame.length!;
}
});
}
@@ -166,12 +170,12 @@ class StorageBackendVm extends StorageBackend {
reader.skip(skip);
}
- if (reader.remainingInBuffer < frame.length) {
- if (await reader.loadBytes(frame.length) < frame.length) {
+ if (reader.remainingInBuffer < frame.length!) {
+ if (await reader.loadBytes(frame.length!) < frame.length!) {
throw HiveError('Could not compact box: Unexpected EOF.');
}
}
- await writer.write(reader.viewBytes(frame.length));
+ await writer.write(reader.viewBytes(frame.length!));
}
await writer.flush();
} finally {
@@ -187,7 +191,7 @@ class StorageBackendVm extends StorageBackend {
for (var frame in sortedFrames) {
if (frame.offset == -1) continue;
frame.offset = offset;
- offset += frame.length;
+ offset += frame.length!;
}
_compactionScheduled = false;
});
diff --git a/hive/lib/src/binary/binary_reader.dart b/hive/lib/src/binary/binary_reader.dart
index 4bc0041f4..486792b0e 100644
--- a/hive/lib/src/binary/binary_reader.dart
+++ b/hive/lib/src/binary/binary_reader.dart
@@ -47,55 +47,55 @@ abstract class BinaryReader {
///
/// If [byteCount] is not provided, it is read first.
String readString([
- int byteCount,
+ int? byteCount,
Converter, String> decoder = utf8Decoder,
]);
/// Read a list of bytes with [length].
///
/// If [length] is not provided, it is read first.
- Uint8List readByteList([int length]);
+ Uint8List readByteList([int? length]);
/// Read a list of integers with [length].
///
/// If [length] is not provided, it is read first.
- List readIntList([int length]);
+ List readIntList([int? length]);
/// Read a list of doubles with [length].
///
/// If [length] is not provided, it is read first.
- List readDoubleList([int length]);
+ List readDoubleList([int? length]);
/// Read a list of booleans with [length].
///
/// If [length] is not provided, it is read first.
- List readBoolList([int length]);
+ List readBoolList([int? length]);
/// Read a list of Strings with [length].
///
/// If [length] is not provided, it is read first.
List readStringList([
- int length,
+ int? length,
Converter, String> decoder = utf8Decoder,
]);
/// Read a list with [length].
///
/// If [length] is not provided, it is read first.
- List readList([int length]);
+ List readList([int? length]);
/// Read a map with [length] entries.
///
/// If [length] is not provided, it is read first.
- Map readMap([int length]);
+ Map readMap([int? length]);
/// Read and decode any value.
///
/// If [typeId] is not provided, it is read first.
- dynamic read([int typeId]);
+ dynamic read([int? typeId]);
/// Read a [HiveList] with [length].
///
/// If [length] is not provided, it is read first.
- HiveList readHiveList([int length]);
+ HiveList readHiveList([int? length]);
}
diff --git a/hive/lib/src/binary/binary_reader_impl.dart b/hive/lib/src/binary/binary_reader_impl.dart
index f7c4b3423..b2926d4ec 100644
--- a/hive/lib/src/binary/binary_reader_impl.dart
+++ b/hive/lib/src/binary/binary_reader_impl.dart
@@ -19,7 +19,7 @@ class BinaryReaderImpl extends BinaryReader {
int _offset = 0;
/// Not part of public API
- BinaryReaderImpl(this._buffer, TypeRegistry typeRegistry, [int bufferLength])
+ BinaryReaderImpl(this._buffer, TypeRegistry typeRegistry, [int? bufferLength])
: _byteData = ByteData.view(_buffer.buffer, _buffer.offsetInBytes),
_bufferLength = bufferLength ?? _buffer.length,
_bufferLimit = bufferLength ?? _buffer.length,
@@ -129,7 +129,7 @@ class BinaryReaderImpl extends BinaryReader {
@override
String readString(
- [int byteCount,
+ [int? byteCount,
Converter, String> decoder = BinaryReader.utf8Decoder]) {
byteCount ??= readUint32();
var view = viewBytes(byteCount);
@@ -137,7 +137,7 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- Uint8List readByteList([int length]) {
+ Uint8List readByteList([int? length]) {
length ??= readUint32();
_requireBytes(length);
var byteList = _buffer.sublist(_offset, _offset + length);
@@ -146,11 +146,11 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- List readIntList([int length]) {
+ List readIntList([int? length]) {
length ??= readUint32();
_requireBytes(length * 8);
var byteData = _byteData;
- var list = []..length = length;
+ var list = List.filled(length, 0);
for (var i = 0; i < length; i++) {
list[i] = byteData.getFloat64(_offset, Endian.little).toInt();
_offset += 8;
@@ -159,11 +159,11 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- List readDoubleList([int length]) {
+ List readDoubleList([int? length]) {
length ??= readUint32();
_requireBytes(length * 8);
var byteData = _byteData;
- var list = []..length = length;
+ var list = List.filled(length, 0.0);
for (var i = 0; i < length; i++) {
list[i] = byteData.getFloat64(_offset, Endian.little);
_offset += 8;
@@ -172,10 +172,10 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- List readBoolList([int length]) {
+ List readBoolList([int? length]) {
length ??= readUint32();
_requireBytes(length);
- var list = []..length = length;
+ var list = List.filled(length, false);
for (var i = 0; i < length; i++) {
list[i] = _buffer[_offset++] > 0;
}
@@ -184,10 +184,10 @@ class BinaryReaderImpl extends BinaryReader {
@override
List readStringList(
- [int length,
+ [int? length,
Converter, String> decoder = BinaryReader.utf8Decoder]) {
length ??= readUint32();
- var list = []..length = length;
+ var list = List.filled(length, '');
for (var i = 0; i < length; i++) {
list[i] = readString(null, decoder);
}
@@ -195,9 +195,9 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- List readList([int length]) {
+ List readList([int? length]) {
length ??= readUint32();
- var list = []..length = length;
+ var list = List.filled(length, null);
for (var i = 0; i < length; i++) {
list[i] = read();
}
@@ -205,7 +205,7 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- Map readMap([int length]) {
+ Map readMap([int? length]) {
length ??= readUint32();
var map = {};
for (var i = 0; i < length; i++) {
@@ -228,11 +228,11 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- HiveList readHiveList([int length]) {
+ HiveList readHiveList([int? length]) {
length ??= readUint32();
var boxNameLength = readByte();
var boxName = String.fromCharCodes(viewBytes(boxNameLength));
- var keys = List(length);
+ var keys = List.filled(length, null);
for (var i = 0; i < length; i++) {
keys[i] = readKey();
}
@@ -241,7 +241,8 @@ class BinaryReaderImpl extends BinaryReader {
}
/// Not part of public API
- Frame readFrame({HiveCipher cipher, bool lazy = false, int frameOffset}) {
+ Frame? readFrame(
+ {HiveCipher? cipher, bool lazy = false, int frameOffset = 0}) {
if (availableBytes < 4) return null;
var frameLength = readUint32();
@@ -287,7 +288,7 @@ class BinaryReaderImpl extends BinaryReader {
}
@override
- dynamic read([int typeId]) {
+ dynamic read([int? typeId]) {
typeId ??= readByte();
switch (typeId) {
case FrameValueType.nullT:
diff --git a/hive/lib/src/binary/binary_writer_impl.dart b/hive/lib/src/binary/binary_writer_impl.dart
index 82f93a7bd..a2aa7096d 100644
--- a/hive/lib/src/binary/binary_writer_impl.dart
+++ b/hive/lib/src/binary/binary_writer_impl.dart
@@ -16,7 +16,7 @@ class BinaryWriterImpl extends BinaryWriter {
final TypeRegistryImpl _typeRegistry;
Uint8List _buffer = Uint8List(_initBufferSize);
- ByteData _byteDataInstance;
+ ByteData? _byteDataInstance;
int _offset = 0;
@@ -24,7 +24,7 @@ class BinaryWriterImpl extends BinaryWriter {
@pragma('dart2js:tryInline')
ByteData get _byteData {
_byteDataInstance ??= ByteData.view(_buffer.buffer);
- return _byteDataInstance;
+ return _byteDataInstance!;
}
/// Not part of public API
@@ -55,6 +55,8 @@ class BinaryWriterImpl extends BinaryWriter {
@pragma('vm:prefer-inline')
@pragma('dart2js:tryInline')
void _addBytes(List bytes) {
+ ArgumentError.checkNotNull(bytes);
+
var length = bytes.length;
_reserveBytes(length);
_buffer.setRange(_offset, _offset + length, bytes);
@@ -65,15 +67,16 @@ class BinaryWriterImpl extends BinaryWriter {
@pragma('dart2js:tryInline')
@override
void writeByte(int byte) {
- if (byte == null) {
- throw ArgumentError.notNull();
- }
+ ArgumentError.checkNotNull(byte);
+
_reserveBytes(1);
_buffer[_offset++] = byte;
}
@override
void writeWord(int value) {
+ ArgumentError.checkNotNull(value);
+
_reserveBytes(2);
_buffer[_offset++] = value;
_buffer[_offset++] = value >> 8;
@@ -81,9 +84,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeInt32(int value) {
- if (value == null) {
- throw ArgumentError.notNull();
- }
+ ArgumentError.checkNotNull(value);
+
_reserveBytes(4);
_byteData.setInt32(_offset, value, Endian.little);
_offset += 4;
@@ -93,6 +95,8 @@ class BinaryWriterImpl extends BinaryWriter {
@pragma('dart2js:tryInline')
@override
void writeUint32(int value) {
+ ArgumentError.checkNotNull(value);
+
_reserveBytes(4);
_buffer.writeUint32(_offset, value);
_offset += 4;
@@ -105,9 +109,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeDouble(double value) {
- if (value == null) {
- throw ArgumentError.notNull();
- }
+ ArgumentError.checkNotNull(value);
+
_reserveBytes(8);
_byteData.setFloat64(_offset, value, Endian.little);
_offset += 8;
@@ -115,6 +118,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeBool(bool value) {
+ ArgumentError.checkNotNull(value);
+
writeByte(value ? 1 : 0);
}
@@ -124,6 +129,8 @@ class BinaryWriterImpl extends BinaryWriter {
bool writeByteCount = true,
Converter> encoder = BinaryWriter.utf8Encoder,
}) {
+ ArgumentError.checkNotNull(value);
+
var bytes = encoder.convert(value);
if (writeByteCount) {
writeUint32(bytes.length);
@@ -133,6 +140,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeByteList(List bytes, {bool writeLength = true}) {
+ ArgumentError.checkNotNull(bytes);
+
if (writeLength) {
writeUint32(bytes.length);
}
@@ -141,6 +150,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeIntList(List list, {bool writeLength = true}) {
+ ArgumentError.checkNotNull(list);
+
var length = list.length;
if (writeLength) {
writeUint32(length);
@@ -155,6 +166,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeDoubleList(List list, {bool writeLength = true}) {
+ ArgumentError.checkNotNull(list);
+
var length = list.length;
if (writeLength) {
writeUint32(length);
@@ -169,6 +182,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeBoolList(List list, {bool writeLength = true}) {
+ ArgumentError.checkNotNull(list);
+
var length = list.length;
if (writeLength) {
writeUint32(length);
@@ -185,6 +200,8 @@ class BinaryWriterImpl extends BinaryWriter {
bool writeLength = true,
Converter> encoder = BinaryWriter.utf8Encoder,
}) {
+ ArgumentError.checkNotNull(list);
+
if (writeLength) {
writeUint32(list.length);
}
@@ -197,6 +214,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeList(List list, {bool writeLength = true}) {
+ ArgumentError.checkNotNull(list);
+
if (writeLength) {
writeUint32(list.length);
}
@@ -207,6 +226,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeMap(Map map, {bool writeLength = true}) {
+ ArgumentError.checkNotNull(map);
+
if (writeLength) {
writeUint32(map.length);
}
@@ -218,6 +239,8 @@ class BinaryWriterImpl extends BinaryWriter {
/// Not part of public API
void writeKey(dynamic key) {
+ ArgumentError.checkNotNull(key);
+
if (key is String) {
writeByte(FrameKeyType.asciiStringT);
writeByte(key.length);
@@ -230,6 +253,8 @@ class BinaryWriterImpl extends BinaryWriter {
@override
void writeHiveList(HiveList list, {bool writeLength = true}) {
+ ArgumentError.checkNotNull(list);
+
if (writeLength) {
writeUint32(list.length);
}
@@ -242,7 +267,9 @@ class BinaryWriterImpl extends BinaryWriter {
}
/// Not part of public API
- int writeFrame(Frame frame, {HiveCipher cipher}) {
+ int writeFrame(Frame frame, {HiveCipher? cipher}) {
+ ArgumentError.checkNotNull(frame);
+
var startOffset = _offset;
_reserveBytes(4);
_offset += 4; // reserve bytes for length
diff --git a/hive/lib/src/binary/frame.dart b/hive/lib/src/binary/frame.dart
index 9c8b2937a..4f1861e82 100644
--- a/hive/lib/src/binary/frame.dart
+++ b/hive/lib/src/binary/frame.dart
@@ -16,7 +16,7 @@ class Frame {
final bool lazy;
/// Not part of public API
- int length;
+ int? length;
/// Not part of public API
int offset = -1;
diff --git a/hive/lib/src/binary/frame_helper.dart b/hive/lib/src/binary/frame_helper.dart
index 5a83c3b5e..f65a397cc 100644
--- a/hive/lib/src/binary/frame_helper.dart
+++ b/hive/lib/src/binary/frame_helper.dart
@@ -7,8 +7,12 @@ import 'package:hive/src/box/keystore.dart';
/// Not part of public API
class FrameHelper {
/// Not part of public API
- int framesFromBytes(Uint8List bytes, Keystore keystore, TypeRegistry registry,
- HiveCipher cipher) {
+ int framesFromBytes(
+ Uint8List bytes,
+ Keystore? keystore,
+ TypeRegistry registry,
+ HiveCipher? cipher,
+ ) {
var reader = BinaryReaderImpl(bytes, registry);
while (reader.availableBytes != 0) {
@@ -21,7 +25,7 @@ class FrameHelper {
);
if (frame == null) return frameOffset;
- keystore.insert(frame, notify: false);
+ keystore!.insert(frame, notify: false);
}
return -1;
diff --git a/hive/lib/src/box/box.dart b/hive/lib/src/box/box.dart
index e2862ef89..697667868 100644
--- a/hive/lib/src/box/box.dart
+++ b/hive/lib/src/box/box.dart
@@ -31,10 +31,10 @@ abstract class Box implements BoxBase {
///
/// If [defaultValue] is specified, it is returned in case the key does not
/// exist.
- E get(dynamic key, {E defaultValue});
+ E? get(dynamic key, {E? defaultValue});
/// Returns the value associated with the n-th key.
- E getAt(int index);
+ E? getAt(int index);
/// Returns a map which contains all key - value pairs of the box.
Map toMap();
diff --git a/hive/lib/src/box/box_base.dart b/hive/lib/src/box/box_base.dart
index 59041a779..0644b43d3 100644
--- a/hive/lib/src/box/box_base.dart
+++ b/hive/lib/src/box/box_base.dart
@@ -43,7 +43,7 @@ abstract class BoxBase {
bool get isOpen;
/// The location of the box in the file system. In the browser, this is null.
- String get path;
+ String? get path;
/// Whether this box is lazy or not.
///
diff --git a/hive/lib/src/box/box_base_impl.dart b/hive/lib/src/box/box_base_impl.dart
index 0408f9752..368ab6584 100644
--- a/hive/lib/src/box/box_base_impl.dart
+++ b/hive/lib/src/box/box_base_impl.dart
@@ -7,6 +7,8 @@ import 'package:meta/meta.dart';
/// Not part of public API
abstract class BoxBaseImpl implements BoxBase {
+ static BoxBase nullImpl() => _NullBoxBase();
+
@override
final String name;
@@ -21,9 +23,11 @@ abstract class BoxBaseImpl implements BoxBase {
final StorageBackend backend;
/// Not part of public API
+ ///
+ /// Not `late final` for testing
@protected
@visibleForTesting
- Keystore keystore;
+ late Keystore keystore;
bool _open = true;
@@ -31,7 +35,7 @@ abstract class BoxBaseImpl implements BoxBase {
BoxBaseImpl(
this.hive,
this.name,
- KeyComparator keyComparator,
+ KeyComparator? keyComparator,
this._compactionStrategy,
this.backend,
) {
@@ -45,7 +49,7 @@ abstract class BoxBaseImpl implements BoxBase {
bool get isOpen => _open;
@override
- String get path => backend.path;
+ String? get path => backend.path;
@override
Iterable get keys {
@@ -82,7 +86,7 @@ abstract class BoxBaseImpl implements BoxBase {
@override
dynamic keyAt(int index) {
checkOpen();
- return keystore.getAt(index).key;
+ return keystore.getAt(index)!.key;
}
/// Not part of public API
@@ -121,12 +125,12 @@ abstract class BoxBaseImpl implements BoxBase {
@override
Future putAt(int index, E value) {
- return putAll({keystore.getAt(index).key: value});
+ return putAll({keystore.getAt(index)!.key: value});
}
@override
Future deleteAt(int index) {
- return deleteAll([keystore.getAt(index).key]);
+ return delete(keystore.getAt(index)!.key);
}
@override
@@ -180,3 +184,74 @@ abstract class BoxBaseImpl implements BoxBase {
await backend.deleteFromDisk();
}
}
+
+class _NullBoxBase implements BoxBase {
+ @override
+ Never add(E value) => throw UnimplementedError();
+
+ @override
+ Never addAll(Iterable values) => throw UnimplementedError();
+
+ @override
+ Never clear() => throw UnimplementedError();
+
+ @override
+ Never close() => throw UnimplementedError();
+
+ @override
+ Never compact() => throw UnimplementedError();
+
+ @override
+ Never containsKey(key) => throw UnimplementedError();
+
+ @override
+ Never delete(key) => throw UnimplementedError();
+
+ @override
+ Never deleteAll(Iterable keys) => throw UnimplementedError();
+
+ @override
+ Never deleteAt(int index) => throw UnimplementedError();
+
+ @override
+ Never deleteFromDisk() => throw UnimplementedError();
+
+ @override
+ Never get isEmpty => throw UnimplementedError();
+
+ @override
+ Never get isNotEmpty => throw UnimplementedError();
+
+ @override
+ Never get isOpen => throw UnimplementedError();
+
+ @override
+ Never keyAt(int index) => throw UnimplementedError();
+
+ @override
+ Never get keys => throw UnimplementedError();
+
+ @override
+ Never get lazy => throw UnimplementedError();
+
+ @override
+ Never get length => throw UnimplementedError();
+
+ @override
+ Never get name => throw UnimplementedError();
+
+ @override
+ Never get path => throw UnimplementedError();
+
+ @override
+ Never put(key, E value) => throw UnimplementedError();
+
+ @override
+ Never putAll(Map entries) => throw UnimplementedError();
+
+ @override
+ Never putAt(int index, E value) => throw UnimplementedError();
+
+ @override
+ Never watch({key}) => throw UnimplementedError();
+}
diff --git a/hive/lib/src/box/box_impl.dart b/hive/lib/src/box/box_impl.dart
index 97552a663..5c84cd077 100644
--- a/hive/lib/src/box/box_impl.dart
+++ b/hive/lib/src/box/box_impl.dart
@@ -13,7 +13,7 @@ class BoxImpl extends BoxBaseImpl implements Box {
BoxImpl(
HiveImpl hive,
String name,
- KeyComparator keyComparator,
+ KeyComparator? keyComparator,
CompactionStrategy compactionStrategy,
StorageBackend backend,
) : super(hive, name, keyComparator, compactionStrategy, backend);
@@ -36,12 +36,12 @@ class BoxImpl extends BoxBaseImpl implements Box {
}
@override
- E get(dynamic key, {E defaultValue}) {
+ E? get(dynamic key, {E? defaultValue}) {
checkOpen();
var frame = keystore.get(key);
if (frame != null) {
- return frame.value as E;
+ return frame.value as E?;
} else {
if (defaultValue != null && defaultValue is HiveObject) {
defaultValue.init(key, this);
@@ -51,10 +51,10 @@ class BoxImpl extends BoxBaseImpl implements Box {
}
@override
- E getAt(int index) {
+ E? getAt(int index) {
checkOpen();
- return keystore.getAt(index).value as E;
+ return keystore.getAt(index)?.value as E?;
}
@override
diff --git a/hive/lib/src/box/keystore.dart b/hive/lib/src/box/keystore.dart
index 4fddfe99c..b02c12493 100644
--- a/hive/lib/src/box/keystore.dart
+++ b/hive/lib/src/box/keystore.dart
@@ -11,6 +11,8 @@ import 'package:hive/src/object/hive_object.dart';
import 'package:hive/src/util/indexable_skip_list.dart';
import 'package:meta/meta.dart';
+import 'box_base_impl.dart';
+
/// Not part of public API
class KeyTransaction {
/// The values that have been added
@@ -40,18 +42,18 @@ class Keystore {
var _autoIncrement = -1;
/// Not part of public API
- Keystore(this._box, this._notifier, KeyComparator keyComparator)
+ Keystore(this._box, this._notifier, KeyComparator? keyComparator)
: _store = IndexableSkipList(keyComparator ?? defaultKeyComparator);
/// Not part of public API
factory Keystore.debug({
Iterable frames = const [],
- BoxBase box,
- ChangeNotifier notifier,
+ BoxBase? box,
+ ChangeNotifier? notifier,
KeyComparator keyComparator = defaultKeyComparator,
}) {
- var keystore =
- Keystore(box, notifier ?? ChangeNotifier(), keyComparator);
+ var keystore = Keystore(box ?? BoxBaseImpl.nullImpl(),
+ notifier ?? ChangeNotifier(), keyComparator);
for (var frame in frames) {
keystore.insert(frame);
}
@@ -101,14 +103,14 @@ class Keystore {
/// Not part of public API
@pragma('vm:prefer-inline')
@pragma('dart2js:tryInline')
- Frame get(dynamic key) {
+ Frame? get(dynamic key) {
return _store.get(key);
}
/// Not part of public API
@pragma('vm:prefer-inline')
@pragma('dart2js:tryInline')
- Frame getAt(int index) {
+ Frame? getAt(int index) {
return _store.getAt(index);
}
@@ -144,9 +146,9 @@ class Keystore {
}
/// Not part of public API
- Frame insert(Frame frame, {bool notify = true}) {
+ Frame? insert(Frame frame, {bool notify = true}) {
var value = frame.value;
- Frame deletedFrame;
+ Frame? deletedFrame;
if (!frame.deleted) {
var key = frame.key;
@@ -214,17 +216,17 @@ class Keystore {
var deletedFrame = canceled.deleted[key];
for (var t in transactions) {
if (t.deleted.containsKey(key)) {
- t.deleted[key] = deletedFrame;
+ t.deleted[key] = deletedFrame!;
continue deleted_loop;
}
if (t.added.contains(key)) {
- t.deleted[key] = deletedFrame;
+ t.deleted[key] = deletedFrame!;
continue deleted_loop;
}
}
_store.insert(key, deletedFrame);
- _notifier.notify(deletedFrame);
+ _notifier.notify(deletedFrame!);
}
added_loop:
@@ -256,7 +258,6 @@ class Keystore {
for (var frame in frameList) {
if (frame.value is HiveObject) {
- // ignore: invalid_use_of_protected_member
(frame.value as HiveObject).dispose();
}
_notifier.notify(Frame.deleted(frame.key));
diff --git a/hive/lib/src/box/lazy_box.dart b/hive/lib/src/box/lazy_box.dart
index 57619238a..d08176d6b 100644
--- a/hive/lib/src/box/lazy_box.dart
+++ b/hive/lib/src/box/lazy_box.dart
@@ -8,8 +8,8 @@ abstract class LazyBox extends BoxBase {
///
/// If [defaultValue] is specified, it is returned in case the key does not
/// exist.
- Future get(dynamic key, {E defaultValue});
+ Future get(dynamic key, {E? defaultValue});
/// Returns the value associated with the n-th key.
- Future getAt(int index);
+ Future getAt(int index);
}
diff --git a/hive/lib/src/box/lazy_box_impl.dart b/hive/lib/src/box/lazy_box_impl.dart
index 7ce1258b9..d522cb22d 100644
--- a/hive/lib/src/box/lazy_box_impl.dart
+++ b/hive/lib/src/box/lazy_box_impl.dart
@@ -14,7 +14,7 @@ class LazyBoxImpl extends BoxBaseImpl implements LazyBox {
LazyBoxImpl(
HiveImpl hive,
String name,
- KeyComparator keyComparator,
+ KeyComparator? keyComparator,
CompactionStrategy compactionStrategy,
StorageBackend backend,
) : super(hive, name, keyComparator, compactionStrategy, backend);
@@ -23,7 +23,7 @@ class LazyBoxImpl extends BoxBaseImpl implements LazyBox {
final bool lazy = true;
@override
- Future get(dynamic key, {E defaultValue}) async {
+ Future get(dynamic key, {E? defaultValue}) async {
checkOpen();
var frame = keystore.get(key);
@@ -33,7 +33,7 @@ class LazyBoxImpl extends BoxBaseImpl implements LazyBox {
if (value is HiveObject) {
value.init(key, this);
}
- return value as E;
+ return value as E?;
} else {
if (defaultValue != null && defaultValue is HiveObject) {
defaultValue.init(key, this);
@@ -43,7 +43,7 @@ class LazyBoxImpl extends BoxBaseImpl implements LazyBox {
}
@override
- Future getAt(int index) {
+ Future getAt(int index) {
return get(keystore.keyAt(index));
}
diff --git a/hive/lib/src/crypto/aes_cbc_pkcs7.dart b/hive/lib/src/crypto/aes_cbc_pkcs7.dart
index a4cab50b9..c200e2909 100644
--- a/hive/lib/src/crypto/aes_cbc_pkcs7.dart
+++ b/hive/lib/src/crypto/aes_cbc_pkcs7.dart
@@ -8,8 +8,10 @@ class AesCbcPkcs7 {
final Uint8List _keyBytes;
- List _encryptionKey;
- List _decryptionKey;
+ late final List _encryptionKey =
+ AesEngine.generateWorkingKey(_keyBytes, true);
+ late final List _decryptionKey =
+ AesEngine.generateWorkingKey(_keyBytes, false);
/// Not part of public API
AesCbcPkcs7(this._keyBytes);
@@ -17,8 +19,6 @@ class AesCbcPkcs7 {
/// Not part of public API
int encrypt(Uint8List iv, Uint8List inp, int inpOff, int inpLength,
Uint8List out, int outOff) {
- _encryptionKey ??= AesEngine.generateWorkingKey(_keyBytes, true);
-
var cbcV = Uint8List.fromList(iv);
var inputBlocks = (inpLength + aesBlockSize) ~/ aesBlockSize;
@@ -53,8 +53,6 @@ class AesCbcPkcs7 {
/// Not part of public API
int decrypt(Uint8List iv, Uint8List inp, int inpOff, int inpLength,
Uint8List out, int outOff) {
- _decryptionKey ??= AesEngine.generateWorkingKey(_keyBytes, false);
-
var inputBlocks = (inpLength + aesBlockSize - 1) ~/ aesBlockSize;
var offset = 0;
diff --git a/hive/lib/src/crypto/crc32.dart b/hive/lib/src/crypto/crc32.dart
index c0efb4032..88f5d65bf 100644
--- a/hive/lib/src/crypto/crc32.dart
+++ b/hive/lib/src/crypto/crc32.dart
@@ -7,7 +7,7 @@ class Crc32 {
Uint8List bytes, {
int crc = 0,
int offset = 0,
- int length,
+ int? length,
}) {
crc = crc ^ 0xffffffff;
diff --git a/hive/lib/src/crypto/hive_aes_cipher.dart b/hive/lib/src/crypto/hive_aes_cipher.dart
index ee36a5f44..b8bf06f59 100644
--- a/hive/lib/src/crypto/hive_aes_cipher.dart
+++ b/hive/lib/src/crypto/hive_aes_cipher.dart
@@ -4,9 +4,9 @@ part of hive;
class HiveAesCipher implements HiveCipher {
static final _ivRandom = Random.secure();
- AesCbcPkcs7 _cipher;
+ late final AesCbcPkcs7 _cipher;
- int _keyCrc;
+ late final int _keyCrc;
/// Create a cipher with the given [key].
HiveAesCipher(List key) {
diff --git a/hive/lib/src/hive.dart b/hive/lib/src/hive.dart
index fe5e450a2..d88720d5f 100644
--- a/hive/lib/src/hive.dart
+++ b/hive/lib/src/hive.dart
@@ -13,13 +13,13 @@ abstract class HiveInterface implements TypeRegistry {
/// parameters are being ignored.
Future> openBox(
String name, {
- HiveCipher encryptionCipher,
+ HiveCipher? encryptionCipher,
KeyComparator keyComparator = defaultKeyComparator,
CompactionStrategy compactionStrategy = defaultCompactionStrategy,
bool crashRecovery = true,
- String path,
- Uint8List bytes,
- @deprecated List encryptionKey,
+ String? path,
+ Uint8List? bytes,
+ @deprecated List? encryptionKey,
});
/// Opens a lazy box.
@@ -28,12 +28,12 @@ abstract class HiveInterface implements TypeRegistry {
/// parameters are being ignored.
Future> openLazyBox(
String name, {
- HiveCipher encryptionCipher,
+ HiveCipher? encryptionCipher,
KeyComparator keyComparator = defaultKeyComparator,
CompactionStrategy compactionStrategy = defaultCompactionStrategy,
bool crashRecovery = true,
- String path,
- @deprecated List encryptionKey,
+ String? path,
+ @deprecated List? encryptionKey,
});
/// Returns a previously opened box.
diff --git a/hive/lib/src/hive_impl.dart b/hive/lib/src/hive_impl.dart
index 5a211e743..ecf52a541 100644
--- a/hive/lib/src/hive_impl.dart
+++ b/hive/lib/src/hive_impl.dart
@@ -27,7 +27,7 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
/// Not part of public API
@visibleForTesting
- String homePath;
+ String? homePath;
/// Not part of public API
HiveImpl() : _manager = BackendManager() {
@@ -64,15 +64,13 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
Future> _openBox(
String name,
bool lazy,
- HiveCipher cipher,
+ HiveCipher? cipher,
KeyComparator comparator,
CompactionStrategy compaction,
bool recovery,
- String path,
- Uint8List bytes,
+ String? path,
+ Uint8List? bytes,
) async {
- assert(comparator != null);
- assert(compaction != null);
assert(path == null || bytes == null);
assert(name.length <= 255 && name.isAscii,
'Box names need to be ASCII Strings with a max length of 255.');
@@ -130,13 +128,13 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
@override
Future> openBox(
String name, {
- HiveCipher encryptionCipher,
+ HiveCipher? encryptionCipher,
KeyComparator keyComparator = defaultKeyComparator,
CompactionStrategy compactionStrategy = defaultCompactionStrategy,
bool crashRecovery = true,
- String path,
- Uint8List bytes,
- @deprecated List encryptionKey,
+ String? path,
+ Uint8List? bytes,
+ @deprecated List? encryptionKey,
}) async {
if (encryptionKey != null) {
encryptionCipher = HiveAesCipher(encryptionKey);
@@ -148,12 +146,12 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
@override
Future> openLazyBox(
String name, {
- HiveCipher encryptionCipher,
+ HiveCipher? encryptionCipher,
KeyComparator keyComparator = defaultKeyComparator,
CompactionStrategy compactionStrategy = defaultCompactionStrategy,
bool crashRecovery = true,
- String path,
- @deprecated List encryptionKey,
+ String? path,
+ @deprecated List? encryptionKey,
}) async {
if (encryptionKey != null) {
encryptionCipher = HiveAesCipher(encryptionKey);
@@ -162,7 +160,7 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
compactionStrategy, crashRecovery, path, null) as LazyBox;
}
- BoxBase _getBoxInternal(String name, [bool lazy]) {
+ BoxBase _getBoxInternal(String name, [bool? lazy]) {
var lowerCaseName = name.toLowerCase();
var box = _boxes[lowerCaseName];
if (box != null) {
@@ -181,7 +179,7 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
}
/// Not part of public API
- BoxBase getBoxWithoutCheckInternal(String name) {
+ BoxBase? getBoxWithoutCheckInternal(String name) {
var lowerCaseName = name.toLowerCase();
return _boxes[lowerCaseName];
}
@@ -215,7 +213,7 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
}
@override
- Future deleteBoxFromDisk(String name, {String path}) async {
+ Future deleteBoxFromDisk(String name, {String? path}) async {
var lowerCaseName = name.toLowerCase();
var box = _boxes[lowerCaseName];
if (box != null) {
@@ -240,7 +238,7 @@ class HiveImpl extends TypeRegistryImpl implements HiveInterface {
}
@override
- Future boxExists(String name, {String path}) async {
+ Future boxExists(String name, {String? path}) async {
var lowerCaseName = name.toLowerCase();
return await _manager.boxExists(lowerCaseName, path ?? homePath);
}
diff --git a/hive/lib/src/io/buffered_file_reader.dart b/hive/lib/src/io/buffered_file_reader.dart
index 9f5114b99..e52f73ab2 100644
--- a/hive/lib/src/io/buffered_file_reader.dart
+++ b/hive/lib/src/io/buffered_file_reader.dart
@@ -11,8 +11,11 @@ class BufferedFileReader {
static const defaultChunkSize = 1000 * 64;
/// Not part of public API
+ ///
+ /// Nullable because of testing. [loadBytes] can throw if the count is not in
+ /// the buffer.
@visibleForTesting
- final RandomAccessFile file;
+ final RandomAccessFile? file;
/// Not part of public API
@visibleForTesting
@@ -75,7 +78,7 @@ class BufferedFileReader {
}
_bufferOffset = 0;
- var readBytes = await file.readInto(buffer, remaining);
+ var readBytes = await file!.readInto(buffer, remaining);
_bufferSize = remaining + readBytes;
_fileOffset += readBytes;
diff --git a/hive/lib/src/io/frame_io_helper.dart b/hive/lib/src/io/frame_io_helper.dart
index c964fb16a..4ba08dc51 100644
--- a/hive/lib/src/io/frame_io_helper.dart
+++ b/hive/lib/src/io/frame_io_helper.dart
@@ -6,6 +6,7 @@ import 'package:hive/src/binary/binary_reader_impl.dart';
import 'package:hive/src/binary/frame_helper.dart';
import 'package:hive/src/box/keystore.dart';
import 'package:hive/src/io/buffered_file_reader.dart';
+import 'package:hive/src/registry/type_registry_impl.dart';
import 'package:meta/meta.dart';
/// Not part of public API
@@ -24,7 +25,7 @@ class FrameIoHelper extends FrameHelper {
/// Not part of public API
Future keysFromFile(
- String path, Keystore keystore, HiveCipher cipher) async {
+ String path, Keystore keystore, HiveCipher? cipher) async {
var raf = await openFile(path);
var fileReader = BufferedFileReader(raf);
try {
@@ -36,7 +37,7 @@ class FrameIoHelper extends FrameHelper {
/// Not part of public API
Future framesFromFile(String path, Keystore keystore,
- TypeRegistry registry, HiveCipher cipher) async {
+ TypeRegistry registry, HiveCipher? cipher) async {
var bytes = await readFile(path);
return framesFromBytes(bytes as Uint8List, keystore, registry, cipher);
}
@@ -45,11 +46,11 @@ class FrameIoHelper extends FrameHelper {
class _KeyReader {
final BufferedFileReader fileReader;
- BinaryReaderImpl _reader;
+ late BinaryReaderImpl _reader;
_KeyReader(this.fileReader);
- Future readKeys(Keystore keystore, HiveCipher cipher) async {
+ Future readKeys(Keystore keystore, HiveCipher? cipher) async {
await _load(4);
while (true) {
var frameOffset = fileReader.offset;
@@ -87,7 +88,7 @@ class _KeyReader {
Future _load(int bytes) async {
var loadedBytes = await fileReader.loadBytes(bytes);
var buffer = fileReader.peekBytes(loadedBytes);
- _reader = BinaryReaderImpl(buffer, null);
+ _reader = BinaryReaderImpl(buffer, TypeRegistryImpl.nullImpl);
return loadedBytes;
}
diff --git a/hive/lib/src/object/hive_list.dart b/hive/lib/src/object/hive_list.dart
index 27155f378..72561f01b 100644
--- a/hive/lib/src/object/hive_list.dart
+++ b/hive/lib/src/object/hive_list.dart
@@ -5,7 +5,7 @@ part of hive;
abstract class HiveList extends HiveCollection
implements List {
/// Create a new HiveList which can contain HiveObjects from [box].
- factory HiveList(Box box, {List objects}) =>
+ factory HiveList(Box box, {List? objects}) =>
HiveListImpl(box, objects: objects);
/// Disposes this list. It is important to call this method when the list is
diff --git a/hive/lib/src/object/hive_list_impl.dart b/hive/lib/src/object/hive_list_impl.dart
index c5c947c62..baa6a0649 100644
--- a/hive/lib/src/object/hive_list_impl.dart
+++ b/hive/lib/src/object/hive_list_impl.dart
@@ -14,20 +14,20 @@ class HiveListImpl
/// Not part of public API
final String boxName;
- final List _keys;
+ final List? _keys;
HiveInterface _hive = Hive;
- List _delegate;
+ List? _delegate;
- Box _box;
+ Box? _box;
bool _invalidated = false;
bool _disposed = false;
/// Not part of public API
- HiveListImpl(Box box, {List objects})
+ HiveListImpl(Box box, {List? objects})
: boxName = box.name,
_keys = null,
_delegate = [],
@@ -38,12 +38,12 @@ class HiveListImpl
}
/// Not part of public API
- HiveListImpl.lazy(this.boxName, List keys) : _keys = keys;
+ HiveListImpl.lazy(this.boxName, List? keys) : _keys = keys;
@override
Iterable get keys {
if (_delegate == null) {
- return _keys;
+ return _keys!;
} else {
return super.keys;
}
@@ -60,10 +60,10 @@ class HiveListImpl
throw HiveError('The box "$boxName" is a lazy box. '
'You can only use HiveLists with normal boxes.');
} else {
- _box = box as Box;
+ _box = box;
}
}
- return _box;
+ return _box!;
}
@override
@@ -74,7 +74,7 @@ class HiveListImpl
if (_invalidated) {
var retained = [];
- for (var obj in _delegate) {
+ for (var obj in _delegate!) {
if (obj.isInHiveList(this)) {
retained.add(obj);
}
@@ -83,7 +83,7 @@ class HiveListImpl
_invalidated = false;
} else if (_delegate == null) {
var list = [];
- for (var key in _keys) {
+ for (var key in _keys!) {
if (box.containsKey(key)) {
var obj = box.get(key) as E;
obj.linkHiveList(this);
@@ -93,13 +93,13 @@ class HiveListImpl
_delegate = list;
}
- return _delegate;
+ return _delegate!;
}
@override
void dispose() {
if (_delegate != null) {
- for (var element in _delegate) {
+ for (var element in _delegate!) {
element.unlinkHiveList(this);
}
_delegate = null;
@@ -116,19 +116,16 @@ class HiveListImpl
}
void _checkElementIsValid(E obj) {
- if (obj == null) {
- throw HiveError('HiveLists must not contain null elements.');
- } else if (obj.box != box) {
+ if (obj.box != box) {
throw HiveError('HiveObjects needs to be in the box "$boxName".');
}
}
@override
set length(int newLength) {
- var delegate = this.delegate;
if (newLength < delegate.length) {
for (var i = newLength; i < delegate.length; i++) {
- delegate[i]?.unlinkHiveList(this);
+ delegate[i].unlinkHiveList(this);
}
}
delegate.length = newLength;
@@ -142,7 +139,7 @@ class HiveListImpl
var oldValue = delegate[index];
delegate[index] = value;
- oldValue?.unlinkHiveList(this);
+ oldValue.unlinkHiveList(this);
}
@override
@@ -156,8 +153,6 @@ class HiveListImpl
void addAll(Iterable iterable) {
for (var element in iterable) {
_checkElementIsValid(element);
- }
- for (var element in iterable) {
element.linkHiveList(this);
}
delegate.addAll(iterable);
@@ -166,7 +161,7 @@ class HiveListImpl
@override
HiveList castHiveList() {
if (_delegate != null) {
- return HiveListImpl(box, objects: _delegate.cast());
+ return HiveListImpl(box, objects: _delegate!.cast());
} else {
return HiveListImpl.lazy(boxName, _keys);
}
diff --git a/hive/lib/src/object/hive_object.dart b/hive/lib/src/object/hive_object.dart
index 79c680e53..8bd86d9f3 100644
--- a/hive/lib/src/object/hive_object.dart
+++ b/hive/lib/src/object/hive_object.dart
@@ -9,7 +9,7 @@ part 'hive_object_internal.dart';
/// Extend `HiveObject` to add useful methods to the objects you want to store
/// in Hive
abstract class HiveObject {
- BoxBase _box;
+ BoxBase? _box;
dynamic _key;
@@ -18,7 +18,7 @@ abstract class HiveObject {
/// Get the box in which this object is stored. Returns `null` if object has
/// not been added to a box yet.
- BoxBase get box => _box;
+ BoxBase? get box => _box;
/// Get the key associated with this object. Returns `null` if object has
/// not been added to a box yet.
@@ -33,13 +33,13 @@ abstract class HiveObject {
/// Persists this object.
Future save() {
_requireInitialized();
- return _box.put(_key, this);
+ return _box!.put(_key, this);
}
/// Deletes this object from the box it is stored in.
Future delete() {
_requireInitialized();
- return _box.delete(_key);
+ return _box!.delete(_key);
}
/// Returns whether this object is currently stored in a box.
@@ -48,8 +48,8 @@ abstract class HiveObject {
/// whether this instance is actually stored in the box.
bool get isInBox {
if (_box != null) {
- if (_box.lazy) {
- return _box.containsKey(_key);
+ if (_box!.lazy) {
+ return _box!.containsKey(_key);
} else {
return true;
}
diff --git a/hive/lib/src/object/hive_object_internal.dart b/hive/lib/src/object/hive_object_internal.dart
index 780965de9..c4d5c0e12 100644
--- a/hive/lib/src/object/hive_object_internal.dart
+++ b/hive/lib/src/object/hive_object_internal.dart
@@ -39,7 +39,9 @@ extension HiveObjectInternal on HiveObject {
/// Not part of public API
void unlinkHiveList(HiveList list) {
- if (--_hiveLists[list] <= 0) {
+ final currentIndex = _hiveLists[list]!;
+ final newIndex = _hiveLists[list] = currentIndex - 1;
+ if (newIndex <= 0) {
_hiveLists.remove(list);
}
}
diff --git a/hive/lib/src/registry/type_registry_impl.dart b/hive/lib/src/registry/type_registry_impl.dart
index 95ae2acfd..a66cd752d 100644
--- a/hive/lib/src/registry/type_registry_impl.dart
+++ b/hive/lib/src/registry/type_registry_impl.dart
@@ -2,25 +2,60 @@ import 'package:hive/hive.dart';
import 'package:hive/src/adapters/ignored_type_adapter.dart';
import 'package:meta/meta.dart';
-class _ResolvedAdapter {
+/// Not part of public API
+///
+/// Needed to codegen the TypeRegistry mock
+@visibleForTesting
+class ResolvedAdapter {
final TypeAdapter adapter;
final int typeId;
- _ResolvedAdapter(this.adapter, this.typeId);
+ ResolvedAdapter(this.adapter, this.typeId);
bool matches(dynamic value) => value is T;
}
+class _NullTypeRegistry implements TypeRegistryImpl {
+ const _NullTypeRegistry();
+
+ @override
+ Never get _typeAdapters => throw UnimplementedError();
+
+ @override
+ Never findAdapterForTypeId(int typeId) => throw UnimplementedError();
+
+ @override
+ Never findAdapterForValue(value) => throw UnimplementedError();
+
+ @override
+ Never ignoreTypeId(int typeId) => throw UnimplementedError();
+
+ @override
+ Never isAdapterRegistered(int typeId, {bool internal = false}) =>
+ throw UnimplementedError();
+
+ @override
+ Never registerAdapter(TypeAdapter adapter,
+ {bool internal = false, bool override = false}) =>
+ throw UnimplementedError();
+
+ @override
+ Never resetAdapters() => throw UnimplementedError();
+}
+
/// Not part of public API
class TypeRegistryImpl implements TypeRegistry {
+ /// Not part of public API
+ static const TypeRegistryImpl nullImpl = _NullTypeRegistry();
+
/// Not part of public API
@visibleForTesting
static const reservedTypeIds = 32;
- final _typeAdapters = {};
+ final _typeAdapters = {};
/// Not part of public API
- _ResolvedAdapter findAdapterForValue(dynamic value) {
+ ResolvedAdapter? findAdapterForValue(dynamic value) {
for (var adapter in _typeAdapters.values) {
if (adapter.matches(value)) return adapter;
}
@@ -28,7 +63,7 @@ class TypeRegistryImpl implements TypeRegistry {
}
/// Not part of public API
- _ResolvedAdapter findAdapterForTypeId(int typeId) {
+ ResolvedAdapter? findAdapterForTypeId(int typeId) {
return _typeAdapters[typeId];
}
@@ -62,7 +97,7 @@ class TypeRegistryImpl implements TypeRegistry {
}
}
- var resolved = _ResolvedAdapter(adapter, typeId);
+ var resolved = ResolvedAdapter(adapter, typeId);
_typeAdapters[typeId] = resolved;
}
diff --git a/hive/lib/src/util/delegating_list_view_mixin.dart b/hive/lib/src/util/delegating_list_view_mixin.dart
index 27aa031bf..43cc86c54 100644
--- a/hive/lib/src/util/delegating_list_view_mixin.dart
+++ b/hive/lib/src/util/delegating_list_view_mixin.dart
@@ -32,7 +32,7 @@ abstract class DelegatingListViewMixin implements List {
List cast() => delegate.cast();
@override
- bool contains(Object element) => delegate.contains(element);
+ bool contains(Object? element) => delegate.contains(element);
@override
E elementAt(int index) => delegate.elementAt(index);
@@ -45,7 +45,7 @@ abstract class DelegatingListViewMixin implements List {
delegate.expand(f);
@override
- E firstWhere(bool Function(E element) test, {E Function() orElse}) =>
+ E firstWhere(bool Function(E element) test, {E Function()? orElse}) =>
delegate.firstWhere(test, orElse: orElse);
@override
@@ -62,7 +62,7 @@ abstract class DelegatingListViewMixin implements List {
Iterable getRange(int start, int end) => delegate.getRange(start, end);
@override
- int indexOf(Object element, [int start = 0]) =>
+ int indexOf(Object? element, [int start = 0]) =>
delegate.indexOf(element as E, start);
@override
@@ -82,15 +82,15 @@ abstract class DelegatingListViewMixin implements List {
String join([String separator = '']) => delegate.join(separator);
@override
- int lastIndexOf(Object element, [int start]) =>
+ int lastIndexOf(Object? element, [int? start]) =>
delegate.lastIndexOf(element as E, start);
@override
- int lastIndexWhere(bool Function(E element) test, [int start]) =>
+ int lastIndexWhere(bool Function(E element) test, [int? start]) =>
delegate.lastIndexWhere(test, start);
@override
- E lastWhere(bool Function(E element) test, {E Function() orElse}) =>
+ E lastWhere(bool Function(E element) test, {E Function()? orElse}) =>
delegate.lastWhere(test, orElse: orElse);
@override
@@ -106,7 +106,7 @@ abstract class DelegatingListViewMixin implements List {
E get single => delegate.single;
@override
- E singleWhere(bool Function(E element) test, {E Function() orElse}) =>
+ E singleWhere(bool Function(E element) test, {E Function()? orElse}) =>
delegate.singleWhere(test, orElse: orElse);
@override
@@ -117,7 +117,7 @@ abstract class DelegatingListViewMixin implements List {
delegate.skipWhile(test);
@override
- List sublist(int start, [int end]) => delegate.sublist(start, end);
+ List sublist(int start, [int? end]) => delegate.sublist(start, end);
@override
Iterable take(int count) => delegate.take(count);
diff --git a/hive/lib/src/util/indexable_skip_list.dart b/hive/lib/src/util/indexable_skip_list.dart
index 46474be07..4cd86739d 100644
--- a/hive/lib/src/util/indexable_skip_list.dart
+++ b/hive/lib/src/util/indexable_skip_list.dart
@@ -8,7 +8,7 @@ class IndexableSkipList {
final _Node _head = _Node(
null,
null,
- List(_maxHeight),
+ List.filled(_maxHeight, null),
List.filled(_maxHeight, 0),
);
@@ -21,7 +21,7 @@ class IndexableSkipList {
int _length = 0;
/// Not part of public API
- IndexableSkipList(this._comparator, [Random random])
+ IndexableSkipList(this._comparator, [Random? random])
: _random = random ?? Random();
/// Not part of public API
@@ -34,7 +34,7 @@ class IndexableSkipList {
Iterable get values => _ValueIterable(_head);
/// Not part of public API
- V insert(K key, V value) {
+ V? insert(K key, V? value) {
var existingNode = _getNode(key);
if (existingNode != null) {
var oldValue = existingNode.value;
@@ -54,7 +54,7 @@ class IndexableSkipList {
var newNode = _Node(
key,
value,
- List(newLevel + 1),
+ List.filled(newLevel + 1, null),
List.filled(newLevel + 1, 0),
);
@@ -63,7 +63,7 @@ class IndexableSkipList {
for (var level = _height - 1; level >= 0; level--) {
while (true) {
var next = current.next[level];
- if (next == null || _comparator(key, next.key) < 0) break;
+ if (next == null || _comparator(key, next.key!) < 0) break;
current = next;
}
@@ -83,7 +83,7 @@ class IndexableSkipList {
// CHANGE 3 - Calculate the width of the level
var width = 0;
var node = current.next[level - 1];
- while (node != null && _comparator(key, node.key) >= 0) {
+ while (node != null && _comparator(key, node.key!) >= 0) {
width += node.width[level - 1];
node = node.next[level - 1];
}
@@ -112,7 +112,7 @@ class IndexableSkipList {
}
/// Not part of public API
- V delete(K key) {
+ V? delete(K key) {
var node = _getNode(key);
if (node == null) return null;
@@ -121,7 +121,7 @@ class IndexableSkipList