From e8a32e766fe3f5e40fb8918a4d825e6d0b9aa272 Mon Sep 17 00:00:00 2001 From: shejialuo Date: Mon, 6 Oct 2025 14:32:31 +0800 Subject: string-list: replace negative index encoding with "exact_match" parameter The "string_list_find_insert_index()" function is used to determine the correct insertion index for a new string within the string list. The function also doubles up to convey if the string is already existing in the list, this is done by returning a negative index "-1 -index". Users are expected to decode this information. This approach has several limitations: 1. It requires the callers to look into the detail of the function to understand how to decode the negative index encoding. 2. Using int for indices can cause overflow issues when dealing with large string lists. To address these limitations, change the function to return size_t for the index value and use a separate bool parameter to indicate whether the index refers to an existing entry or an insertion point. In some cases, the callers of "string_list_find_insert_index" only need the index position and don't care whether an exact match is found. However, "get_entry_index" currently requires a non-NULL "exact_match" parameter, forcing these callers to declare unnecessary variables. Let's allow callers to pass NULL for the "exact_match" parameter when they don't need this information, reducing unnecessary variable declarations in calling code. Signed-off-by: shejialuo Signed-off-by: Junio C Hamano --- string-list.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) (limited to 'string-list.c') diff --git a/string-list.c b/string-list.c index d8da3dd414..c589ab5a2c 100644 --- a/string-list.c +++ b/string-list.c @@ -29,12 +29,14 @@ static size_t get_entry_index(const struct string_list *list, const char *string else if (compare > 0) left = middle + 1; else { - *exact_match = true; + if (exact_match) + *exact_match = true; return middle; } } - *exact_match = false; + if (exact_match) + *exact_match = false; return right; } @@ -90,13 +92,9 @@ bool string_list_has_string(const struct string_list *list, const char *string) } int string_list_find_insert_index(const struct string_list *list, const char *string, - int negative_existing_index) + bool *exact_match) { - bool exact_match; - int index = get_entry_index(list, string, &exact_match); - if (exact_match) - index = -1 - (negative_existing_index ? index : 0); - return index; + return get_entry_index(list, string, exact_match); } struct string_list_item *string_list_lookup(struct string_list *list, const char *string) -- cgit v1.2.3