# HG changeset patch
# User Kim Alvefur <zash@zash.se>
# Date 1695555714 -7200
# Node ID 9a86e7cbdd79513a21f769acf7adaf10840dec63
# Parent  7c62370dee9abb91c1733ef18c1ebb5e57415be7
mod_storage_internal: Fix fast trimming of archive with exactly one item

This method would previously never delete the first (and only) item
since it works out which item should become the first item after the
trim operation, which doesn't make sense when all should be removed.

This also works as an optimization for when all the last item should be
trimmed, thus items should be removed.

diff -r 7c62370dee9a -r 9a86e7cbdd79 plugins/mod_storage_internal.lua
--- a/plugins/mod_storage_internal.lua	Sat Sep 23 15:48:21 2023 +0200
+++ b/plugins/mod_storage_internal.lua	Sun Sep 24 13:41:54 2023 +0200
@@ -347,6 +347,13 @@
 function archive:trim(username, to_when)
 	local list, err = datamanager.list_open(username, host, self.store);
 	if not list then return list,err;end
+
+	-- shortcut: check if the last item should be trimmed, if so, drop the whole archive
+	local last = list[#list].when or datetime.parse(list[#list].attr.stamp);
+	if last <= to_when then
+		return datamanager.list_store(username, host, self.store, nil);
+	end
+
 	-- luacheck: ignore 211/exact
 	local i, exact = binary_search(list, function(item)
 		local when = item.when or datetime.parse(item.attr.stamp);