fmap 0.1.1+1 fmap: ^0.1.1+1 copied to clipboard
A `Map` implementation that stores its entries in files. Can be used as a cache or persistent key-value storage.
fmap #
Dart library with a Map
implementation that stores its entries in files.
Can be used as a cache or persistent key-value storage.
var fmap = Fmap(directory);
fmap['keyA'] = 'my string'; // saved string into a file
fmap['keyB'] = 777; // saved int into a file
fmap['keyC'] = [0x12, 0x34, 0x56]; // saved three-bytes into a file
print(fmap['keyA']); // read from file
This object has the same API as ordinary Map
.
Map fmap = Fmap(directory);
print('Count of items: ${fmap.length}');
for (var entry in fmap.entries) {
print('Item ${entry.key} ${entry.value}');
}
Types #
The object is intended primarily for storing values of type String
and Uint8List
(blobs).
var objects = Fmap(directory);
fmap['myJson'] = httpGet('http://somewhere'); // String
fmap['blob'] = myFile.readAsBytesSync(); // Uint8List
Any List<int>
will also be treated as list of bytes.
fmap['blob2'] = [0x12, 0x34, 0x56];
fmap['blob3'] = utf8.encode('my string'); // List<int>
When saving, each int
inside a list will be truncated to the range 0..255.
fmap['blob3'] = [1, 10, -1, 777]; // saves 1, 10, 255, 9
In addition to strings and bytes, you can also store simple values of the
int
, double
, and bool
types. But keep in mind that each value is saved
in a separate file. Therefore, storing a lot of small values like int
may
not be the most efficient approach.
fmap['int'] = 5;
fmap['double'] = 5.0;
fmap['bool'] = true;
When creating an Fmap object, you can also restrict the type of stored values by using a generic argument.
var strings = Fmap<String>(directory);
var myJsonString = strings['json']; // definitely a string
// but now only strings can be read or written
var myIntValue = strings['number']; // throws exception
Purge #
If the storage has become too large, you can delete the oldest data.
// leave only the freshest 16 Mb
fmap.purgeSync(16*1024*1024);
Which elements are removed depends on the policy
argument passed to the
constructor.
final fmap = Fmap(dir, policy: Policy.fifo);
Two policies are supported: FIFO and LRU. By default, this is FIFO.
If you want the purgeSync
method to purge storage with LRU policy, you must
not only create Fmap(policy: Policy.lru)
before purging, but always
create the object this way. It will cause Fmap
to update the the last-used
timestamps every time an item is read.
When you do not specify this argument, the timestamps are only updated on writes, but not on reads. The order of the elements becomes closer to the FIFO.