summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorNicolas Williams <nico@cryptonector.com>2013-12-02 12:16:38 -0600
committerNicolas Williams <nico@cryptonector.com>2013-12-04 18:21:42 -0600
commitcac14a531de733cbffe50eb4e6c479b5ef577e21 (patch)
tree124ac0590c6161cfb170571fc80c1c4a30527651
parentae7a042876130c471dce28a4396abc215192eaa9 (diff)
Add index strings by string; return string indexes
% jq '.[","]' "a,bc,def,ghij,klmno" [1,4,8,13] %
-rw-r--r--jv.c20
-rw-r--r--jv.h1
-rw-r--r--jv_aux.c2
3 files changed, 23 insertions, 0 deletions
diff --git a/jv.c b/jv.c
index b66b0738..0c0bbb76 100644
--- a/jv.c
+++ b/jv.c
@@ -621,6 +621,26 @@ not_this:
}
#endif /* HAVE_MEMMEM */
+jv jv_string_indexes(jv j, jv k) {
+ assert(jv_get_kind(j) == JV_KIND_STRING);
+ assert(jv_get_kind(k) == JV_KIND_STRING);
+ const char *jstr = jv_string_value(j);
+ const char *idxstr = jv_string_value(k);
+ const char *p;
+ int jlen = jv_string_length_bytes(jv_copy(j));
+ int idxlen = jv_string_length_bytes(jv_copy(k));
+ jv a = jv_array();
+
+ p = jstr;
+ while ((p = memmem(p, (jstr + jlen) - p, idxstr, idxlen)) != NULL) {
+ a = jv_array_append(a, jv_number(p - jstr));
+ p += idxlen;
+ }
+ jv_free(j);
+ jv_free(k);
+ return a;
+}
+
jv jv_string_split(jv j, jv sep) {
assert(jv_get_kind(j) == JV_KIND_STRING);
assert(jv_get_kind(sep) == JV_KIND_STRING);
diff --git a/jv.h b/jv.h
index 6b06eea3..efc6fecb 100644
--- a/jv.h
+++ b/jv.h
@@ -83,6 +83,7 @@ int jv_string_length_bytes(jv);
int jv_string_length_codepoints(jv);
unsigned long jv_string_hash(jv);
const char* jv_string_value(jv);
+jv jv_string_indexes(jv j, jv k);
jv jv_string_slice(jv j, int start, int end);
jv jv_string_concat(jv, jv);
jv jv_string_vfmt(const char*, va_list);
diff --git a/jv_aux.c b/jv_aux.c
index f3260c9d..76712aee 100644
--- a/jv_aux.c
+++ b/jv_aux.c
@@ -73,6 +73,8 @@ jv jv_get(jv t, jv k) {
v = jv_invalid_with_msg(jv_string_fmt("Start and end indices of an string slice must be numbers"));
jv_free(t);
}
+ } else if (jv_get_kind(t) == JV_KIND_STRING && jv_get_kind(k) == JV_KIND_STRING) {
+ v = jv_string_indexes(t, k);
} else if (jv_get_kind(t) == JV_KIND_NULL &&
(jv_get_kind(k) == JV_KIND_STRING ||
jv_get_kind(k) == JV_KIND_NUMBER ||