string-array: New function string_array_uniq().
authorBen Pfaff <blp@cs.stanford.edu>
Sat, 9 Jan 2021 19:24:22 +0000 (11:24 -0800)
committerBen Pfaff <blp@cs.stanford.edu>
Sat, 9 Jan 2021 21:53:01 +0000 (13:53 -0800)
src/libpspp/string-array.c
src/libpspp/string-array.h

index a22ade6e10880e28fb47bbca5010ec63a3fa7737..d4badf4638df124681e964f78286a9cb3fda02bc 100644 (file)
@@ -234,6 +234,25 @@ string_array_sort (struct string_array *sa)
   qsort (sa->strings, sa->n, sizeof *sa->strings, compare_strings);
 }
 
+/* Removes all but one of any series of adjacent duplicate strings in SA. */
+void
+string_array_uniq (struct string_array *sa)
+{
+  if (!sa->n)
+    return;
+
+  size_t n = 1;
+  for (size_t i = 1; i < sa->n; i++)
+    {
+      char *s = sa->strings[i];
+      if (strcmp (sa->strings[n - 1], s))
+        sa->strings[n++] = s;
+      else
+        free (s);
+    }
+  sa->n = n;
+}
+
 /* Divides STRING into tokens at DELIMITERS and adds each token to SA. */
 void
 string_array_parse (struct string_array *sa, struct substring string,
index ecad3326b6a73f3a02ff99101d3462e5ce3936fb..353ddf5018b8301a9b1e45749fab9b15fb55644a 100644 (file)
@@ -61,6 +61,7 @@ void string_array_terminate_null (struct string_array *);
 void string_array_shrink (struct string_array *);
 
 void string_array_sort (struct string_array *);
+void string_array_uniq (struct string_array *);
 
 void string_array_parse (struct string_array *, struct substring string,
                          struct substring delimiters);