Update GrResourceCache changeUniqueKey to stay in valid state after each step

The issues are that we are intertwining removing things from the old and new
resource. This changes it so we do all the removal on the old resource first
then start updating the new resource.

Bug: skia:
Change-Id: I7ce4a309290cd499cdc4398c87d1cfd42ef6994d
Reviewed-on: https://skia-review.googlesource.com/44242
Reviewed-by: Brian Salomon <bsalomon@google.com>
Commit-Queue: Greg Daniel <egdaniel@google.com>
diff --git a/src/gpu/GrResourceCache.cpp b/src/gpu/GrResourceCache.cpp
index b781e42..f6170c0 100644
--- a/src/gpu/GrResourceCache.cpp
+++ b/src/gpu/GrResourceCache.cpp
@@ -294,6 +294,16 @@
 
     // If another resource has the new key, remove its key then install the key on this resource.
     if (newKey.isValid()) {
+        if (GrGpuResource* old = fUniqueHash.find(newKey)) {
+            // If the old resource using the key is purgeable and is unreachable, then remove it.
+            if (!old->resourcePriv().getScratchKey().isValid() && old->isPurgeable()) {
+                old->cacheAccess().release();
+            } else {
+                this->removeUniqueKey(old);
+            }
+        }
+        SkASSERT(nullptr == fUniqueHash.find(newKey));
+
         // Remove the entry for this resource if it already has a unique key.
         if (resource->getUniqueKey().isValid()) {
             SkASSERT(resource == fUniqueHash.find(resource->getUniqueKey()));
@@ -307,18 +317,6 @@
             }
         }
 
-        if (GrGpuResource* old = fUniqueHash.find(newKey)) {
-            // If the old resource using the key is purgeable and is unreachable, then remove it.
-            if (!old->resourcePriv().getScratchKey().isValid() && old->isPurgeable()) {
-                // release may call validate() which will assert that resource is in fUniqueHash
-                // if it has a valid key. So in debug reset the key here before we assign it.
-                SkDEBUGCODE(resource->cacheAccess().removeUniqueKey();)
-                old->cacheAccess().release();
-            } else {
-                this->removeUniqueKey(old);
-            }
-        }
-        SkASSERT(nullptr == fUniqueHash.find(newKey));
         resource->cacheAccess().setUniqueKey(newKey);
         fUniqueHash.add(resource);
     } else {