putIfAbsent method

  1. @override
Future<bool> putIfAbsent(
  1. String key,
  2. T value, {
  3. VaultEntryDelegate<T>? delegate,
})
override

Associates the specified key with the given value

  • key: key with which the specified value is to be associated
  • value: value to be associated with the specified key
  • delegate: provides the caller a way of changing the VaultEntry before persistence

Returns true if a value was set.

Implementation

@override
Future<bool> putIfAbsent(String key, T value,
    {VaultEntryDelegate<T>? delegate}) {
  // Current time
  final now = clock.now();
  // #region Statistics
  Stopwatch? watch;
  Future<VaultInfo?> Function(VaultInfo? info) posGet =
      (VaultInfo? entry) => Future.value(entry);
  Future<bool> Function(bool) posPut = (bool ok) => Future<bool>.value(ok);
  if (statsEnabled) {
    watch = clock.stopwatch()..start();
    posGet = (VaultInfo? info) {
      stats.increaseGets();

      return Future.value(info);
    };
    posPut = (bool ok) {
      if (ok) {
        stats.increasePuts();
      }
      if (watch != null) {
        stats.addPutTime(watch.elapsedMicroseconds);
        watch.stop();
      }

      return Future<bool>.value(ok);
    };
  }
  // #endregion

  // Try to get the entry from the vault
  return _getStorageInfo(key).then(posGet).then((entry) {
    // If the entry does not exist
    if (entry == null) {
      return _newEntry(_entryBuilder(key, value, now))
          .then((_) => posPut(true));
    }

    return posPut(false);
  });
}