<commit_before>library more.cache.expiry;

import 'dart:async';

import 'package:more/cache.dart';
import 'package:more/src/cache/clock.dart';
import 'package:more/src/cache/item.dart';
import 'package:more/src/cache/loader.dart';

/// A cache that expires after a certain amount of time.
class ExpiryCache<K, V> extends Cache<K, V> {

  final Loader<K, V> loader;

  final Clock clock;

  final Duration updateExpiry;

  final Duration accessExpiry;

  final Map<K, ExpiryCacheItem<V>> cached = new Map();

  ExpiryCache(this.loader, this.clock, this.updateExpiry, this.accessExpiry);

  @override
  Future<V> get(K key) async {
    var now = clock();
    var item = cached[key];
    if (item == null) {
      item = cached[key] = new ExpiryCacheItem(loader(key), now);
    } else if (item.isExpired(now, updateExpiry, accessExpiry)) {
      item.lastAccess = item.lastUpdate = now;
      item.value = loader(key);
    } else {
      item.lastAccess = now;
    }
    return item.value;
  }

  @override
  Future<V> getIfPresent(K key) async {
    var now = clock();
    var item = cached[key];<commit_msg>Make sure that throwing an exception in the loader has no side-effects.<commit_after>library more.cache.expiry;

import 'dart:async';

import 'package:more/cache.dart';
import 'package:more/src/cache/clock.dart';
import 'package:more/src/cache/item.dart';
import 'package:more/src/cache/loader.dart';

/// A cache that expires after a certain amount of time.
class ExpiryCache<K, V> extends Cache<K, V> {

  final Loader<K, V> loader;

  final Clock clock;

  final Duration updateExpiry;

  final Duration accessExpiry;

  final Map<K, ExpiryCacheItem<V>> cached = new Map();

  ExpiryCache(this.loader, this.clock, this.updateExpiry, this.accessExpiry);

  @override
  Future<V> get(K key) async {
    var now = clock();
    var item = cached[key];
    if (item == null) {
      item = cached[key] = new ExpiryCacheItem(loader(key), now);
    } else if (item.isExpired(now, updateExpiry, accessExpiry)) {
      item.value = loader(key);
      item.lastAccess = item.lastUpdate = now;
    } else {
      item.lastAccess = now;
    }
    return item.value;
  }

  @override
  Future<V> getIfPresent(K key) async {
    var now = clock();
    var item = cached[key];
{'fraction_non_alphanumeric': 0.13127753303964756, 'fraction_numerical': 0.0, 'mean_word_length': 3.5786290322580645, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5597954', 'n_tokens_mistral': 799, 'n_tokens_neox': 771, 'n_words': 202}