Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(156)

Side by Side Diff: sdk/lib/observe/list_diff.dart

Issue 14732003: Implement Model-Driven-Views spec for Dart (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: trying upload again Created 7 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 part of dart.observe;
6
7 // Note: most of this code is a port of:
8 // https://github.com/rafaelw/ChangeSummary/blob/master/change_summary.js
9 //
10 // It contains the logic for computing List diffs. Because this algorithm is
11 // fairly separable from the rest of the code, it gets put in this file.
12
13 /**
14 * Summarize changes to [list]. This takes the changes in aggregate and computes
15 * the minimal "splices"--add/remove/update operations--that are necessary
16 * to reach the final state of the list.
17 *
18 * The return value is a [List] of [ListChangeDelta], where each delta is
19 * conceptually a tuple of:
20 *
21 * <index, removed, addedCount>
22 *
23 * These are returned in ascending index order.
24 *
25 * Lacking individual splice mutation information, the minimal set of
26 * splices can be synthesized given the previous state and final state of an
27 * array. The basic approach is to calculate the edit distance matrix and
28 * choose the shortest path through it.
29 *
30 * Complexity is `O(l * p)`, where `l` is the length of the current list and
31 * `p` is the length of the old list.
32 */
33 List<ListChangeDelta> summarizeListChanges(List list,
34 List<ChangeRecord> records) {
35
36 // TODO(jmesserly): should we cut out the middle man, and produce
37 // ListChangeDeltas straight from ObservableList? Then it's just a matter of
blois 2013/05/01 17:00:42 I think we should consider this. I'd also be inter
38 // summarizing them. That's probably a lot faster than this approach.
39 var diff = new _ListChangeSummary.fromRecords(list, records);
40
41 var initialSplices = _createInitialSplicesFromDiff(list, diff);
42 var splices = [];
43 for (var splice in initialSplices) {
44 var calculatedSplices = _calcSplices(list, splice.index,
45 splice.index + splice.addedCount, splice.removed, 0,
46 splice.removed.length);
47
48 splices.addAll(calculatedSplices);
49 }
50
51 return splices;
52 }
53
54 /**
55 * A summary of an individual change to a [List].
56 *
57 * Each delta represents that at the [index], [removed] sequence of items were
58 * removed, and counting forward from [index], [addedCount] items were added.
59 *
60 * See also: [summarizeListChanges].
61 */
62 class ListChangeDelta {
63 /** The index of the change. */
64 final int index;
65
66 List _removed;
blois 2013/05/01 17:00:42 final?
67
68 // Note: conceptually final, but for convenience we increment it as we build
69 // the object. It will be "frozen" by the time it is returned the the user.
70 int _addedCount = 0;
71
72 ListChangeDelta(this.index, {List removed, int addedCount: 0})
73 : _removed = removed != null ? removed : [],
74 _addedCount = addedCount;
75
76 // TODO(jmesserly): freeze remove list before handing it out?
77 /** The items removed, if any. Otherwise this will be an empty list. */
78 List get removed => _removed;
79
80 /** The number of items added. */
81 int get addedCount => _addedCount;
82
83 String toString() => '#<$runtimeType index: $index, '
84 'removed: $removed, addedCount: $addedCount>';
85 }
86
87 // Note: This function is *based* on the computation of the Levenshtein
88 // "edit" distance. The one change is that "updates" are treated as two
89 // edits - not one. With List splices, an update is really a delete
90 // followed by an add. By retaining this, we optimize for "keeping" the
91 // maximum array items in the original array. For example:
92 //
93 // 'xxxx123' -> '123yyyy'
94 //
95 // With 1-edit updates, the shortest path would be just to update all seven
96 // characters. With 2-edit updates, we delete 4, leave 3, and add 4. This
97 // leaves the substring '123' intact.
98 List<List<int>> _calcEditDistances(List current, int currentStart,
99 int currentEnd, List old, int oldStart, int oldEnd) {
100 // "Deletion" columns
101 var rowCount = oldEnd - oldStart + 1;
102 var columnCount = currentEnd - currentStart + 1;
103 var distances = new List(rowCount);
104
105 // "Addition" rows. Initialize null column.
106 for (var i = 0; i < rowCount; i++) {
107 distances[i] = new List(columnCount);
108 distances[i][0] = i;
109 }
110
111 // Initialize null row
112 for (var j = 0; j < columnCount; j++) {
113 distances[0][j] = j;
114 }
115
116 for (var i = 1; i < rowCount; i++) {
117 for (var j = 1; j < columnCount; j++) {
118 if (identical(old[oldStart + i - 1], current[currentStart + j - 1])) {
119 distances[i][j] = distances[i - 1][j - 1];
120 } else {
121 var north = distances[i - 1][j] + 1;
122 var west = distances[i][j - 1] + 1;
123 distances[i][j] = north < west ? north : west;
Siggi Cherem (dart-lang) 2013/05/01 18:57:56 consider using math.min?
Jennifer Messerly 2013/05/02 02:58:33 Done.
124 }
125 }
126 }
127
128 return distances;
129 }
130
131 const _EDIT_LEAVE = 0;
132 const _EDIT_UPDATE = 1;
133 const _EDIT_ADD = 2;
134 const _EDIT_DELETE = 3;
135
136 // This starts at the final weight, and walks "backward" by finding
137 // the minimum previous weight recursively until the origin of the weight
138 // matrix.
139 List<int> _spliceOperationsFromEditDistances(List<List<int>> distances) {
140 var i = distances.length - 1;
141 var j = distances[0].length - 1;
142 var current = distances[i][j];
143 var edits = [];
144 while (i > 0 || j > 0) {
145 if (i == 0) {
146 edits.add(_EDIT_ADD);
147 j--;
148 continue;
149 }
150 if (j == 0) {
151 edits.add(_EDIT_DELETE);
152 i--;
153 continue;
154 }
155 var northWest = distances[i - 1][j - 1];
156 var west = distances[i - 1][j];
157 var north = distances[i][j - 1];
158
159 var min;
160 if (west < north) {
Siggi Cherem (dart-lang) 2013/05/01 18:57:56 ditto: var m = math.min(northWest, math.min(west,
Jennifer Messerly 2013/05/02 02:58:33 Done.
161 min = west < northWest ? west : northWest;
162 } else {
163 min = north < northWest ? north : northWest;
164 }
165
166 if (min == northWest) {
167 if (northWest == current) {
168 edits.add(_EDIT_LEAVE);
169 } else {
170 edits.add(_EDIT_UPDATE);
171 current = northWest;
172 }
173 i--;
174 j--;
175 } else if (min == west) {
176 edits.add(_EDIT_DELETE);
177 i--;
178 current = west;
179 } else {
180 edits.add(_EDIT_ADD);
181 j--;
182 current = north;
183 }
184 }
185
186 return edits.reversed.toList();
187 }
188
189 int _sharedPrefix(List arr1, List arr2, int searchLength) {
190 for (var i = 0; i < searchLength; i++) {
191 if (!identical(arr1[i], arr2[i])) {
192 return i;
193 }
194 }
195 return searchLength;
196 }
197
198 int _sharedSuffix(List arr1, List arr2, int searchLength) {
199 var index1 = arr1.length;
200 var index2 = arr2.length;
201 var count = 0;
202 while (count < searchLength && identical(arr1[--index1], arr2[--index2])) {
203 count++;
204 }
205 return count;
206 }
207
208 /**
209 * Lacking individual splice mutation information, the minimal set of
210 * splices can be synthesized given the previous state and final state of an
211 * array. The basic approach is to calculate the edit distance matrix and
212 * choose the shortest path through it.
213 *
214 * Complexity: O(l * p)
215 * l: The length of the current array
216 * p: The length of the old array
217 */
218 List<ListChangeDelta> _calcSplices(List current, int currentStart,
219 int currentEnd, List old, int oldStart, int oldEnd) {
220
221 var prefixCount = 0;
222 var suffixCount = 0;
223
224 var minLength = math.min(currentEnd - currentStart, oldEnd - oldStart);
225 if (currentStart == 0 && oldStart == 0) {
226 prefixCount = _sharedPrefix(current, old, minLength);
227 }
228
229 if (currentEnd == current.length && oldEnd == old.length) {
230 suffixCount = _sharedSuffix(current, old, minLength - prefixCount);
231 }
232
233 currentStart += prefixCount;
234 oldStart += prefixCount;
235 currentEnd -= suffixCount;
236 oldEnd -= suffixCount;
237
238 if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) {
239 return const [];
240 }
241
242 if (currentStart == currentEnd) {
243 var splice = new ListChangeDelta(currentStart);
244 while (oldStart < oldEnd)
Siggi Cherem (dart-lang) 2013/05/01 18:57:56 style: add braces for the loop
Jennifer Messerly 2013/05/02 02:58:33 thanks. I had to fix that in sooooo many places, l
245 splice.removed.add(old[oldStart++]);
246
247 return [ splice ];
Siggi Cherem (dart-lang) 2013/05/01 18:57:56 style, remove spaces after [ and before ]
Jennifer Messerly 2013/05/02 02:58:33 done, but last I checked, there is no agreed upon
Siggi Cherem (dart-lang) 2013/05/02 16:21:08 I was surprised to find it there, but apparently w
248 } else if (oldStart == oldEnd)
249 return [ new ListChangeDelta(currentStart,
Siggi Cherem (dart-lang) 2013/05/01 18:57:56 likewise
Jennifer Messerly 2013/05/02 02:58:33 Done.
250 addedCount: currentEnd - currentStart) ];
251
252 var ops = _spliceOperationsFromEditDistances(
253 _calcEditDistances(current, currentStart, currentEnd, old, oldStart,
254 oldEnd));
255
256 ListChangeDelta splice = null;
257 var splices = <ListChangeDelta>[];
258 var index = currentStart;
259 var oldIndex = oldStart;
260 for (var i = 0; i < ops.length; i++) {
261 switch(ops[i]) {
262 case _EDIT_LEAVE:
263 if (splice != null) {
264 splices.add(splice);
265 splice = null;
266 }
267
268 index++;
269 oldIndex++;
270 break;
271 case _EDIT_UPDATE:
272 if (splice == null) splice = new ListChangeDelta(index);
273
274 splice._addedCount++;
275 index++;
276
277 splice.removed.add(old[oldIndex]);
278 oldIndex++;
279 break;
280 case _EDIT_ADD:
281 if (splice == null) splice = new ListChangeDelta(index);
282
283 splice._addedCount++;
284 index++;
285 break;
286 case _EDIT_DELETE:
287 if (splice == null) splice = new ListChangeDelta(index);
288
289 splice.removed.add(old[oldIndex]);
290 oldIndex++;
291 break;
292 }
293 }
294
295 if (splice != null) {
296 splices.add(splice);
297 }
298 return splices;
299 }
300
301 List<ListChangeDelta> _createInitialSplicesFromDiff(List list,
302 _ListChangeSummary diff) {
303
304 var oldLength = diff.oldFields['length'];
305 if (oldLength == null) oldLength = list.length;
306
307 ListChangeDelta lengthChange = null;
308 if (list.length > oldLength) {
309 lengthChange = new ListChangeDelta(oldLength,
310 addedCount: list.length - oldLength);
311 } else if (list.length < oldLength) {
312 lengthChange = new ListChangeDelta(list.length,
313 removed: new List(oldLength - list.length));
314 }
315
316 var indicesChanged = new SplayTreeMap<int, Object>();
317 for (var properties in [diff.added, diff.removed, diff.items]) {
318 for (var index in properties.keys) {
319 if (index.isNaN || index < 0 || index >= oldLength) {
320 continue;
321 }
322
323 var oldValue = diff.oldItems[index];
324 if (index < list.length) {
325 indicesChanged[index] = oldValue;
326 } else {
327 lengthChange.removed[index - list.length] = diff.oldItems[index];
328 }
329 }
330 }
331
332 var splices = <ListChangeDelta>[];
333 ListChangeDelta current = null;
334
335 for (var index in indicesChanged.keys) {
336 if (current != null) {
337 if (current.index + current.removed.length == index) {
338 current.removed.add(indicesChanged[index]);
339 continue;
340 }
341
342 current._addedCount = math.min(list.length, current.index +
343 current.removed.length) - current.index;
344 splices.add(current);
345 current = null;
346 }
347
348 current = new ListChangeDelta(index, removed: [indicesChanged[index]]);
349 }
350
351 if (current != null) {
352 current._addedCount = math.min(
353 list.length, current.index + current.removed.length) - current.index;
354
355 if (lengthChange != null) {
356 if (current.index + current.removed.length == lengthChange.index) {
357 // Join splices
358 current._addedCount = current.addedCount + lengthChange.addedCount;
359 current.removed.addAll(lengthChange.removed);
360 splices.add(current);
361 } else {
362 splices.add(current);
363 splices.add(lengthChange);
364 }
365 } else {
366 splices.add(current);
367 }
368 } else if (lengthChange != null) {
369 splices.add(lengthChange);
370 }
371
372 return splices;
373 }
374
375
376 class _ListChangeSummary {
377 final Map added = new LinkedHashMap();
378 final Map removed = new LinkedHashMap();
379 final Map items = new LinkedHashMap();
380 final Map oldFields = new LinkedHashMap();
381 final Map oldItems = new LinkedHashMap();
382
383 _ListChangeSummary.fromRecords(List list, List<ChangeRecord> records) {
384
385 for (var record in records) {
386 var key = record.key;
387 if (record.kind == ChangeRecord.FIELD) {
388 oldFields.putIfAbsent(key, () => record.oldValue);
389 continue;
390 }
391
392 oldItems.putIfAbsent(key, () => record.oldValue);
393
394 if (record.kind == ChangeRecord.INSERT) {
395 removed.remove(key);
396 added[key] = record.newValue;
397 } else if (record.kind == ChangeRecord.REMOVE) {
398 if (added.containsKey(key)) {
399 added.remove(key);
400 oldItems.remove(key);
401 } else {
402 items.remove(key);
403 removed[key] = null;
404 }
405 } else if (record.kind == ChangeRecord.INDEX) {
406 // TODO(jmesserly): arguably our ObservableList should not do this.
407 removed.remove(key);
408 var update = added.containsKey(key) ? added : items;
409 update[key] = record.newValue;
410 }
411 }
412 }
413
414 bool get isEmpty => added.isEmpty && removed.isEmpty && items.isEmpty;
415 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698