write_queue: Enable updating max_length field

Dequeue and free any excess messages, in case the new queue length
is shorter than the old.

Related: OS#5774
Change-Id: Ibfe51a2faf29f8ae160a9c330c9af0d09b5a9002
diff --git a/tests/write_queue/wqueue_test.c b/tests/write_queue/wqueue_test.c
index 3823ef5..d4476f1 100644
--- a/tests/write_queue/wqueue_test.c
+++ b/tests/write_queue/wqueue_test.c
@@ -1,3 +1,14 @@
+/*
+ * (C) 2023 by sysmocom - s.f.m.c. GmbH.
+ * Authors: Holger Hans Peter Freyther
+ *	    Alexander Rehbein
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ */
+
 #include <osmocom/core/logging.h>
 #include <osmocom/core/utils.h>
 #include <osmocom/core/write_queue.h>
@@ -15,6 +26,7 @@
 	struct msgb *msg;
 	struct osmo_wqueue wqueue;
 	int rc;
+	size_t dropped_msgs;
 
 	osmo_wqueue_init(&wqueue, 0);
 	OSMO_ASSERT(wqueue.max_length == 0);
@@ -63,6 +75,46 @@
 	OSMO_ASSERT(wqueue.current_length == 2);
 	msgb_free(msg);
 	osmo_wqueue_clear(&wqueue);
+
+	/* Update limit */
+	OSMO_ASSERT(osmo_wqueue_set_maxlen(&wqueue, 5) == 0);
+	OSMO_ASSERT(osmo_wqueue_set_maxlen(&wqueue, 1) == 0);
+	OSMO_ASSERT(osmo_wqueue_set_maxlen(&wqueue, 4) == 0);
+
+	/* Add three, update limit to 1 */
+	OSMO_ASSERT(wqueue.max_length == 4);
+	msg = msgb_alloc(4096, "msg6");
+	rc = osmo_wqueue_enqueue(&wqueue, msg);
+	OSMO_ASSERT(rc == 0);
+	OSMO_ASSERT(wqueue.current_length == 1);
+	msg = msgb_alloc(4096, "msg7");
+	rc = osmo_wqueue_enqueue(&wqueue, msg);
+	OSMO_ASSERT(rc == 0);
+	OSMO_ASSERT(wqueue.current_length == 2);
+	msg = msgb_alloc(4096, "msg8");
+	rc = osmo_wqueue_enqueue(&wqueue, msg);
+	OSMO_ASSERT(wqueue.current_length == 3);
+	dropped_msgs = osmo_wqueue_set_maxlen(&wqueue, 1);
+	OSMO_ASSERT(dropped_msgs == 2);
+	osmo_wqueue_clear(&wqueue);
+
+	/* Add three, reduce limit to 3 from 6 */
+	OSMO_ASSERT(osmo_wqueue_set_maxlen(&wqueue, 6) == 0);
+	OSMO_ASSERT(wqueue.max_length == 6);
+	msg = msgb_alloc(4096, "msg9");
+	rc = osmo_wqueue_enqueue(&wqueue, msg);
+	OSMO_ASSERT(rc == 0);
+	OSMO_ASSERT(wqueue.current_length == 1);
+	msg = msgb_alloc(4096, "msg10");
+	rc = osmo_wqueue_enqueue(&wqueue, msg);
+	OSMO_ASSERT(rc == 0);
+	OSMO_ASSERT(wqueue.current_length == 2);
+	msg = msgb_alloc(4096, "msg11");
+	rc = osmo_wqueue_enqueue(&wqueue, msg);
+	OSMO_ASSERT(wqueue.current_length == 3);
+	dropped_msgs = osmo_wqueue_set_maxlen(&wqueue, 3);
+	OSMO_ASSERT(dropped_msgs == 0);
+	osmo_wqueue_clear(&wqueue);
 }
 
 int main(int argc, char **argv)