[Asterisk-code-review] vector: Add AST_VECTOR_COMPACT() to reclaim wasted space (...asterisk[13])

Friendly Automation asteriskteam at digium.com
Mon Mar 18 06:26:12 CDT 2019


Friendly Automation has submitted this change and it was merged. ( https://gerrit.asterisk.org/c/asterisk/+/11150 )

Change subject: vector: Add AST_VECTOR_COMPACT() to reclaim wasted space
......................................................................

vector: Add AST_VECTOR_COMPACT() to reclaim wasted space

This might be useful in situations where you are loading an undetermined number
of items into a vector and don't want to keep (potentially) 2x the necessary
memory around indefinitely.

Change-Id: I9711daa0fe01783fc6f04c5710eba84f2676d7b9
---
M include/asterisk/vector.h
1 file changed, 28 insertions(+), 0 deletions(-)

Approvals:
  Corey Farrell: Looks good to me, but someone else must approve
  Kevin Harwell: Looks good to me, but someone else must approve
  Joshua Colp: Looks good to me, approved
  Friendly Automation: Approved for Submit



diff --git a/include/asterisk/vector.h b/include/asterisk/vector.h
index 2ee5e29..0e33590 100644
--- a/include/asterisk/vector.h
+++ b/include/asterisk/vector.h
@@ -590,6 +590,34 @@
 })
 
 /*!
+ * \brief Resize a vector so that its capacity is the same as its size.
+ *
+ * \param vec Vector to compact.
+ *
+ * \return 0 on success.
+ * \return Non-zero on failure.
+ */
+#define AST_VECTOR_COMPACT(vec) ({ \
+	int res = 0;								\
+	do {														\
+		if ((vec)->max > (vec)->current) {						\
+			size_t new_max = (vec)->current;				\
+			typeof((vec)->elems) new_elems = ast_realloc(		\
+				(vec)->elems,									\
+				new_max * sizeof(*new_elems));					\
+			if (new_elems || (vec)->current == 0) {				\
+				(vec)->elems = new_elems;						\
+				(vec)->max = new_max;							\
+			} else {											\
+				res = -1;										\
+				break;											\
+			}													\
+		}														\
+	} while(0);													\
+	res;														\
+})
+
+/*!
  * \brief Get an address of element in a vector.
  *
  * \param vec Vector to query.

-- 
To view, visit https://gerrit.asterisk.org/c/asterisk/+/11150
To unsubscribe, or for help writing mail filters, visit https://gerrit.asterisk.org/settings

Gerrit-Project: asterisk
Gerrit-Branch: 13
Gerrit-Change-Id: I9711daa0fe01783fc6f04c5710eba84f2676d7b9
Gerrit-Change-Number: 11150
Gerrit-PatchSet: 4
Gerrit-Owner: Sean Bright <sean.bright at gmail.com>
Gerrit-Reviewer: Corey Farrell <git at cfware.com>
Gerrit-Reviewer: Friendly Automation
Gerrit-Reviewer: Joshua Colp <jcolp at digium.com>
Gerrit-Reviewer: Kevin Harwell <kharwell at digium.com>
Gerrit-Reviewer: Sean Bright <sean.bright at gmail.com>
Gerrit-MessageType: merged
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.digium.com/pipermail/asterisk-code-review/attachments/20190318/67c6704d/attachment-0001.html>


More information about the asterisk-code-review mailing list