From 05d0e9b8bb43e2703bd0f0656e11f53c98946191 Mon Sep 17 00:00:00 2001
From: Max Kellermann <mk@cm4all.com>
Date: Wed, 17 Jan 2024 11:57:07 +0100
Subject: [PATCH] lib/avahi/Publisher: reuse the AvahiEntryGroup

The libavahi-client documentation recommends reusing AvahiEntryGroup
instances instead of freeing them and creating new ones.
---
 src/lib/avahi/Publisher.cxx | 37 +++++++++++++++----------------------
 1 file changed, 15 insertions(+), 22 deletions(-)

diff --git a/src/lib/avahi/Publisher.cxx b/src/lib/avahi/Publisher.cxx
index 0bfe2b47e..416fa3fde 100644
--- a/src/lib/avahi/Publisher.cxx
+++ b/src/lib/avahi/Publisher.cxx
@@ -126,32 +126,23 @@ AddServices(AvahiEntryGroup &group,
 		AddService(group, i, name);
 }
 
-static EntryGroupPtr
-MakeEntryGroup(AvahiClient &c,
-	       const std::forward_list<Service> &services, const char *name,
-	       AvahiEntryGroupCallback callback, void *userdata)
-{
-	EntryGroupPtr group(avahi_entry_group_new(&c, callback, userdata));
-	if (!group)
-		throw MakeError(c, "Failed to create Avahi service group");
-
-	AddServices(*group, services, name);
-
-	int error = avahi_entry_group_commit(group.get());
-	if (error != AVAHI_OK)
-		throw MakeError(error, "Failed to commit Avahi service group");
-
-	return group;
-}
-
 void
 Publisher::RegisterServices(AvahiClient *c) noexcept
 {
 	assert(visible);
 
 	try {
-		group = MakeEntryGroup(*c, services, name.c_str(),
-				       GroupCallback, this);
+		if (!group) {
+			group.reset(avahi_entry_group_new(c, GroupCallback, this));
+			if (!group)
+				throw MakeError(*c, "Failed to create Avahi service group");
+		}
+
+		AddServices(*group, services, name.c_str());
+
+		if (int error = avahi_entry_group_commit(group.get());
+		    error != AVAHI_OK)
+			throw MakeError(error, "Failed to commit Avahi service group");
 	} catch (...) {
 		error_handler.OnAvahiError(std::current_exception());
 	}
@@ -164,7 +155,9 @@ Publisher::HideServices() noexcept
 		return;
 
 	visible = false;
-	group.reset();
+
+	if (group)
+		avahi_entry_group_reset(group.get());
 }
 
 void
@@ -183,7 +176,7 @@ Publisher::ShowServices() noexcept
 void
 Publisher::OnAvahiConnect(AvahiClient *c) noexcept
 {
-	if (group == nullptr && visible)
+	if (visible)
 		RegisterServices(c);
 }