diff --git a/services/sync/modules/util.js b/services/sync/modules/util.js index 44245919b010..1c8f3079bb00 100644 --- a/services/sync/modules/util.js +++ b/services/sync/modules/util.js @@ -249,6 +249,24 @@ let Utils = { return Utils.waitForSyncCallback(storageCallback.syncCb); }, + /* + * Partition the input array into an array of arrays. Return a generator. + */ + slices: function slices(arr, sliceSize) { + if (!sliceSize || sliceSize <= 0) + throw "Invalid slice size."; + + if (sliceSize > arr.length) { + yield arr; + } else { + let offset = 0; + while (arr.length > offset) { + yield arr.slice(offset, offset + sliceSize); + offset += sliceSize; + } + } + }, + byteArrayToString: function byteArrayToString(bytes) { return [String.fromCharCode(byte) for each (byte in bytes)].join(""); }, diff --git a/services/sync/tests/unit/test_utils_slices.js b/services/sync/tests/unit/test_utils_slices.js new file mode 100644 index 000000000000..7493e329043f --- /dev/null +++ b/services/sync/tests/unit/test_utils_slices.js @@ -0,0 +1,48 @@ +Cu.import("resource://services-sync/util.js"); + +function run_test() { + let input = [1, 2, 3, 4, 5]; + + let err; + try { + Utils.slices(input, 0).next(); + } catch (ex) { + err = ex; + } + do_check_eq("Invalid slice size.", err); + + err = undefined; + try { + Utils.slices(input).next(); + } catch (ex) { + err = ex; + } + do_check_eq("Invalid slice size.", err); + + function slurp(g) [x for each (x in g)] + + let sliced1 = slurp(Utils.slices(input, 1)); + let sliced2 = slurp(Utils.slices(input, 2)); + let sliced3 = slurp(Utils.slices(input, 5)); + let sliced4 = slurp(Utils.slices(input, 7)); + + do_check_eq(sliced1.length, 5); + do_check_eq(sliced2.length, 3); + do_check_eq(sliced3.length, 1); + do_check_eq(sliced4.length, 1); + sliced1.every(function(x) x.length == 1); + _(JSON.stringify(sliced2)); + do_check_eq(sliced2[0].length, 2); + do_check_eq(sliced2[1].length, 2); + do_check_eq(sliced2[2].length, 1); + sliced3.every(function(x) x.length == 5); + sliced4.every(function(x) x.length == 5); + + let sliced5 = slurp(Utils.slices(["foo"], 50)); + do_check_eq(sliced5.length, 1); + do_check_eq(sliced5[0], "foo"); + + let sliced6 = slurp(Utils.slices([], 50)); + do_check_eq(sliced6.length, 1); + do_check_eq(sliced6[0].length, 0); +} diff --git a/services/sync/tests/unit/xpcshell.ini b/services/sync/tests/unit/xpcshell.ini index a97e35228e94..e2a1405d5850 100644 --- a/services/sync/tests/unit/xpcshell.ini +++ b/services/sync/tests/unit/xpcshell.ini @@ -97,5 +97,6 @@ tail = [test_utils_sha1.js] [test_utils_sha1hmac.js] [test_utils_sha256HMAC.js] +[test_utils_slices.js] [test_utils_stackTrace.js] [test_utils_utf8.js]