Fri, 16 Jan 2015 18:13:44 +0100
Integrate suggestion from review to improve consistency with existing code.
1 //* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "ChunkSet.h"
8 namespace mozilla {
9 namespace safebrowsing {
11 nsresult
12 ChunkSet::Serialize(nsACString& aChunkStr)
13 {
14 aChunkStr.Truncate();
16 uint32_t i = 0;
17 while (i < mChunks.Length()) {
18 if (i != 0) {
19 aChunkStr.Append(',');
20 }
21 aChunkStr.AppendInt((int32_t)mChunks[i]);
23 uint32_t first = i;
24 uint32_t last = first;
25 i++;
26 while (i < mChunks.Length() && (mChunks[i] == mChunks[i - 1] + 1 || mChunks[i] == mChunks[i - 1])) {
27 last = i++;
28 }
30 if (last != first) {
31 aChunkStr.Append('-');
32 aChunkStr.AppendInt((int32_t)mChunks[last]);
33 }
34 }
36 return NS_OK;
37 }
39 nsresult
40 ChunkSet::Set(uint32_t aChunk)
41 {
42 uint32_t idx = mChunks.BinaryIndexOf(aChunk);
43 if (idx == nsTArray<uint32_t>::NoIndex) {
44 mChunks.InsertElementSorted(aChunk);
45 }
46 return NS_OK;
47 }
49 nsresult
50 ChunkSet::Unset(uint32_t aChunk)
51 {
52 mChunks.RemoveElementSorted(aChunk);
54 return NS_OK;
55 }
57 bool
58 ChunkSet::Has(uint32_t aChunk) const
59 {
60 return mChunks.BinaryIndexOf(aChunk) != nsTArray<uint32_t>::NoIndex;
61 }
63 nsresult
64 ChunkSet::Merge(const ChunkSet& aOther)
65 {
66 const uint32_t *dupIter = aOther.mChunks.Elements();
67 const uint32_t *end = aOther.mChunks.Elements() + aOther.mChunks.Length();
69 for (const uint32_t *iter = dupIter; iter != end; iter++) {
70 nsresult rv = Set(*iter);
71 NS_ENSURE_SUCCESS(rv, rv);
72 }
74 return NS_OK;
75 }
77 nsresult
78 ChunkSet::Remove(const ChunkSet& aOther)
79 {
80 uint32_t *addIter = mChunks.Elements();
81 uint32_t *end = mChunks.Elements() + mChunks.Length();
83 for (uint32_t *iter = addIter; iter != end; iter++) {
84 if (!aOther.Has(*iter)) {
85 *addIter = *iter;
86 addIter++;
87 }
88 }
90 mChunks.SetLength(addIter - mChunks.Elements());
92 return NS_OK;
93 }
95 void
96 ChunkSet::Clear()
97 {
98 mChunks.Clear();
99 }
101 }
102 }