diff Lists.lua @ 96:082ff877c443

Small refactor
author John@Doomsday
date Mon, 23 Apr 2012 09:11:21 -0400
parents 5ade79caeece
children 19fd02bff870
line wrap: on
line diff
--- a/Lists.lua	Sun Apr 22 23:18:35 2012 -0400
+++ b/Lists.lua	Mon Apr 23 09:11:21 2012 -0400
@@ -921,3 +921,69 @@
     return true
 end
 
+
+function CreateChangeDiff(remoteBase,remoteChanges)
+    local t = remoteChanges
+
+    if remoteBase == db.profile.time then
+        local j = 1 -- index in foreign list
+        local n = getn(t)
+        local o = {}
+        for i,v in pairs(db.profile.changes) do -- for each timestamp in our list
+            if t and t[j] < v.time then
+                table.insert(o,v)
+            end
+            while j<n and t[j] <= v.time do j = j+1 end -- advance the foreign pointer past our current entry
+        end -- j>=n ? add because the remote hit end of road. lt? add because it's a missing stamp
+        print("Received request at timebase",remoteBase,"and returning:")
+        PrintTable(o)
+        if getn(o) > 0 then
+            Send("CU",o) -- todo: send privately to the requster
+        end
+        return true, o
+    else
+        return false, {}
+    end
+end
+
+function IntegrateChangeDiff(remoteChanges) -- todo: check against remoteBase before committing to insanity
+    local c = remoteChanges
+    local old = db.profile.changes
+
+    local new = {}
+
+    local op = 1
+    local cp = 1
+
+    local no = getn(old)
+    local nc = getn(c)
+
+    if no == 0 then
+        db.profile.changes = c
+    else
+        while op <= no or cp <= nc do -- lists are pre-sorted. insertion merge them
+            if cp > nc then -- inelegant
+                table.insert(new,old[op])
+                op = op + 1
+            elseif op > no then
+                table.insert(new,c[cp])
+                cp = cp + 1
+            elseif c[cp].time < old[op].time then
+                table.insert(new,c[cp])
+                cp = cp + 1
+            elseif c[cp].time > old[op].time then
+                table.insert(new,old[op])
+                op = op + 1
+            else
+                error("Bad update received from ",sender)
+            end
+        end
+        print("Updating changes - ",getn(new), "entries")
+        db.profile.changes = new
+    end
+
+    CreateWorkingStateFromChanges(db.profile.changes)
+    if changeListener then
+        changeListener:DataEvent()
+    end
+end