| 1 | /* |
| 2 | * Copyright 2018 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package androidx.recyclerview.widget; |
| 18 | |
| 19 | import androidx.annotation.IntRange; |
| 20 | import androidx.annotation.NonNull; |
| 21 | import androidx.annotation.Nullable; |
| 22 | import androidx.annotation.VisibleForTesting; |
| 23 | |
| 24 | import java.util.ArrayList; |
| 25 | import java.util.Arrays; |
| 26 | import java.util.Collections; |
| 27 | import java.util.Comparator; |
| 28 | import java.util.List; |
| 29 | |
| 30 | /** |
| 31 | * DiffUtil is a utility class that calculates the difference between two lists and outputs a |
| 32 | * list of update operations that converts the first list into the second one. |
| 33 | * <p> |
| 34 | * It can be used to calculate updates for a RecyclerView Adapter. See {@link ListAdapter} and |
| 35 | * {@link AsyncListDiffer} which can simplify the use of DiffUtil on a background thread. |
| 36 | * <p> |
| 37 | * DiffUtil uses Eugene W. Myers's difference algorithm to calculate the minimal number of updates |
| 38 | * to convert one list into another. Myers's algorithm does not handle items that are moved so |
| 39 | * DiffUtil runs a second pass on the result to detect items that were moved. |
| 40 | * <p> |
| 41 | * Note that DiffUtil, ListAdapter, and AsyncListDiffer require the list to not mutate while in use. |
| 42 | * This generally means that both the lists themselves and their elements (or at least, the |
| 43 | * properties of elements used in diffing) should not be modified directly. Instead, new lists |
| 44 | * should be provided any time content changes. It's common for lists passed to DiffUtil to share |
| 45 | * elements that have not mutated, so it is not strictly required to reload all data to use |
| 46 | * DiffUtil. |
| 47 | * <p> |
| 48 | * If the lists are large, this operation may take significant time so you are advised to run this |
| 49 | * on a background thread, get the {@link DiffResult} then apply it on the RecyclerView on the main |
| 50 | * thread. |
| 51 | * <p> |
| 52 | * This algorithm is optimized for space and uses O(N) space to find the minimal |
| 53 | * number of addition and removal operations between the two lists. It has O(N + D^2) expected time |
| 54 | * performance where D is the length of the edit script. |
| 55 | * <p> |
| 56 | * If move detection is enabled, it takes an additional O(N^2) time where N is the total number of |
| 57 | * added and removed items. If your lists are already sorted by the same constraint (e.g. a created |
| 58 | * timestamp for a list of posts), you can disable move detection to improve performance. |
| 59 | * <p> |
| 60 | * The actual runtime of the algorithm significantly depends on the number of changes in the list |
| 61 | * and the cost of your comparison methods. Below are some average run times for reference: |
| 62 | * (The test list is composed of random UUID Strings and the tests are run on Nexus 5X with M) |
| 63 | * <ul> |
| 64 | * <li>100 items and 10 modifications: avg: 0.39 ms, median: 0.35 ms |
| 65 | * <li>100 items and 100 modifications: 3.82 ms, median: 3.75 ms |
| 66 | * <li>100 items and 100 modifications without moves: 2.09 ms, median: 2.06 ms |
| 67 | * <li>1000 items and 50 modifications: avg: 4.67 ms, median: 4.59 ms |
| 68 | * <li>1000 items and 50 modifications without moves: avg: 3.59 ms, median: 3.50 ms |
| 69 | * <li>1000 items and 200 modifications: 27.07 ms, median: 26.92 ms |
| 70 | * <li>1000 items and 200 modifications without moves: 13.54 ms, median: 13.36 ms |
| 71 | * </ul> |
| 72 | * <p> |
| 73 | * Due to implementation constraints, the max size of the list can be 2^26. |
| 74 | * |
| 75 | * @see ListAdapter |
| 76 | * @see AsyncListDiffer |
| 77 | */ |
| 78 | public class DiffUtil { |
| 79 | |
| 80 | private DiffUtil() { |
| 81 | // utility class, no instance. |
| 82 | } |
| 83 | |
| 84 | private static final Comparator<Snake> SNAKE_COMPARATOR = new Comparator<Snake>() { |
| 85 | @Override |
| 86 | public int compare(Snake o1, Snake o2) { |
| 87 | int cmpX = o1.x - o2.x; |
| 88 | return cmpX == 0 ? o1.y - o2.y : cmpX; |
| 89 | } |
| 90 | }; |
| 91 | |
| 92 | // Myers' algorithm uses two lists as axis labels. In DiffUtil's implementation, `x` axis is |
| 93 | // used for old list and `y` axis is used for new list. |
| 94 | |
| 95 | /** |
| 96 | * Calculates the list of update operations that can covert one list into the other one. |
| 97 | * |
| 98 | * @param cb The callback that acts as a gateway to the backing list data |
| 99 | * |
| 100 | * @return A DiffResult that contains the information about the edit sequence to convert the |
| 101 | * old list into the new list. |
| 102 | */ |
| 103 | @NonNull |
| 104 | public static DiffResult calculateDiff(@NonNull Callback cb) { |
| 105 | return calculateDiff(cb, true); |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * Calculates the list of update operations that can covert one list into the other one. |
| 110 | * <p> |
| 111 | * If your old and new lists are sorted by the same constraint and items never move (swap |
| 112 | * positions), you can disable move detection which takes <code>O(N^2)</code> time where |
| 113 | * N is the number of added, moved, removed items. |
| 114 | * |
| 115 | * @param cb The callback that acts as a gateway to the backing list data |
| 116 | * @param detectMoves True if DiffUtil should try to detect moved items, false otherwise. |
| 117 | * |
| 118 | * @return A DiffResult that contains the information about the edit sequence to convert the |
| 119 | * old list into the new list. |
| 120 | */ |
| 121 | @NonNull |
| 122 | public static DiffResult calculateDiff(@NonNull Callback cb, boolean detectMoves) { |
| 123 | final int oldSize = cb.getOldListSize(); |
| 124 | final int newSize = cb.getNewListSize(); |
| 125 | |
| 126 | final List<Snake> snakes = new ArrayList<>(); |
| 127 | |
| 128 | // instead of a recursive implementation, we keep our own stack to avoid potential stack |
| 129 | // overflow exceptions |
| 130 | final List<Range> stack = new ArrayList<>(); |
| 131 | |
| 132 | stack.add(new Range(0, oldSize, 0, newSize)); |
| 133 | |
| 134 | final int max = oldSize + newSize + Math.abs(oldSize - newSize); |
| 135 | // allocate forward and backward k-lines. K lines are diagonal lines in the matrix. (see the |
| 136 | // paper for details) |
| 137 | // These arrays lines keep the max reachable position for each k-line. |
| 138 | final int[] forward = new int[max * 2]; |
| 139 | final int[] backward = new int[max * 2]; |
| 140 | |
| 141 | // We pool the ranges to avoid allocations for each recursive call. |
| 142 | final List<Range> rangePool = new ArrayList<>(); |
| 143 | while (!stack.isEmpty()) { |
| 144 | final Range range = stack.remove(stack.size() - 1); |
| 145 | final Snake snake = diffPartial(cb, range.oldListStart, range.oldListEnd, |
| 146 | range.newListStart, range.newListEnd, forward, backward, max); |
| 147 | if (snake != null) { |
| 148 | if (snake.size > 0) { |
| 149 | snakes.add(snake); |
| 150 | } |
| 151 | // offset the snake to convert its coordinates from the Range's area to global |
| 152 | snake.x += range.oldListStart; |
| 153 | snake.y += range.newListStart; |
| 154 | |
| 155 | // add new ranges for left and right |
| 156 | final Range left = rangePool.isEmpty() ? new Range() : rangePool.remove( |
| 157 | rangePool.size() - 1); |
| 158 | left.oldListStart = range.oldListStart; |
| 159 | left.newListStart = range.newListStart; |
| 160 | if (snake.reverse) { |
| 161 | left.oldListEnd = snake.x; |
| 162 | left.newListEnd = snake.y; |
| 163 | } else { |
| 164 | if (snake.removal) { |
| 165 | left.oldListEnd = snake.x - 1; |
| 166 | left.newListEnd = snake.y; |
| 167 | } else { |
| 168 | left.oldListEnd = snake.x; |
| 169 | left.newListEnd = snake.y - 1; |
| 170 | } |
| 171 | } |
| 172 | stack.add(left); |
| 173 | |
| 174 | // re-use range for right |
| 175 | //noinspection UnnecessaryLocalVariable |
| 176 | final Range right = range; |
| 177 | if (snake.reverse) { |
| 178 | if (snake.removal) { |
| 179 | right.oldListStart = snake.x + snake.size + 1; |
| 180 | right.newListStart = snake.y + snake.size; |
| 181 | } else { |
| 182 | right.oldListStart = snake.x + snake.size; |
| 183 | right.newListStart = snake.y + snake.size + 1; |
| 184 | } |
| 185 | } else { |
| 186 | right.oldListStart = snake.x + snake.size; |
| 187 | right.newListStart = snake.y + snake.size; |
| 188 | } |
| 189 | stack.add(right); |
| 190 | } else { |
| 191 | rangePool.add(range); |
| 192 | } |
| 193 | |
| 194 | } |
| 195 | // sort snakes |
| 196 | Collections.sort(snakes, SNAKE_COMPARATOR); |
| 197 | |
| 198 | return new DiffResult(cb, snakes, forward, backward, detectMoves); |
| 199 | |
| 200 | } |
| 201 | |
| 202 | private static Snake diffPartial(Callback cb, int startOld, int endOld, |
| 203 | int startNew, int endNew, int[] forward, int[] backward, int kOffset) { |
| 204 | final int oldSize = endOld - startOld; |
| 205 | final int newSize = endNew - startNew; |
| 206 | |
| 207 | if (endOld - startOld < 1 || endNew - startNew < 1) { |
| 208 | return null; |
| 209 | } |
| 210 | |
| 211 | final int delta = oldSize - newSize; |
| 212 | final int dLimit = (oldSize + newSize + 1) / 2; |
| 213 | Arrays.fill(forward, kOffset - dLimit - 1, kOffset + dLimit + 1, 0); |
| 214 | Arrays.fill(backward, kOffset - dLimit - 1 + delta, kOffset + dLimit + 1 + delta, oldSize); |
| 215 | final boolean checkInFwd = delta % 2 != 0; |
| 216 | for (int d = 0; d <= dLimit; d++) { |
| 217 | for (int k = -d; k <= d; k += 2) { |
| 218 | // find forward path |
| 219 | // we can reach k from k - 1 or k + 1. Check which one is further in the graph |
| 220 | int x; |
| 221 | final boolean removal; |
| 222 | if (k == -d || (k != d && forward[kOffset + k - 1] < forward[kOffset + k + 1])) { |
| 223 | x = forward[kOffset + k + 1]; |
| 224 | removal = false; |
| 225 | } else { |
| 226 | x = forward[kOffset + k - 1] + 1; |
| 227 | removal = true; |
| 228 | } |
| 229 | // set y based on x |
| 230 | int y = x - k; |
| 231 | // move diagonal as long as items match |
| 232 | while (x < oldSize && y < newSize |
| 233 | && cb.areItemsTheSame(startOld + x, startNew + y)) { |
| 234 | x++; |
| 235 | y++; |
| 236 | } |
| 237 | forward[kOffset + k] = x; |
| 238 | if (checkInFwd && k >= delta - d + 1 && k <= delta + d - 1) { |
| 239 | if (forward[kOffset + k] >= backward[kOffset + k]) { |
| 240 | Snake outSnake = new Snake(); |
| 241 | outSnake.x = backward[kOffset + k]; |
| 242 | outSnake.y = outSnake.x - k; |
| 243 | outSnake.size = forward[kOffset + k] - backward[kOffset + k]; |
| 244 | outSnake.removal = removal; |
| 245 | outSnake.reverse = false; |
| 246 | return outSnake; |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | for (int k = -d; k <= d; k += 2) { |
| 251 | // find reverse path at k + delta, in reverse |
| 252 | final int backwardK = k + delta; |
| 253 | int x; |
| 254 | final boolean removal; |
| 255 | if (backwardK == d + delta || (backwardK != -d + delta |
| 256 | && backward[kOffset + backwardK - 1] < backward[kOffset + backwardK + 1])) { |
| 257 | x = backward[kOffset + backwardK - 1]; |
| 258 | removal = false; |
| 259 | } else { |
| 260 | x = backward[kOffset + backwardK + 1] - 1; |
| 261 | removal = true; |
| 262 | } |
| 263 | |
| 264 | // set y based on x |
| 265 | int y = x - backwardK; |
| 266 | // move diagonal as long as items match |
| 267 | while (x > 0 && y > 0 |
| 268 | && cb.areItemsTheSame(startOld + x - 1, startNew + y - 1)) { |
| 269 | x--; |
| 270 | y--; |
| 271 | } |
| 272 | backward[kOffset + backwardK] = x; |
| 273 | if (!checkInFwd && k + delta >= -d && k + delta <= d) { |
| 274 | if (forward[kOffset + backwardK] >= backward[kOffset + backwardK]) { |
| 275 | Snake outSnake = new Snake(); |
| 276 | outSnake.x = backward[kOffset + backwardK]; |
| 277 | outSnake.y = outSnake.x - backwardK; |
| 278 | outSnake.size = |
| 279 | forward[kOffset + backwardK] - backward[kOffset + backwardK]; |
| 280 | outSnake.removal = removal; |
| 281 | outSnake.reverse = true; |
| 282 | return outSnake; |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | throw new IllegalStateException("DiffUtil hit an unexpected case while trying to calculate" |
| 288 | + " the optimal path. Please make sure your data is not changing during the" |
| 289 | + " diff calculation."); |
| 290 | } |
| 291 | |
| 292 | /** |
| 293 | * A Callback class used by DiffUtil while calculating the diff between two lists. |
| 294 | */ |
| 295 | public abstract static class Callback { |
| 296 | /** |
| 297 | * Returns the size of the old list. |
| 298 | * |
| 299 | * @return The size of the old list. |
| 300 | */ |
| 301 | public abstract int getOldListSize(); |
| 302 | |
| 303 | /** |
| 304 | * Returns the size of the new list. |
| 305 | * |
| 306 | * @return The size of the new list. |
| 307 | */ |
| 308 | public abstract int getNewListSize(); |
| 309 | |
| 310 | /** |
| 311 | * Called by the DiffUtil to decide whether two object represent the same Item. |
| 312 | * <p> |
| 313 | * For example, if your items have unique ids, this method should check their id equality. |
| 314 | * |
| 315 | * @param oldItemPosition The position of the item in the old list |
| 316 | * @param newItemPosition The position of the item in the new list |
| 317 | * @return True if the two items represent the same object or false if they are different. |
| 318 | */ |
| 319 | public abstract boolean areItemsTheSame(int oldItemPosition, int newItemPosition); |
| 320 | |
| 321 | /** |
| 322 | * Called by the DiffUtil when it wants to check whether two items have the same data. |
| 323 | * DiffUtil uses this information to detect if the contents of an item has changed. |
| 324 | * <p> |
| 325 | * DiffUtil uses this method to check equality instead of {@link Object#equals(Object)} |
| 326 | * so that you can change its behavior depending on your UI. |
| 327 | * For example, if you are using DiffUtil with a |
| 328 | * {@link RecyclerView.Adapter RecyclerView.Adapter}, you should |
| 329 | * return whether the items' visual representations are the same. |
| 330 | * <p> |
| 331 | * This method is called only if {@link #areItemsTheSame(int, int)} returns |
| 332 | * {@code true} for these items. |
| 333 | * |
| 334 | * @param oldItemPosition The position of the item in the old list |
| 335 | * @param newItemPosition The position of the item in the new list which replaces the |
| 336 | * oldItem |
| 337 | * @return True if the contents of the items are the same or false if they are different. |
| 338 | */ |
| 339 | public abstract boolean areContentsTheSame(int oldItemPosition, int newItemPosition); |
| 340 | |
| 341 | /** |
| 342 | * When {@link #areItemsTheSame(int, int)} returns {@code true} for two items and |
| 343 | * {@link #areContentsTheSame(int, int)} returns false for them, DiffUtil |
| 344 | * calls this method to get a payload about the change. |
| 345 | * <p> |
| 346 | * For example, if you are using DiffUtil with {@link RecyclerView}, you can return the |
| 347 | * particular field that changed in the item and your |
| 348 | * {@link RecyclerView.ItemAnimator ItemAnimator} can use that |
| 349 | * information to run the correct animation. |
| 350 | * <p> |
| 351 | * Default implementation returns {@code null}. |
| 352 | * |
| 353 | * @param oldItemPosition The position of the item in the old list |
| 354 | * @param newItemPosition The position of the item in the new list |
| 355 | * |
| 356 | * @return A payload object that represents the change between the two items. |
| 357 | */ |
| 358 | @Nullable |
| 359 | public Object getChangePayload(int oldItemPosition, int newItemPosition) { |
| 360 | return null; |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * Callback for calculating the diff between two non-null items in a list. |
| 366 | * <p> |
| 367 | * {@link Callback} serves two roles - list indexing, and item diffing. ItemCallback handles |
| 368 | * just the second of these, which allows separation of code that indexes into an array or List |
| 369 | * from the presentation-layer and content specific diffing code. |
| 370 | * |
| 371 | * @param <T> Type of items to compare. |
| 372 | */ |
| 373 | public abstract static class ItemCallback<T> { |
| 374 | /** |
| 375 | * Called to check whether two objects represent the same item. |
| 376 | * <p> |
| 377 | * For example, if your items have unique ids, this method should check their id equality. |
| 378 | * <p> |
| 379 | * Note: {@code null} items in the list are assumed to be the same as another {@code null} |
| 380 | * item and are assumed to not be the same as a non-{@code null} item. This callback will |
| 381 | * not be invoked for either of those cases. |
| 382 | * |
| 383 | * @param oldItem The item in the old list. |
| 384 | * @param newItem The item in the new list. |
| 385 | * @return True if the two items represent the same object or false if they are different. |
| 386 | * |
| 387 | * @see Callback#areItemsTheSame(int, int) |
| 388 | */ |
| 389 | public abstract boolean areItemsTheSame(@NonNull T oldItem, @NonNull T newItem); |
| 390 | |
| 391 | /** |
| 392 | * Called to check whether two items have the same data. |
| 393 | * <p> |
| 394 | * This information is used to detect if the contents of an item have changed. |
| 395 | * <p> |
| 396 | * This method to check equality instead of {@link Object#equals(Object)} so that you can |
| 397 | * change its behavior depending on your UI. |
| 398 | * <p> |
| 399 | * For example, if you are using DiffUtil with a |
| 400 | * {@link RecyclerView.Adapter RecyclerView.Adapter}, you should |
| 401 | * return whether the items' visual representations are the same. |
| 402 | * <p> |
| 403 | * This method is called only if {@link #areItemsTheSame(T, T)} returns {@code true} for |
| 404 | * these items. |
| 405 | * <p> |
| 406 | * Note: Two {@code null} items are assumed to represent the same contents. This callback |
| 407 | * will not be invoked for this case. |
| 408 | * |
| 409 | * @param oldItem The item in the old list. |
| 410 | * @param newItem The item in the new list. |
| 411 | * @return True if the contents of the items are the same or false if they are different. |
| 412 | * |
| 413 | * @see Callback#areContentsTheSame(int, int) |
| 414 | */ |
| 415 | public abstract boolean areContentsTheSame(@NonNull T oldItem, @NonNull T newItem); |
| 416 | |
| 417 | /** |
| 418 | * When {@link #areItemsTheSame(T, T)} returns {@code true} for two items and |
| 419 | * {@link #areContentsTheSame(T, T)} returns false for them, this method is called to |
| 420 | * get a payload about the change. |
| 421 | * <p> |
| 422 | * For example, if you are using DiffUtil with {@link RecyclerView}, you can return the |
| 423 | * particular field that changed in the item and your |
| 424 | * {@link RecyclerView.ItemAnimator ItemAnimator} can use that |
| 425 | * information to run the correct animation. |
| 426 | * <p> |
| 427 | * Default implementation returns {@code null}. |
| 428 | * |
| 429 | * @see Callback#getChangePayload(int, int) |
| 430 | */ |
| 431 | @SuppressWarnings({"WeakerAccess", "unused"}) |
| 432 | @Nullable |
| 433 | public Object getChangePayload(@NonNull T oldItem, @NonNull T newItem) { |
| 434 | return null; |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | /** |
| 439 | * Snakes represent a match between two lists. It is optionally prefixed or postfixed with an |
| 440 | * add or remove operation. See the Myers' paper for details. |
| 441 | */ |
| 442 | static class Snake { |
| 443 | /** |
| 444 | * Position in the old list |
| 445 | */ |
| 446 | int x; |
| 447 | |
| 448 | /** |
| 449 | * Position in the new list |
| 450 | */ |
| 451 | int y; |
| 452 | |
| 453 | /** |
| 454 | * Number of matches. Might be 0. |
| 455 | */ |
| 456 | int size; |
| 457 | |
| 458 | /** |
| 459 | * If true, this is a removal from the original list followed by {@code size} matches. |
| 460 | * If false, this is an addition from the new list followed by {@code size} matches. |
| 461 | */ |
| 462 | boolean removal; |
| 463 | |
| 464 | /** |
| 465 | * If true, the addition or removal is at the end of the snake. |
| 466 | * If false, the addition or removal is at the beginning of the snake. |
| 467 | */ |
| 468 | boolean reverse; |
| 469 | } |
| 470 | |
| 471 | /** |
| 472 | * Represents a range in two lists that needs to be solved. |
| 473 | * <p> |
| 474 | * This internal class is used when running Myers' algorithm without recursion. |
| 475 | */ |
| 476 | static class Range { |
| 477 | |
| 478 | int oldListStart, oldListEnd; |
| 479 | |
| 480 | int newListStart, newListEnd; |
| 481 | |
| 482 | public Range() { |
| 483 | } |
| 484 | |
| 485 | public Range(int oldListStart, int oldListEnd, int newListStart, int newListEnd) { |
| 486 | this.oldListStart = oldListStart; |
| 487 | this.oldListEnd = oldListEnd; |
| 488 | this.newListStart = newListStart; |
| 489 | this.newListEnd = newListEnd; |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | /** |
| 494 | * This class holds the information about the result of a |
| 495 | * {@link DiffUtil#calculateDiff(Callback, boolean)} call. |
| 496 | * <p> |
| 497 | * You can consume the updates in a DiffResult via |
| 498 | * {@link #dispatchUpdatesTo(ListUpdateCallback)} or directly stream the results into a |
| 499 | * {@link RecyclerView.Adapter} via {@link #dispatchUpdatesTo(RecyclerView.Adapter)}. |
| 500 | */ |
| 501 | public static class DiffResult { |
| 502 | /** |
| 503 | * Signifies an item not present in the list. |
| 504 | */ |
| 505 | public static final int NO_POSITION = -1; |
| 506 | |
| 507 | |
| 508 | /** |
| 509 | * While reading the flags below, keep in mind that when multiple items move in a list, |
| 510 | * Myers's may pick any of them as the anchor item and consider that one NOT_CHANGED while |
| 511 | * picking others as additions and removals. This is completely fine as we later detect |
| 512 | * all moves. |
| 513 | * <p> |
| 514 | * Below, when an item is mentioned to stay in the same "location", it means we won't |
| 515 | * dispatch a move/add/remove for it, it DOES NOT mean the item is still in the same |
| 516 | * position. |
| 517 | */ |
| 518 | // item stayed the same. |
| 519 | private static final int FLAG_NOT_CHANGED = 1; |
| 520 | // item stayed in the same location but changed. |
| 521 | private static final int FLAG_CHANGED = FLAG_NOT_CHANGED << 1; |
| 522 | // Item has moved and also changed. |
| 523 | private static final int FLAG_MOVED_CHANGED = FLAG_CHANGED << 1; |
| 524 | // Item has moved but did not change. |
| 525 | private static final int FLAG_MOVED_NOT_CHANGED = FLAG_MOVED_CHANGED << 1; |
| 526 | // Ignore this update. |
| 527 | // If this is an addition from the new list, it means the item is actually removed from an |
| 528 | // earlier position and its move will be dispatched when we process the matching removal |
| 529 | // from the old list. |
| 530 | // If this is a removal from the old list, it means the item is actually added back to an |
| 531 | // earlier index in the new list and we'll dispatch its move when we are processing that |
| 532 | // addition. |
| 533 | private static final int FLAG_IGNORE = FLAG_MOVED_NOT_CHANGED << 1; |
| 534 | |
| 535 | // since we are re-using the int arrays that were created in the Myers' step, we mask |
| 536 | // change flags |
| 537 | private static final int FLAG_OFFSET = 5; |
| 538 | |
| 539 | private static final int FLAG_MASK = (1 << FLAG_OFFSET) - 1; |
| 540 | |
| 541 | // The Myers' snakes. At this point, we only care about their diagonal sections. |
| 542 | private final List<Snake> mSnakes; |
| 543 | |
| 544 | // The list to keep oldItemStatuses. As we traverse old items, we assign flags to them |
| 545 | // which also includes whether they were a real removal or a move (and its new index). |
| 546 | private final int[] mOldItemStatuses; |
| 547 | // The list to keep newItemStatuses. As we traverse new items, we assign flags to them |
| 548 | // which also includes whether they were a real addition or a move(and its old index). |
| 549 | private final int[] mNewItemStatuses; |
| 550 | // The callback that was given to calcualte diff method. |
| 551 | private final Callback mCallback; |
| 552 | |
| 553 | private final int mOldListSize; |
| 554 | |
| 555 | private final int mNewListSize; |
| 556 | |
| 557 | private final boolean mDetectMoves; |
| 558 | |
| 559 | /** |
| 560 | * @param callback The callback that was used to calculate the diff |
| 561 | * @param snakes The list of Myers' snakes |
| 562 | * @param oldItemStatuses An int[] that can be re-purposed to keep metadata |
| 563 | * @param newItemStatuses An int[] that can be re-purposed to keep metadata |
| 564 | * @param detectMoves True if this DiffResult will try to detect moved items |
| 565 | */ |
| 566 | DiffResult(Callback callback, List<Snake> snakes, int[] oldItemStatuses, |
| 567 | int[] newItemStatuses, boolean detectMoves) { |
| 568 | mSnakes = snakes; |
| 569 | mOldItemStatuses = oldItemStatuses; |
| 570 | mNewItemStatuses = newItemStatuses; |
| 571 | Arrays.fill(mOldItemStatuses, 0); |
| 572 | Arrays.fill(mNewItemStatuses, 0); |
| 573 | mCallback = callback; |
| 574 | mOldListSize = callback.getOldListSize(); |
| 575 | mNewListSize = callback.getNewListSize(); |
| 576 | mDetectMoves = detectMoves; |
| 577 | addRootSnake(); |
| 578 | findMatchingItems(); |
| 579 | } |
| 580 | |
| 581 | /** |
| 582 | * We always add a Snake to 0/0 so that we can run loops from end to beginning and be done |
| 583 | * when we run out of snakes. |
| 584 | */ |
| 585 | private void addRootSnake() { |
| 586 | Snake firstSnake = mSnakes.isEmpty() ? null : mSnakes.get(0); |
| 587 | if (firstSnake == null || firstSnake.x != 0 || firstSnake.y != 0) { |
| 588 | Snake root = new Snake(); |
| 589 | root.x = 0; |
| 590 | root.y = 0; |
| 591 | root.removal = false; |
| 592 | root.size = 0; |
| 593 | root.reverse = false; |
| 594 | mSnakes.add(0, root); |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | /** |
| 599 | * This method traverses each addition / removal and tries to match it to a previous |
| 600 | * removal / addition. This is how we detect move operations. |
| 601 | * <p> |
| 602 | * This class also flags whether an item has been changed or not. |
| 603 | * <p> |
| 604 | * DiffUtil does this pre-processing so that if it is running on a big list, it can be moved |
| 605 | * to background thread where most of the expensive stuff will be calculated and kept in |
| 606 | * the statuses maps. DiffResult uses this pre-calculated information while dispatching |
| 607 | * the updates (which is probably being called on the main thread). |
| 608 | */ |
| 609 | private void findMatchingItems() { |
| 610 | int posOld = mOldListSize; |
| 611 | int posNew = mNewListSize; |
| 612 | // traverse the matrix from right bottom to 0,0. |
| 613 | for (int i = mSnakes.size() - 1; i >= 0; i--) { |
| 614 | final Snake snake = mSnakes.get(i); |
| 615 | final int endX = snake.x + snake.size; |
| 616 | final int endY = snake.y + snake.size; |
| 617 | if (mDetectMoves) { |
| 618 | while (posOld > endX) { |
| 619 | // this is a removal. Check remaining snakes to see if this was added before |
| 620 | findAddition(posOld, posNew, i); |
| 621 | posOld--; |
| 622 | } |
| 623 | while (posNew > endY) { |
| 624 | // this is an addition. Check remaining snakes to see if this was removed |
| 625 | // before |
| 626 | findRemoval(posOld, posNew, i); |
| 627 | posNew--; |
| 628 | } |
| 629 | } |
| 630 | for (int j = 0; j < snake.size; j++) { |
| 631 | // matching items. Check if it is changed or not |
| 632 | final int oldItemPos = snake.x + j; |
| 633 | final int newItemPos = snake.y + j; |
| 634 | final boolean theSame = mCallback |
| 635 | .areContentsTheSame(oldItemPos, newItemPos); |
| 636 | final int changeFlag = theSame ? FLAG_NOT_CHANGED : FLAG_CHANGED; |
| 637 | mOldItemStatuses[oldItemPos] = (newItemPos << FLAG_OFFSET) | changeFlag; |
| 638 | mNewItemStatuses[newItemPos] = (oldItemPos << FLAG_OFFSET) | changeFlag; |
| 639 | } |
| 640 | posOld = snake.x; |
| 641 | posNew = snake.y; |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | private void findAddition(int x, int y, int snakeIndex) { |
| 646 | if (mOldItemStatuses[x - 1] != 0) { |
| 647 | return; // already set by a latter item |
| 648 | } |
| 649 | findMatchingItem(x, y, snakeIndex, false); |
| 650 | } |
| 651 | |
| 652 | private void findRemoval(int x, int y, int snakeIndex) { |
| 653 | if (mNewItemStatuses[y - 1] != 0) { |
| 654 | return; // already set by a latter item |
| 655 | } |
| 656 | findMatchingItem(x, y, snakeIndex, true); |
| 657 | } |
| 658 | |
| 659 | /** |
| 660 | * Given a position in the old list, returns the position in the new list, or |
| 661 | * {@code NO_POSITION} if it was removed. |
| 662 | * |
| 663 | * @param oldListPosition Position of item in old list |
| 664 | * |
| 665 | * @return Position of item in new list, or {@code NO_POSITION} if not present. |
| 666 | * |
| 667 | * @see #NO_POSITION |
| 668 | * @see #convertNewPositionToOld(int) |
| 669 | */ |
| 670 | public int convertOldPositionToNew(@IntRange(from = 0) int oldListPosition) { |
| 671 | if (oldListPosition < 0 || oldListPosition >= mOldListSize) { |
| 672 | throw new IndexOutOfBoundsException("Index out of bounds - passed position = " |
| 673 | + oldListPosition + ", old list size = " + mOldListSize); |
| 674 | } |
| 675 | final int status = mOldItemStatuses[oldListPosition]; |
| 676 | if ((status & FLAG_MASK) == 0) { |
| 677 | return NO_POSITION; |
| 678 | } else { |
| 679 | return status >> FLAG_OFFSET; |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | /** |
| 684 | * Given a position in the new list, returns the position in the old list, or |
| 685 | * {@code NO_POSITION} if it was removed. |
| 686 | * |
| 687 | * @param newListPosition Position of item in new list |
| 688 | * |
| 689 | * @return Position of item in old list, or {@code NO_POSITION} if not present. |
| 690 | * |
| 691 | * @see #NO_POSITION |
| 692 | * @see #convertOldPositionToNew(int) |
| 693 | */ |
| 694 | public int convertNewPositionToOld(@IntRange(from = 0) int newListPosition) { |
| 695 | if (newListPosition < 0 || newListPosition >= mNewListSize) { |
| 696 | throw new IndexOutOfBoundsException("Index out of bounds - passed position = " |
| 697 | + newListPosition + ", new list size = " + mNewListSize); |
| 698 | } |
| 699 | final int status = mNewItemStatuses[newListPosition]; |
| 700 | if ((status & FLAG_MASK) == 0) { |
| 701 | return NO_POSITION; |
| 702 | } else { |
| 703 | return status >> FLAG_OFFSET; |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | /** |
| 708 | * Finds a matching item that is before the given coordinates in the matrix |
| 709 | * (before : left and above). |
| 710 | * |
| 711 | * @param x The x position in the matrix (position in the old list) |
| 712 | * @param y The y position in the matrix (position in the new list) |
| 713 | * @param snakeIndex The current snake index |
| 714 | * @param removal True if we are looking for a removal, false otherwise |
| 715 | * |
| 716 | * @return True if such item is found. |
| 717 | */ |
| 718 | private boolean findMatchingItem(final int x, final int y, final int snakeIndex, |
| 719 | final boolean removal) { |
| 720 | final int myItemPos; |
| 721 | int curX; |
| 722 | int curY; |
| 723 | if (removal) { |
| 724 | myItemPos = y - 1; |
| 725 | curX = x; |
| 726 | curY = y - 1; |
| 727 | } else { |
| 728 | myItemPos = x - 1; |
| 729 | curX = x - 1; |
| 730 | curY = y; |
| 731 | } |
| 732 | for (int i = snakeIndex; i >= 0; i--) { |
| 733 | final Snake snake = mSnakes.get(i); |
| 734 | final int endX = snake.x + snake.size; |
| 735 | final int endY = snake.y + snake.size; |
| 736 | if (removal) { |
| 737 | // check removals for a match |
| 738 | for (int pos = curX - 1; pos >= endX; pos--) { |
| 739 | if (mCallback.areItemsTheSame(pos, myItemPos)) { |
| 740 | // found! |
| 741 | final boolean theSame = mCallback.areContentsTheSame(pos, myItemPos); |
| 742 | final int changeFlag = theSame ? FLAG_MOVED_NOT_CHANGED |
| 743 | : FLAG_MOVED_CHANGED; |
| 744 | mNewItemStatuses[myItemPos] = (pos << FLAG_OFFSET) | FLAG_IGNORE; |
| 745 | mOldItemStatuses[pos] = (myItemPos << FLAG_OFFSET) | changeFlag; |
| 746 | return true; |
| 747 | } |
| 748 | } |
| 749 | } else { |
| 750 | // check for additions for a match |
| 751 | for (int pos = curY - 1; pos >= endY; pos--) { |
| 752 | if (mCallback.areItemsTheSame(myItemPos, pos)) { |
| 753 | // found |
| 754 | final boolean theSame = mCallback.areContentsTheSame(myItemPos, pos); |
| 755 | final int changeFlag = theSame ? FLAG_MOVED_NOT_CHANGED |
| 756 | : FLAG_MOVED_CHANGED; |
| 757 | mOldItemStatuses[x - 1] = (pos << FLAG_OFFSET) | FLAG_IGNORE; |
| 758 | mNewItemStatuses[pos] = ((x - 1) << FLAG_OFFSET) | changeFlag; |
| 759 | return true; |
| 760 | } |
| 761 | } |
| 762 | } |
| 763 | curX = snake.x; |
| 764 | curY = snake.y; |
| 765 | } |
| 766 | return false; |
| 767 | } |
| 768 | |
| 769 | /** |
| 770 | * Dispatches the update events to the given adapter. |
| 771 | * <p> |
| 772 | * For example, if you have an {@link RecyclerView.Adapter Adapter} |
| 773 | * that is backed by a {@link List}, you can swap the list with the new one then call this |
| 774 | * method to dispatch all updates to the RecyclerView. |
| 775 | * <pre> |
| 776 | * List oldList = mAdapter.getData(); |
| 777 | * DiffResult result = DiffUtil.calculateDiff(new MyCallback(oldList, newList)); |
| 778 | * mAdapter.setData(newList); |
| 779 | * result.dispatchUpdatesTo(mAdapter); |
| 780 | * </pre> |
| 781 | * <p> |
| 782 | * Note that the RecyclerView requires you to dispatch adapter updates immediately when you |
| 783 | * change the data (you cannot defer {@code notify*} calls). The usage above adheres to this |
| 784 | * rule because updates are sent to the adapter right after the backing data is changed, |
| 785 | * before RecyclerView tries to read it. |
| 786 | * <p> |
| 787 | * On the other hand, if you have another |
| 788 | * {@link RecyclerView.AdapterDataObserver AdapterDataObserver} |
| 789 | * that tries to process events synchronously, this may confuse that observer because the |
| 790 | * list is instantly moved to its final state while the adapter updates are dispatched later |
| 791 | * on, one by one. If you have such an |
| 792 | * {@link RecyclerView.AdapterDataObserver AdapterDataObserver}, |
| 793 | * you can use |
| 794 | * {@link #dispatchUpdatesTo(ListUpdateCallback)} to handle each modification |
| 795 | * manually. |
| 796 | * |
| 797 | * @param adapter A RecyclerView adapter which was displaying the old list and will start |
| 798 | * displaying the new list. |
| 799 | * @see AdapterListUpdateCallback |
| 800 | */ |
| 801 | public void dispatchUpdatesTo(@NonNull final RecyclerView.Adapter adapter) { |
| 802 | dispatchUpdatesTo(new AdapterListUpdateCallback(adapter)); |
| 803 | } |
| 804 | |
| 805 | /** |
| 806 | * Dispatches update operations to the given Callback. |
| 807 | * <p> |
| 808 | * These updates are atomic such that the first update call affects every update call that |
| 809 | * comes after it (the same as RecyclerView). |
| 810 | * |
| 811 | * @param updateCallback The callback to receive the update operations. |
| 812 | * @see #dispatchUpdatesTo(RecyclerView.Adapter) |
| 813 | */ |
| 814 | public void dispatchUpdatesTo(@NonNull ListUpdateCallback updateCallback) { |
| 815 | final BatchingListUpdateCallback batchingCallback; |
| 816 | if (updateCallback instanceof BatchingListUpdateCallback) { |
| 817 | batchingCallback = (BatchingListUpdateCallback) updateCallback; |
| 818 | } else { |
| 819 | batchingCallback = new BatchingListUpdateCallback(updateCallback); |
| 820 | // replace updateCallback with a batching callback and override references to |
| 821 | // updateCallback so that we don't call it directly by mistake |
| 822 | //noinspection UnusedAssignment |
| 823 | updateCallback = batchingCallback; |
| 824 | } |
| 825 | // These are add/remove ops that are converted to moves. We track their positions until |
| 826 | // their respective update operations are processed. |
| 827 | final List<PostponedUpdate> postponedUpdates = new ArrayList<>(); |
| 828 | int posOld = mOldListSize; |
| 829 | int posNew = mNewListSize; |
| 830 | for (int snakeIndex = mSnakes.size() - 1; snakeIndex >= 0; snakeIndex--) { |
| 831 | final Snake snake = mSnakes.get(snakeIndex); |
| 832 | final int snakeSize = snake.size; |
| 833 | final int endX = snake.x + snakeSize; |
| 834 | final int endY = snake.y + snakeSize; |
| 835 | if (endX < posOld) { |
| 836 | dispatchRemovals(postponedUpdates, batchingCallback, endX, posOld - endX, endX); |
| 837 | } |
| 838 | |
| 839 | if (endY < posNew) { |
| 840 | dispatchAdditions(postponedUpdates, batchingCallback, endX, posNew - endY, |
| 841 | endY); |
| 842 | } |
| 843 | for (int i = snakeSize - 1; i >= 0; i--) { |
| 844 | if ((mOldItemStatuses[snake.x + i] & FLAG_MASK) == FLAG_CHANGED) { |
| 845 | batchingCallback.onChanged(snake.x + i, 1, |
| 846 | mCallback.getChangePayload(snake.x + i, snake.y + i)); |
| 847 | } |
| 848 | } |
| 849 | posOld = snake.x; |
| 850 | posNew = snake.y; |
| 851 | } |
| 852 | batchingCallback.dispatchLastEvent(); |
| 853 | } |
| 854 | |
| 855 | private static PostponedUpdate removePostponedUpdate(List<PostponedUpdate> updates, |
| 856 | int pos, boolean removal) { |
| 857 | for (int i = updates.size() - 1; i >= 0; i--) { |
| 858 | final PostponedUpdate update = updates.get(i); |
| 859 | if (update.posInOwnerList == pos && update.removal == removal) { |
| 860 | updates.remove(i); |
| 861 | for (int j = i; j < updates.size(); j++) { |
| 862 | // offset other ops since they swapped positions |
| 863 | updates.get(j).currentPos += removal ? 1 : -1; |
| 864 | } |
| 865 | return update; |
| 866 | } |
| 867 | } |
| 868 | return null; |
| 869 | } |
| 870 | |
| 871 | private void dispatchAdditions(List<PostponedUpdate> postponedUpdates, |
| 872 | ListUpdateCallback updateCallback, int start, int count, int globalIndex) { |
| 873 | if (!mDetectMoves) { |
| 874 | updateCallback.onInserted(start, count); |
| 875 | return; |
| 876 | } |
| 877 | for (int i = count - 1; i >= 0; i--) { |
| 878 | int status = mNewItemStatuses[globalIndex + i] & FLAG_MASK; |
| 879 | switch (status) { |
| 880 | case 0: // real addition |
| 881 | updateCallback.onInserted(start, 1); |
| 882 | for (PostponedUpdate update : postponedUpdates) { |
| 883 | update.currentPos += 1; |
| 884 | } |
| 885 | break; |
| 886 | case FLAG_MOVED_CHANGED: |
| 887 | case FLAG_MOVED_NOT_CHANGED: |
| 888 | final int pos = mNewItemStatuses[globalIndex + i] >> FLAG_OFFSET; |
| 889 | final PostponedUpdate update = removePostponedUpdate(postponedUpdates, pos, |
| 890 | true); |
| 891 | // the item was moved from that position |
| 892 | //noinspection ConstantConditions |
| 893 | updateCallback.onMoved(update.currentPos, start); |
| 894 | if (status == FLAG_MOVED_CHANGED) { |
| 895 | // also dispatch a change |
| 896 | updateCallback.onChanged(start, 1, |
| 897 | mCallback.getChangePayload(pos, globalIndex + i)); |
| 898 | } |
| 899 | break; |
| 900 | case FLAG_IGNORE: // ignoring this |
| 901 | postponedUpdates.add(new PostponedUpdate(globalIndex + i, start, false)); |
| 902 | break; |
| 903 | default: |
| 904 | throw new IllegalStateException( |
| 905 | "unknown flag for pos " + (globalIndex + i) + " " + Long |
| 906 | .toBinaryString(status)); |
| 907 | } |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | private void dispatchRemovals(List<PostponedUpdate> postponedUpdates, |
| 912 | ListUpdateCallback updateCallback, int start, int count, int globalIndex) { |
| 913 | if (!mDetectMoves) { |
| 914 | updateCallback.onRemoved(start, count); |
| 915 | return; |
| 916 | } |
| 917 | for (int i = count - 1; i >= 0; i--) { |
| 918 | final int status = mOldItemStatuses[globalIndex + i] & FLAG_MASK; |
| 919 | switch (status) { |
| 920 | case 0: // real removal |
| 921 | updateCallback.onRemoved(start + i, 1); |
| 922 | for (PostponedUpdate update : postponedUpdates) { |
| 923 | update.currentPos -= 1; |
| 924 | } |
| 925 | break; |
| 926 | case FLAG_MOVED_CHANGED: |
| 927 | case FLAG_MOVED_NOT_CHANGED: |
| 928 | final int pos = mOldItemStatuses[globalIndex + i] >> FLAG_OFFSET; |
| 929 | final PostponedUpdate update = removePostponedUpdate(postponedUpdates, pos, |
| 930 | false); |
| 931 | // the item was moved to that position. we do -1 because this is a move not |
| 932 | // add and removing current item offsets the target move by 1 |
| 933 | //noinspection ConstantConditions |
| 934 | updateCallback.onMoved(start + i, update.currentPos - 1); |
| 935 | if (status == FLAG_MOVED_CHANGED) { |
| 936 | // also dispatch a change |
| 937 | updateCallback.onChanged(update.currentPos - 1, 1, |
| 938 | mCallback.getChangePayload(globalIndex + i, pos)); |
| 939 | } |
| 940 | break; |
| 941 | case FLAG_IGNORE: // ignoring this |
| 942 | postponedUpdates.add(new PostponedUpdate(globalIndex + i, start + i, true)); |
| 943 | break; |
| 944 | default: |
| 945 | throw new IllegalStateException( |
| 946 | "unknown flag for pos " + (globalIndex + i) + " " + Long |
| 947 | .toBinaryString(status)); |
| 948 | } |
| 949 | } |
| 950 | } |
| 951 | |
| 952 | @VisibleForTesting |
| 953 | List<Snake> getSnakes() { |
| 954 | return mSnakes; |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | /** |
| 959 | * Represents an update that we skipped because it was a move. |
| 960 | * <p> |
| 961 | * When an update is skipped, it is tracked as other updates are dispatched until the matching |
| 962 | * add/remove operation is found at which point the tracked position is used to dispatch the |
| 963 | * update. |
| 964 | */ |
| 965 | private static class PostponedUpdate { |
| 966 | |
| 967 | int posInOwnerList; |
| 968 | |
| 969 | int currentPos; |
| 970 | |
| 971 | boolean removal; |
| 972 | |
| 973 | public PostponedUpdate(int posInOwnerList, int currentPos, boolean removal) { |
| 974 | this.posInOwnerList = posInOwnerList; |
| 975 | this.currentPos = currentPos; |
| 976 | this.removal = removal; |
| 977 | } |
| 978 | } |
| 979 | } |
| 980 | |