Bug 1358846: Part 2 - Allow using file compression with JSONFile.jsm. r?rhelmer
MozReview-Commit-ID: 5lHsZqBGq3E
--- a/toolkit/modules/JSONFile.jsm
+++ b/toolkit/modules/JSONFile.jsm
@@ -85,32 +85,39 @@ const kSaveDelayMs = 1500;
* data is written to disk. This can be used to create any
* intermediate directories before saving. The file will
* not be saved if the promise rejects or the function
* throws an exception.
* - finalizeAt: An `AsyncShutdown` phase or barrier client that should
* automatically finalize the file when triggered. Defaults
* to `profileBeforeChange`; exposed as an option for
* testing.
+ * - compression: A compression algorithm to use when reading and
+ * writing the data.
*/
function JSONFile(config) {
this.path = config.path;
if (typeof config.dataPostProcessor === "function") {
this._dataPostProcessor = config.dataPostProcessor;
}
if (typeof config.beforeSave === "function") {
this._beforeSave = config.beforeSave;
}
if (config.saveDelayMs === undefined) {
config.saveDelayMs = kSaveDelayMs;
}
this._saver = new DeferredTask(() => this._save(), config.saveDelayMs);
+ this._options = {};
+ if (config.compression) {
+ this._options.compression = config.compression;
+ }
+
this._finalizeAt = config.finalizeAt || AsyncShutdown.profileBeforeChange;
this._finalizeInternalBound = this._finalizeInternal.bind(this);
this._finalizeAt.addBlocker("JSON store: writing data",
this._finalizeInternalBound);
}
JSONFile.prototype = {
/**
@@ -171,17 +178,17 @@ JSONFile.prototype = {
* @resolves When the operation finished successfully.
* @rejects JavaScript exception when dataPostProcessor fails. It never fails
* if there is no dataPostProcessor.
*/
load: Task.async(function* () {
let data = {};
try {
- let bytes = yield OS.File.read(this.path);
+ let bytes = yield OS.File.read(this.path, this._options);
// If synchronous loading happened in the meantime, exit now.
if (this.dataReady) {
return;
}
data = JSON.parse(gTextDecoder.decode(bytes));
} catch (ex) {
@@ -281,17 +288,19 @@ JSONFile.prototype = {
*/
_save: Task.async(function* () {
// Create or overwrite the file.
let bytes = gTextEncoder.encode(JSON.stringify(this._data));
if (this._beforeSave) {
yield Promise.resolve(this._beforeSave());
}
yield OS.File.writeAtomic(this.path, bytes,
- { tmpPath: this.path + ".tmp" });
+ Object.assign(
+ { tmpPath: this.path + ".tmp" },
+ this._options));
}),
/**
* Synchronously work on the data just loaded into memory.
*/
_processLoadedData(data) {
if (this._finalizePromise) {
// It's possible for `load` to race with `finalize`. In that case, don't