You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by va...@apache.org on 2026/04/25 16:22:29 UTC
(couchdb-jiffy) tag 2.0.0 created (now 83a470a)
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a change to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
at 83a470a (commit)
This tag includes the following new commits:
new 9dc7d0a Simplify numerical overflow handling for doubles
new 514d548 Simplify and speed up number parsing
new 25ad8b5 Encode UTF8 atoms (OTP 26+ only)
new 465193c Allow number encoding as keys
new bd7df5f Export 'encode_options/0' and 'decode_options/0' types
new 3e3a06b Implement pre-encoded json
new 62c80e7 Remove dead yielding code
new 81f1918 Skip-ahead for UTF8 encoding
new 83a470a Version 2.0.0
The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(couchdb-jiffy) 04/09: Allow number encoding as keys
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 465193c6cdaf9abb1608fe5d8c3ce5c0c6c05f18
Author: Gaspar Chilingarov <ga...@gmail.com>
AuthorDate: Thu Jun 29 15:12:38 2017 +0300
Allow number encoding as keys
Co-author: Nick Vatamaniuc <va...@apache.org>
---
README.md | 6 +++++-
c_src/encoder.c | 29 +++++++++++++++++++----------
test/jiffy_07_compound_tests.erl | 23 ++++++++++++++++++++++-
test/jiffy_12_error_tests.erl | 9 +--------
4 files changed, 47 insertions(+), 20 deletions(-)
diff --git a/README.md b/README.md
index ed84d6e..5572a4b 100644
--- a/README.md
+++ b/README.md
@@ -106,10 +106,14 @@ Data Format
[true, 1.0] -> [true, 1.0] -> [true, 1.0]
{[]} -> {} -> {[]}
{[{foo, bar}]} -> {"foo": "bar"} -> {[{<<"foo">>, <<"bar">>}]}
+ {[{123, bar}]} -> {"123": "bar"} -> {[{<<"123">>, <<"bar">>}]}
+ {[{1.5, bar}]} -> {"1.5": "bar"} -> {[{<<"1.5">>, <<"bar">>}]}
{[{<<"foo">>, <<"bar">>}]} -> {"foo": "bar"} -> {[{<<"foo">>, <<"bar">>}]}
#{<<"foo">> => <<"bar">>} -> {"foo": "bar"} -> #{<<"foo">> => <<"bar">>}
+ #{123 => <<"bar">>} -> {"123": "bar"} -> #{<<"123">> => <<"bar">>}
+ #{1.5 => <<"bar">>} -> {"1.5": "bar"} -> #{<<"1.5">> => <<"bar">>}
-N.B. The last entry in this table is only valid for VM's that support
+N.B. The last three entries in this table are only valid for VM's that support
the `maps` data type (i.e., 17.0 and newer) and client code must pass
the `return_maps` option to `jiffy:decode/2`.
diff --git a/c_src/encoder.c b/c_src/encoder.c
index 731b78b..ca1689e 100644
--- a/c_src/encoder.c
+++ b/c_src/encoder.c
@@ -492,16 +492,6 @@ enc_string(Encoder* e, ERL_NIF_TERM val)
return enc_quoted(e, bin.data, bin.size, 0);
}
-static inline int
-enc_object_key(ErlNifEnv *env, Encoder* e, ERL_NIF_TERM val)
-{
- if(enif_is_atom(env, val)) {
- return enc_atom(e, val);
- }
-
- return enc_string(e, val);
-}
-
// From https://www.slideshare.net/andreialexandrescu1/three-optimization-tips-for-c-15708507
#define P01 10
@@ -620,6 +610,25 @@ enc_char(Encoder* e, char c)
return 1;
}
+static inline int
+enc_object_key(ErlNifEnv *env, Encoder* e, ERL_NIF_TERM val)
+{
+ ErlNifSInt64 ival;
+ double dval;
+
+ if(enif_is_atom(env, val)) {
+ return enc_atom(e, val);
+ }
+ if(enif_get_int64(env, val, &ival)) {
+ return enc_char(e, '"') && enc_long(e, ival) && enc_char(e, '"');
+ }
+ if(enif_get_double(env, val, &dval)) {
+ return enc_char(e, '"') && enc_double(e, dval) && enc_char(e, '"');
+ }
+
+ return enc_string(e, val);
+}
+
static int
enc_shift(Encoder* e) {
int i;
diff --git a/test/jiffy_07_compound_tests.erl b/test/jiffy_07_compound_tests.erl
index 45fd383..39e4941 100644
--- a/test/jiffy_07_compound_tests.erl
+++ b/test/jiffy_07_compound_tests.erl
@@ -9,7 +9,8 @@
compound_success_test_() ->
- [gen(ok, Case) || Case <- cases(ok)].
+ [gen(ok, Case) || Case <- cases(ok)] ++
+ [gen(number_key_encoding, Case) || Case <- cases(number_key_encoding)].
compound_failure_test_() ->
@@ -24,6 +25,11 @@ gen(ok, {J1, E, J2}) ->
{"Encode", ?_assertEqual(J2, enc(E))}
]};
+gen(number_key_encoding, {J, E}) ->
+ {msg("~s", [J]), [
+ {"Encode", ?_assertEqual(J, enc(E))}
+ ]};
+
gen(error, J) ->
{msg("Error: ~s", [J]), [
?_assertError(_, dec(J))
@@ -53,6 +59,21 @@ cases(ok) ->
}
];
+cases(number_key_encoding) ->
+ [
+ % Integer keys
+ {<<"{\"123\":\"foo\"}">>, {[{123, <<"foo">>}]}},
+ {<<"{\"-1\":\"n\"}">>, {[{-1, <<"n">>}]}},
+ {<<"{\"123\":\"a\",\"456\":\"b\"}">>, {[{123, <<"a">>}, {456, <<"b">>}]}},
+ {<<"{\"123\":\"v\"}">>, #{123 => <<"v">>}},
+ % These could change if we swtich away from Ryu
+ {<<"{\"1.5\":\"x\"}">>, {[{1.5, <<"x">>}]}},
+ {<<"{\"-2.5\":\"x\"}">>, {[{-2.5, <<"x">>}]}},
+ {<<"{\"0.0\":\"x\"}">>, {[{0.0, <<"x">>}]}},
+ {<<"{\"1.5\":\"a\",\"2.0\":\"b\"}">>, {[{1.5, <<"a">>}, {2.0, <<"b">>}]}},
+ {<<"{\"1.5\":\"v\"}">>, #{1.5 => <<"v">>}}
+ ];
+
cases(error) ->
[
<<"[{}">>,
diff --git a/test/jiffy_12_error_tests.erl b/test/jiffy_12_error_tests.erl
index 7a1ed9f..7c2c2b3 100644
--- a/test/jiffy_12_error_tests.erl
+++ b/test/jiffy_12_error_tests.erl
@@ -68,17 +68,10 @@ enc_invalid_object_member_arity_test_() ->
enc_invalid_object_member_key_test_() ->
Type = invalid_object_member_key,
- E1 = {1, true},
{"invalid_object_member_key", [
{"Bad string", enc_error(Type, <<143>>, {[{<<143>>, true}]})},
- {"Basic", enc_error(Type, 1, {[{1, true}]})},
{"Basic", enc_error(Type, [1], {[{[1], true}]})},
- {"Basic", enc_error(Type, {[{foo,bar}]}, {[{{[{foo,bar}]}, true}]})},
- {"Second", enc_error(Type, 1, {[{bar, baz}, E1]})},
- {"Nested", enc_error(Type, 1, {[{bar,{[E1]}}]})},
- {"Nested", enc_error(Type, 1, {[{bar,{[{baz, 1}, E1]}}]})},
- {"In List", enc_error(Type, 1, [{[E1]}])},
- {"In List", enc_error(Type, 1, [{[{bang, true}, E1]}])}
+ {"Basic", enc_error(Type, {[{foo,bar}]}, {[{{[{foo,bar}]}, true}]})}
]}.
(couchdb-jiffy) 05/09: Export 'encode_options/0' and 'decode_options/0' types
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit bd7df5f12fc87373e1400ec461d8408086f45f75
Author: Feng Lee <fe...@emqx.io>
AuthorDate: Sun Jan 19 10:24:46 2020 +0800
Export 'encode_options/0' and 'decode_options/0' types
---
src/jiffy.erl | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/jiffy.erl b/src/jiffy.erl
index 8f9f4ac..81275ab 100644
--- a/src/jiffy.erl
+++ b/src/jiffy.erl
@@ -46,9 +46,9 @@
-type decode_options() :: [decode_option()].
-type encode_options() :: [encode_option()].
+-export_type([decode_options/0, encode_options/0]).
-export_type([json_value/0, jiffy_decode_result/0]).
-
-spec decode(iolist() | binary()) -> jiffy_decode_result().
decode(Data) ->
decode(Data, []).
(couchdb-jiffy) 09/09: Version 2.0.0
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 83a470a574c543812a11b6dd92dd2698eb00c615
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Sat Apr 25 12:07:30 2026 -0400
Version 2.0.0
Performance
===========
- **SIMD vectorization** for ASCII scan-ahead loops in both decoder string parsing and encoder
string emission. This meant replacing the byte-at-a-time scans with 16/32-byte chunked compares.
The most interesting part is it was done without writing a single line of assembly, just relying
on compiler auto-vectorization. This showed a **15x** performance improvement on encoding large
strings like in the "Issue 90" benchmark. To get even better auto-vectorizer behavior, it's
advisable to set `-march=native` or `-march=x86-64-v3`. That can make the auto-vectorizers on
recent compilers switch to using 256bit AVX2 registers and instructions.
- **UTF-8 skip-ahead in encoder** and faster UTF-8 validation. This is like the scan-ahead loop for
ASCII, but it's for UTF-8 validation. This helps quite a bit on non-ASCII, Unicode-heavy inputs.
"UTF-8 unescaped" benchmark got a **5.8x** speedup from it.
- Use **Ryu** for number encoding. This is the exact Ryu version from the latest Erlang/OTP release
with all the updates and tweaks they added. This makes the float output the same as Erlang's.
However, this means the output is not exactly the same as before for Jiffy (we used to emit more
fractional digits, now it switches to the scientific notation a bit earlier). Number heavy
benchmarks like "Canada" showed a **2x** speedup.
- **ffc.h** for number parsing in the decoder. This is the fastest C number parser around at this
time. I worked with the upstream author to add a new API to it parse JSON numbers as a single call
which returns back either an integer or a double, as opposed pre-parsing to figure out which is
which first (https://github.com/kolemannix/ffc.h/pull/22). Using this library yielded a **4x**
speedup in the number-heavy "Canada" benchmark on decoding.
- **Faster array and map creation** for building the result term in fewer steps. (In the processes
discovered that maps with duplicates created from NIFs were subtly broken in Erlang
https://github.com/erlang/otp/pull/10976. The fix is now merged and should be in the recent patch
Erlang releases). This bulk creation improved decoding across the board. Some examples are
**2.5x** for "JSON Generator", **2.6x** for "Github" and **3.3x** for "Blockchain". Most of those
a mixed inputs so number parsing and scan-ahead played a role in there as well.
- **Branch hints** (`JIFFY_LIKELY` / `JIFFY_UNLIKELY`) on encoder hot paths. I saw QuickJS library
doing this, so experimented around and saw few percent speedup from it.
- **Unity build**. Having handled a few issues over the years related to enabling, disabling and
detecting LTO (Link-time optimization) compiler features, decided to side-step it and go with a
unity build. This is where we include all the source file into one `jiffy.c` file and compile
that. We get all the benefits of LTO but without having to juggle linker flags.
Yielding & scheduler behavior
- **Reduction count bumped to 4000** to match current Erlang VM defaults
- **Bytes per reduction lowered** so cooperative yields fire more
often on long input. This results in better latency under contention without a
measurable throughput hit.
Since Jiffy is a NIF, it's crucial for it to never block schedulers and always yield appropriately.
As the concurrency increases it should degrade gracefully in proportion to the applied load. This is
not a trivial task to accomplish in a NIF, in general. Some json library NIFs use dirty schedulers,
however in cases where Jiffy is used that wouldn't work as that is still a limited resource and
during high concurrency it would lead to bottlenecks.
A separate benchmark, `bench_scheduling.sh` in https://github.com/nickva/bench runs concurrent JSON
encoding and decoding scaled by the number of schedulers. Testing with a few Erlang json libraries
shows something like this:
```
./bench_scheduling.sh
...
scheduler responsiveness check
input: citm-catalog.json duration: 2000
schedulers: 12 online
impls: json, jiffy, simdjsone, jsone, jsx
[json]
1x encdec n=84 p50=135.0ms p95=182.9ms p99=191.9ms max=196.7ms
12x encdec n=86 p50=129.7ms p95=189.9ms p99=203.0ms max=206.2ms
24x encdec n=87 p50=263.0ms p95=461.2ms p99=506.1ms max=527.1ms
[jiffy]
1x encdec n=309 p50=38.3ms p95=51.9ms p99=57.4ms max=66.5ms
12x encdec n=300 p50=41.2ms p95=52.5ms p99=59.7ms max=66.2ms
24x encdec n=306 p50=80.2ms p95=111.8ms p99=118.8ms max=140.1ms
[simdjsone]
1x encdec n=20 p50=690.1ms p95=784.6ms p99=784.6ms max=784.8ms
12x encdec n=16 p50=790.9ms p95=887.5ms p99=887.5ms max=899.9ms
24x encdec n=24 p50=1448.4ms p95=1876.7ms p99=1879.5ms max=1882.7ms
[jsone]
1x encdec n=60 p50=213.1ms p95=261.8ms p99=263.9ms max=264.8ms
12x encdec n=60 p50=204.9ms p95=329.8ms p99=345.0ms max=350.9ms
24x encdec n=52 p50=440.1ms p95=700.3ms p99=773.3ms max=817.3ms
[jsx]
1x encdec n=24 p50=398.8ms p95=539.0ms p99=544.1ms max=548.3ms
12x encdec n=24 p50=391.5ms p95=684.9ms p99=687.0ms max=689.6ms
24x encdec n=24 p50=1181.3ms p95=1479.0ms p99=1558.1ms max=1654.7ms
```
There we measure both the latency of sending a term back and forth between two encoder/decoder
processes, as well as the throughput (`n` is how many times we managed to do that).
Features
- **Pre-encoded JSON** — embed already-encoded JSON fragments directly in a value being encoded,
saving a round-trip through the decoder. Use `{json, IoData}` terms and they will be embedded in
the emitted stream as is. This was a surprisingly popular feature over the years. Paul J. Davis
(Jiffy's original author) suggested a nice and quick patch to make it work so I went with that.
- **Encode UTF-8 atoms** (on OTP 26+ only!) atoms with non-ASCII bytes now encode as their UTF-8
source. Unfortunately this is for OTP 26+ only.
- **Number-as-key encoding** — integer/float map keys are encoded as string keys instead of
erroring. Both Python and Erlang/OTP's built-in json already does this.
Correctness & compliance
========================
- **RFC 8259 100% compliance.** A new test suite based on `nst/JSONTestSuite` is wired in and all
conformance tests pass.
- **Big List of Naughty Strings (BLNS)** added in the test mix.
Build & CI
==========
- **OTP 21** is the new minimum.
- **C coverage checks** added so the test suite reports per-file C line coverage; several uncovered
paths were closed during this work.
---
src/jiffy.app.src | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/jiffy.app.src b/src/jiffy.app.src
index 1908c8c..1dce860 100644
--- a/src/jiffy.app.src
+++ b/src/jiffy.app.src
@@ -1,9 +1,9 @@
{application, jiffy, [
{description, "JSON Decoder/Encoder."},
- {vsn, "1.1.2"},
+ {vsn, "2.0.0"},
{registered, []},
{applications, [kernel, stdlib, xmerl]},
- {maintainers, ["Paul J. Davis"]},
+ {maintainers, ["Paul J. Davis", "Nick Vatamaniuc"]},
{licenses, ["MIT", "BSD"]},
{links, [{"GitHub", "https://github.com/davisp/jiffy"}]},
{files, [
(couchdb-jiffy) 01/09: Simplify numerical overflow handling for doubles
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 9dc7d0ac7ca9ad19bc03024cc53c95c4b3f8672b
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Mon Apr 20 18:56:44 2026 -0400
Simplify numerical overflow handling for doubles
Previously, we handled the exponent and the fractional part with different
flags and different atoms on the NIF side. There is not reason to do that since
we split them on e/E in Erlang anyway, so we can figure out what's what and
differentiate between the two cases.
---
c_src/decoder.c | 18 ++++++------------
c_src/jiffy.c | 1 -
c_src/jiffy.h | 1 -
src/jiffy.erl | 40 ++++++++++++++++++++++++----------------
4 files changed, 30 insertions(+), 30 deletions(-)
diff --git a/c_src/decoder.c b/c_src/decoder.c
index 7ebaeb9..3617b41 100644
--- a/c_src/decoder.c
+++ b/c_src/decoder.c
@@ -373,8 +373,7 @@ dec_number(Decoder* d, ERL_NIF_TERM* value)
{
ERL_NIF_TERM num_type = d->atoms->atom_error;
char state = nst_init;
- int has_frac = 0;
- int has_exp = 0;
+ int is_real = 0;
double dval;
int64_t lval;
@@ -489,7 +488,7 @@ dec_number(Decoder* d, ERL_NIF_TERM* value)
break;
case nst_frac1:
- has_frac = 1;
+ is_real = 1;
switch(p[idx]) {
case '0':
case '1':
@@ -536,7 +535,7 @@ dec_number(Decoder* d, ERL_NIF_TERM* value)
break;
case nst_esign:
- has_exp = 1;
+ is_real = 1;
switch(p[idx]) {
case '-':
case '+':
@@ -632,7 +631,7 @@ parse:
const char* nend = (const char*)&p[d->i];
const size_t num_len = d->i - start;
- if(has_frac || has_exp) {
+ if(is_real) {
ffc_parse_options opts = {FFC_PRESET_JSON, '.'};
ffc_result res = ffc_from_chars_double_options(nstart, nend, &dval, opts);
if(res.outcome == FFC_OUTCOME_OK) {
@@ -647,13 +646,8 @@ parse:
}
}
- if(!has_frac && !has_exp) {
- num_type = d->atoms->atom_bignum;
- } else if(!has_frac && has_exp) {
- num_type = d->atoms->atom_bignum_e;
- } else {
- num_type = d->atoms->atom_bigdbl;
- }
+ // Let Erlang handle out-of-range cases
+ num_type = is_real ? d->atoms->atom_bigdbl : d->atoms->atom_bignum;
d->is_partial = 1;
*value = enif_make_sub_binary(d->env, d->arg, start, num_len);
diff --git a/c_src/jiffy.c b/c_src/jiffy.c
index c44952a..46cbce7 100644
--- a/c_src/jiffy.c
+++ b/c_src/jiffy.c
@@ -29,7 +29,6 @@ load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)
st->atom_true = make_atom(env, "true");
st->atom_false = make_atom(env, "false");
st->atom_bignum = make_atom(env, "bignum");
- st->atom_bignum_e = make_atom(env, "bignum_e");
st->atom_bigdbl = make_atom(env, "bigdbl");
st->atom_partial = make_atom(env, "partial");
st->atom_uescape = make_atom(env, "uescape");
diff --git a/c_src/jiffy.h b/c_src/jiffy.h
index 68dcb90..7012dad 100644
--- a/c_src/jiffy.h
+++ b/c_src/jiffy.h
@@ -39,7 +39,6 @@ typedef struct {
ERL_NIF_TERM atom_true;
ERL_NIF_TERM atom_false;
ERL_NIF_TERM atom_bignum;
- ERL_NIF_TERM atom_bignum_e;
ERL_NIF_TERM atom_bigdbl;
ERL_NIF_TERM atom_partial;
ERL_NIF_TERM atom_uescape;
diff --git a/src/jiffy.erl b/src/jiffy.erl
index fd9c230..8f9f4ac 100644
--- a/src/jiffy.erl
+++ b/src/jiffy.erl
@@ -100,23 +100,31 @@ encode(Data, Options) ->
finish_decode({bignum, Value}) ->
binary_to_integer(Value);
-finish_decode({bignum_e, Value}) ->
- {IVal, EVal} = case binary:split(Value, [<<$e>>, <<$E>>]) of
- [IStr, EStr] ->
- {binary_to_integer(IStr), binary_to_integer(EStr)}
- end,
- try
- IVal * math:pow(10, EVal)
- catch
- error:badarith ->
- error({range, EVal})
- end;
finish_decode({bigdbl, Value}) ->
- try
- binary_to_float(Value)
- catch
- error:badarg ->
- error({range, Value})
+ % Got something like a 1e400, 1.5e500, or 999...999.5. Split on e/E and if
+ % we do have an explicit exponent use math:pow/2 to create the float since
+ % Erlang/OTP's binary_to_float can't handle something like 1e10, it needs
+ % the first number (the mantissa) to have '.' in it (it has to be 1.0e10).
+ case binary:split(Value, [<<$e>>, <<$E>>]) of
+ [IStr, EStr] ->
+ EVal = binary_to_integer(EStr),
+ IVal = case binary:match(IStr, <<$.>>) of
+ nomatch -> binary_to_integer(IStr);
+ _ -> binary_to_float(IStr)
+ end,
+ try
+ IVal * math:pow(10, EVal)
+ catch
+ error:badarith ->
+ error({range, Value})
+ end;
+ [_] ->
+ try
+ binary_to_float(Value)
+ catch
+ error:badarg ->
+ error({range, Value})
+ end
end;
finish_decode({Pairs}) when is_list(Pairs) ->
finish_decode_obj(Pairs, []);
(couchdb-jiffy) 08/09: Skip-ahead for UTF8 encoding
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 81f1918f680dde7b1274decdd17023112b02e577
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Thu Apr 23 14:22:57 2026 -0400
Skip-ahead for UTF8 encoding
Just like we do it for ASCII-only input, this should help unicode-heavy input.
---
c_src/decoder.c | 2 +-
c_src/encoder.c | 51 +++++++++++++++++++++++++++++++++++----------------
c_src/jiffy_simd.h | 27 ++++++++++++++++++++++++++-
c_src/jiffy_utf8.h | 20 ++++++++++++++++++++
4 files changed, 82 insertions(+), 18 deletions(-)
diff --git a/c_src/decoder.c b/c_src/decoder.c
index 4915241..05524f9 100644
--- a/c_src/decoder.c
+++ b/c_src/decoder.c
@@ -260,7 +260,7 @@ dec_string(Decoder* d, ERL_NIF_TERM* value)
} else if(d->p[d->i] < 0x80) {
// Scan ahead plain ASCII as an optimization. The first
// byte has already been checked, so start at i+1.
- d->i = jiffy_scan_string_body(d->p, d->len, d->i + 1);
+ d->i = jiffy_scan_ascii_string_body(d->p, d->len, d->i + 1);
} else {
ulen = utf8_validate(&(d->p[d->i]), d->len - d->i);
if(ulen == 0) {
diff --git a/c_src/encoder.c b/c_src/encoder.c
index a9644fd..79ea956 100644
--- a/c_src/encoder.c
+++ b/c_src/encoder.c
@@ -409,7 +409,7 @@ enc_quoted(Encoder* e,
i++;
}
} else {
- i = jiffy_scan_string_body(data, size, i);
+ i = jiffy_scan_ascii_string_body(data, size, i);
}
size_t run = i - start;
if(!enc_ensure(e, run)) {
@@ -424,27 +424,46 @@ enc_quoted(Encoder* e,
e->i += unicode_to_utf8((int)data[i], &(e->p[e->i]));
}
i++;
- } else {
- // UTF-8 2/3/4-byte sequence: validate, then copy as is or
- // or uencode as \uXXXX
+ } else if(JIFFY_UNLIKELY(e->uescape)) {
ulen = utf8_validate((unsigned char*)&(data[i]), size - i);
if(JIFFY_UNLIKELY(ulen == 0)) {
return 0;
- } else if(JIFFY_UNLIKELY(e->uescape)) {
- uval = utf8_to_unicode((unsigned char*)&(data[i]), size - i);
- if(uval < 0) {
- return 0;
- }
- esc_len = unicode_uescape(uval, &(e->p[e->i]));
- if(esc_len < 0) {
- return 0;
+ }
+ uval = utf8_to_unicode((unsigned char*)&(data[i]), size - i);
+ if(uval < 0) {
+ return 0;
+ }
+ esc_len = unicode_uescape(uval, &(e->p[e->i]));
+ if(esc_len < 0) {
+ return 0;
+ }
+ e->i += esc_len;
+ i += ulen;
+ } else {
+ // Non-ASCII UTF-8 . Scan through the run first and then validate
+ // the whole thing, kinda how we do it for ASCII only.
+ start = i;
+ i++;
+ if(e->escape_forward_slashes) {
+ while(i < size
+ && data[i] >= 0x20
+ && data[i] != '\"'
+ && data[i] != '\\'
+ && data[i] != '/') {
+ i++;
}
- e->i += esc_len;
} else {
- memcpy(&e->p[e->i], &data[i], ulen);
- e->i += ulen;
+ i = jiffy_scan_utf8_string_body(data, size, i);
}
- i += ulen;
+ size_t run = i - start;
+ if(JIFFY_UNLIKELY(!utf8_validate_range(&data[start], run))) {
+ return 0;
+ }
+ if(JIFFY_UNLIKELY(!enc_ensure(e, run))) {
+ return 0;
+ }
+ memcpy(&(e->p[e->i]), &data[start], run);
+ e->i += run;
}
}
diff --git a/c_src/jiffy_simd.h b/c_src/jiffy_simd.h
index 44ad5d8..6f3eb76 100644
--- a/c_src/jiffy_simd.h
+++ b/c_src/jiffy_simd.h
@@ -50,7 +50,7 @@ jiffy_block_has_stop(const unsigned char* JIFFY_RESTRICT p)
}
static inline size_t
-jiffy_scan_string_body(const unsigned char* JIFFY_RESTRICT p, size_t len, size_t i)
+jiffy_scan_ascii_string_body(const unsigned char* JIFFY_RESTRICT p, size_t len, size_t i)
{
while (i + JIFFY_SIMD_BLOCK_SIZE <= len && !jiffy_block_has_stop(p + i)) {
i += JIFFY_SIMD_BLOCK_SIZE;
@@ -61,4 +61,29 @@ jiffy_scan_string_body(const unsigned char* JIFFY_RESTRICT p, size_t len, size_t
return i;
}
+// Variant of the scan which lets UTF-8 multi-byte sequences pass through. This
+// so we can scan a whole block and then validate it as a block later.
+static inline unsigned int
+jiffy_block_has_utf8_stop(const unsigned char* JIFFY_RESTRICT p)
+{
+ unsigned int bad = 0;
+ for (int i = 0; i < JIFFY_SIMD_BLOCK_SIZE; i++) {
+ unsigned char c = p[i];
+ bad |= (unsigned)(c < 0x20) | (unsigned)(c == '"') | (unsigned)(c == '\\');
+ }
+ return bad;
+}
+
+static inline size_t
+jiffy_scan_utf8_string_body(const unsigned char* JIFFY_RESTRICT p, size_t len, size_t i)
+{
+ while (i + JIFFY_SIMD_BLOCK_SIZE <= len && !jiffy_block_has_utf8_stop(p + i)) {
+ i += JIFFY_SIMD_BLOCK_SIZE;
+ }
+ while (i < len && p[i] >= 0x20 && p[i] != '"' && p[i] != '\\') {
+ i++;
+ }
+ return i;
+}
+
#endif
diff --git a/c_src/jiffy_utf8.h b/c_src/jiffy_utf8.h
index f6891e9..95b333a 100644
--- a/c_src/jiffy_utf8.h
+++ b/c_src/jiffy_utf8.h
@@ -236,6 +236,26 @@ utf8_validate(const unsigned char* JIFFY_RESTRICT data, size_t size)
return 4;
}
+// Validate a whole range UTF-8 codepoints
+static inline int
+utf8_validate_range(const unsigned char* data, size_t size)
+{
+ size_t i = 0;
+ while(i < size) {
+ if(data[i] < 0x80) {
+ i++;
+ // ASCII skip-through
+ continue;
+ }
+ size_t ulen = utf8_validate((unsigned char*)&data[i], size - i);
+ if(ulen == 0) {
+ return 0;
+ }
+ i += ulen;
+ }
+ return 1;
+}
+
static inline int
unicode_to_utf8(int c, unsigned char* buf)
{
(couchdb-jiffy) 02/09: Simplify and speed up number parsing
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 514d5485efdcdda5d499d25eead78b3af2324f3a
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Wed Apr 22 00:45:59 2026 -0400
Simplify and speed up number parsing
With the ffc_parse_json_number [1] patch, and consolidating overflow atoms [2]
in jiffy, we can now have our cake and eat it, too; that is we simplify and
speed-up number decoding at the same time.
[1] https://github.com/kolemannix/ffc.h/pull/22
[2] https://github.com/davisp/jiffy/pull/284
---
c_src/decoder.c | 305 +++-----------------------------
c_src/ffc.h | 86 ++++++++-
test/cases/leading_zero_in_number.eterm | 2 +-
3 files changed, 105 insertions(+), 288 deletions(-)
diff --git a/c_src/decoder.c b/c_src/decoder.c
index 3617b41..4915241 100644
--- a/c_src/decoder.c
+++ b/c_src/decoder.c
@@ -25,18 +25,6 @@ enum {
st_invalid
} JsonState;
-enum {
- nst_init=0,
- nst_sign,
- nst_mantissa,
- nst_frac0,
- nst_frac1,
- nst_frac,
- nst_esign,
- nst_echeck,
- nst_edigit
-} JsonNumState;
-
typedef struct {
ErlNifEnv* env;
jiffy_st* atoms;
@@ -371,292 +359,43 @@ parse:
static int
dec_number(Decoder* d, ERL_NIF_TERM* value)
{
- ERL_NIF_TERM num_type = d->atoms->atom_error;
- char state = nst_init;
- int is_real = 0;
- double dval;
- int64_t lval;
-
- // Use the same trick as did for dec_string. The restrict qualifier hints
- // to the compiler p won't alias any other pointers so it can optimize
- // access to it. Also avoid writing back do d->i on every increment,
- // instead increment a local variable (hopefully in a register) then update
- // d->i once at the end. Also, when parsing looping states (mantissa, frac,
- // edigit) scan-ahead quickly looking for strings of digits only. The wins
- // will not be as big as we have for strings as most numbers are not that
- // long, but it shouldn't hurt either.
+ // ffc validates, parses, and picks int-vs-double in a single call
const unsigned char* JIFFY_RESTRICT p = d->p;
- const size_t len = d->len;
const size_t start = d->i;
- size_t idx = start;
- while(idx < len) {
- switch(state) {
- case nst_init:
- switch(p[idx]) {
- case '-':
- state = nst_sign;
- idx++;
- break;
- case '0':
- state = nst_frac0;
- idx++;
- break;
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- state = nst_mantissa;
- idx++;
- break;
- default:
- assert(0 && "this state should be unreachable"); // LCOV_EXCL_LINE
- }
- break;
-
- case nst_sign:
- switch(p[idx]) {
- case '0':
- state = nst_frac0;
- idx++;
- break;
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- state = nst_mantissa;
- idx++;
- break;
- default:
- goto error;
- }
- break;
-
- case nst_mantissa:
- switch(p[idx]) {
- case '.':
- state = nst_frac1;
- idx++;
- break;
- case 'e':
- case 'E':
- state = nst_esign;
- idx++;
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- while(idx < len && p[idx] >= '0' && p[idx] <= '9') {
- idx++;
- }
- break;
- default:
- goto parse;
- }
- break;
-
- case nst_frac0:
- switch(p[idx]) {
- case '.':
- state = nst_frac1;
- idx++;
- break;
- case 'e':
- case 'E':
- state = nst_esign;
- idx++;
- break;
- default:
- goto parse;
- }
- break;
-
- case nst_frac1:
- is_real = 1;
- switch(p[idx]) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- state = nst_frac;
- idx++;
- break;
- default:
- goto parse;
- }
- break;
-
- case nst_frac:
- switch(p[idx]) {
- case 'e':
- case 'E':
- state = nst_esign;
- idx++;
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- while(idx < len && p[idx] >= '0' && p[idx] <= '9') {
- idx++;
- }
- break;
- default:
- goto parse;
- }
- break;
-
- case nst_esign:
- is_real = 1;
- switch(p[idx]) {
- case '-':
- case '+':
- state = nst_echeck;
- idx++;
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- state = nst_edigit;
- idx++;
- break;
- default:
- goto error;
- }
- break;
-
- case nst_echeck:
- switch(p[idx]) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- state = nst_edigit;
- while(idx < len && p[idx] >= '0' && p[idx] <= '9') {
- idx++;
- }
- break;
- default:
- goto parse;
- }
- break;
+ const char* nstart = (const char*)&p[start];
+ const char* nend_max = (const char*)&p[d->len];
- case nst_edigit:
- switch(p[idx]) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- while(idx < len && p[idx] >= '0' && p[idx] <= '9') {
- idx++;
- }
- break;
- default:
- goto parse;
- }
- break;
+ ffc_json_number jn;
+ ffc_result r = ffc_parse_json_number(nstart, nend_max, &jn);
- default:
- goto error;
- }
- }
+ // After parsing r.ptr point to where parsing stops:
+ // OK - first byte past the number
+ // OUT_OF_RANGE - first byte past the number (same span, just doesn't fit)
+ // INVALID - the offending byte
+ d->i = start + (size_t)(r.ptr - nstart);
-parse:
- d->i = idx;
-
- switch(state) {
- case nst_init:
- case nst_sign:
- case nst_frac1:
- case nst_esign:
- case nst_echeck:
- return 0;
- default:
- break;
+ if(r.outcome == FFC_OUTCOME_INVALID_INPUT) {
+ return 0;
}
- // Use ffc.h to parse numbers. It parses direclty from the stream no need
- // to allocate a separate buffer as with strtod and strtol. The state
- // machine already validated the syntax, so parse-level errors shouldn't
- // occur here, only FFC_OUTCOME_OUT_OF_RANGE. If the range erro happens we
- // fall back to Erlang with handle big numbers.
- const char* nstart = (const char*)&p[start];
- const char* nend = (const char*)&p[d->i];
- const size_t num_len = d->i - start;
-
- if(is_real) {
- ffc_parse_options opts = {FFC_PRESET_JSON, '.'};
- ffc_result res = ffc_from_chars_double_options(nstart, nend, &dval, opts);
- if(res.outcome == FFC_OUTCOME_OK) {
- *value = enif_make_double(d->env, dval);
- return 1;
- }
- } else {
- ffc_result res = ffc_parse_i64(num_len, nstart, 10, &lval);
- if(res.outcome == FFC_OUTCOME_OK) {
- *value = enif_make_int64(d->env, lval);
- return 1;
+ if(r.outcome == FFC_OUTCOME_OK) {
+ if(jn.kind == FFC_JSON_NUM_KIND_INT64) {
+ *value = enif_make_int64(d->env, jn.value.i64);
+ } else {
+ *value = enif_make_double(d->env, jn.value.f64);
}
+ return 1;
}
- // Let Erlang handle out-of-range cases
- num_type = is_real ? d->atoms->atom_bigdbl : d->atoms->atom_bignum;
+ ERL_NIF_TERM num_type = (jn.kind == FFC_JSON_NUM_KIND_INT64)
+ ? d->atoms->atom_bignum
+ : d->atoms->atom_bigdbl;
d->is_partial = 1;
+ const size_t num_len = (size_t)(r.ptr - nstart);
*value = enif_make_sub_binary(d->env, d->arg, start, num_len);
*value = enif_make_tuple2(d->env, num_type, *value);
return 1;
-
-error:
- d->i = idx;
- return 0;
}
static ERL_NIF_TERM
diff --git a/c_src/ffc.h b/c_src/ffc.h
index 8d40697..056b6f9 100644
--- a/c_src/ffc.h
+++ b/c_src/ffc.h
@@ -253,6 +253,32 @@ uint64_t ffc_parse_u64_simple(size_t len, const char *input, int base, ffc_outco
int32_t ffc_parse_i32_simple(size_t len, const char *input, int base, ffc_outcome *outcome);
uint32_t ffc_parse_u32_simple(size_t len, const char *input, int base, ffc_outcome *outcome);
+/**
+ * Parse a JSON number from the range [start, end) and return an int64_t or a double
+ *
+ * If the outcome is FCC_OUTCOME_OK
+ * If kind == FFC_JSON_NUM_KIND_INT64, value will be an int64
+ * If kind == FCC_JSON_NUM_DOUBLE, value will be a double
+ *
+ * The returned ffc_result's ptr points at the byte where parsing stopped
+ */
+
+typedef uint32_t ffc_json_number_kind;
+enum ffc_json_number_kind_bits {
+ FFC_JSON_NUM_KIND_INT64 = 0,
+ FFC_JSON_NUM_KIND_DOUBLE = 1,
+};
+
+typedef struct ffc_json_number {
+ ffc_json_number_kind kind;
+ union {
+ int64_t i64;
+ double f64;
+ } value;
+} ffc_json_number;
+
+ffc_result ffc_parse_json_number(const char *start, const char *end, ffc_json_number *out);
+
#endif // FFC_API
#ifdef FFC_IMPL
@@ -1271,13 +1297,16 @@ ffc_parsed ffc_parse_number_string(
++p;
}
if ((p == pend) || !ffc_is_integer(*p)) {
- if (!(uint64_t)(fmt & FFC_FORMAT_FLAG_FIXED)) {
+ if (basic_json_fmt || !(uint64_t)(fmt & FFC_FORMAT_FLAG_FIXED)) {
// The exponential part is invalid for scientific notation, so it must
// be a trailing token for fixed notation. However, fixed notation is
- // disabled, so report a scientific notation error.
+ // disabled, so report a scientific notation error. JSON mode is strict
+ // for the scientific form (exp = e [ minus / plus ] 1*DIGIT in RFC
+ // 8259) so we also report the error, even though FIXED is part of
+ // FFC_PRESET_JSON.
return ffc_report_parse_error(p, FFC_PARSE_OUTCOME_MISSING_EXPONENTIAL_PART);
}
- // Otherwise, we will be ignoring the 'e'.
+ // Otherwise (fixed-tolerant, non-JSON), we will be ignoring the 'e'.
p = location_of_e;
} else {
while ((p != pend) && ffc_is_integer(*p)) {
@@ -3200,7 +3229,56 @@ uint32_t ffc_parse_u32_simple(size_t len, const char *input, int base, ffc_outco
return out;
}
-#undef FFC_DOUBLE_SMALLEST_POWER_OF_10
+ffc_result ffc_parse_json_number(const char *start, const char *end,
+ ffc_json_number *out) {
+ ffc_result answer;
+
+ if (start == end) {
+ answer.ptr = (char *)start;
+ answer.outcome = FFC_OUTCOME_INVALID_INPUT;
+ return answer;
+ }
+
+ ffc_parse_options opts;
+ opts.format = FFC_PRESET_JSON;
+ opts.decimal_point = '.';
+
+ ffc_parsed pns = ffc_parse_number_string(start, end, opts, true);
+
+ if (!pns.valid) {
+ answer.ptr = (char *)pns.lastmatch;
+ answer.outcome = FFC_OUTCOME_INVALID_INPUT;
+ return answer;
+ }
+
+ // INT64 or DOUBLE?
+ // For an integer bytes consumed past the sign should be just digits
+ // If we see '.' then `fractional_part_start` is not NULL
+ // If we see e/E then consumed span is > int_part_len (e + $digit)
+ // If both above are true then we have a DOUBLE
+ size_t consumed = (size_t)(pns.lastmatch - start) - (pns.negative ? 1 : 0);
+ bool is_integer = (pns.fraction_part_start == NULL) && (consumed == pns.int_part_len);
+
+ ffc_result r;
+ if (is_integer) {
+ ffc_int_value v = {0};
+ r = ffc_parse_int_string(start, end, &v, FFC_INT_KIND_S64, opts, 10);
+ out->kind = FFC_JSON_NUM_KIND_INT64;
+ if (r.outcome == FFC_OUTCOME_OK) {
+ out->value.i64 = v.s64;
+ }
+ } else {
+ ffc_value v = {0};
+ r = ffc_from_chars_advanced(pns, &v, FFC_VALUE_KIND_DOUBLE);
+ out->kind = FFC_JSON_NUM_KIND_DOUBLE;
+ if (r.outcome == FFC_OUTCOME_OK) {
+ out->value.f64 = v.d;
+ }
+ }
+ return r;
+}
+
+#undef FFC_DOUBLE_SMALLEST_POWER_OF_10
#undef FFC_DOUBLE_LARGEST_POWER_OF_10
#undef FFC_DOUBLE_SIGN_INDEX
#undef FFC_DOUBLE_INFINITE_POWER
diff --git a/test/cases/leading_zero_in_number.eterm b/test/cases/leading_zero_in_number.eterm
index 5bc5d8c..e184037 100644
--- a/test/cases/leading_zero_in_number.eterm
+++ b/test/cases/leading_zero_in_number.eterm
@@ -1 +1 @@
-{error,{17,invalid_json}}.
+{error,{16,invalid_number}}.
(couchdb-jiffy) 07/09: Remove dead yielding code
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 62c80e72268411ce83cb87c6a839ea5ec249208c
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Fri Apr 24 00:10:05 2026 -0400
Remove dead yielding code
Looking at scheduling and yielding noticed we had a whole bunch of dead code
hanging around. Nothing calls iterator code in Erlang any longer, all our
scheduling is done in C now.
On one hand it's a bit silly to keep the functions named `_init` but, on the
other hand, I think it kind of makes sense, since they are still following init
+ iter pattern, just that the iteration continues in C.
---
c_src/jiffy.c | 6 +-----
c_src/jiffy.h | 1 -
src/jiffy.erl | 45 ---------------------------------------------
3 files changed, 1 insertion(+), 51 deletions(-)
diff --git a/c_src/jiffy.c b/c_src/jiffy.c
index 46cbce7..debdab9 100644
--- a/c_src/jiffy.c
+++ b/c_src/jiffy.c
@@ -34,7 +34,6 @@ load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)
st->atom_uescape = make_atom(env, "uescape");
st->atom_pretty = make_atom(env, "pretty");
st->atom_force_utf8 = make_atom(env, "force_utf8");
- st->atom_iter = make_atom(env, "iter");
st->atom_bytes_per_iter = make_atom(env, "bytes_per_iter");
st->atom_bytes_per_red = make_atom(env, "bytes_per_red");
st->atom_return_maps = make_atom(env, "return_maps");
@@ -89,13 +88,10 @@ unload(ErlNifEnv* env, void* priv)
// {name, arity, fptr, dirty_flag}
// dirty flag: 0 (default) | ERL_NIF_DIRTY_JOB_{IO|CPU}_BOUND
-//
static ErlNifFunc funcs[] =
{
{"nif_decode_init", 2, decode_init, 0},
- {"nif_decode_iter", 5, decode_iter, 0},
- {"nif_encode_init", 2, encode_init, 0},
- {"nif_encode_iter", 3, encode_iter, 0}
+ {"nif_encode_init", 2, encode_init, 0}
};
ERL_NIF_INIT(jiffy, funcs, &load, NULL, &upgrade, &unload);
diff --git a/c_src/jiffy.h b/c_src/jiffy.h
index 7012dad..9547016 100644
--- a/c_src/jiffy.h
+++ b/c_src/jiffy.h
@@ -44,7 +44,6 @@ typedef struct {
ERL_NIF_TERM atom_uescape;
ERL_NIF_TERM atom_pretty;
ERL_NIF_TERM atom_force_utf8;
- ERL_NIF_TERM atom_iter;
ERL_NIF_TERM atom_bytes_per_iter;
ERL_NIF_TERM atom_bytes_per_red;
ERL_NIF_TERM atom_return_maps;
diff --git a/src/jiffy.erl b/src/jiffy.erl
index 5313e5a..6860faf 100644
--- a/src/jiffy.erl
+++ b/src/jiffy.erl
@@ -63,8 +63,6 @@ decode(Data, Opts) when is_binary(Data), is_list(Opts) ->
error(Error);
{partial, EJson} ->
finish_decode(EJson);
- {iter, {_, Decoder, Val, Objs, Curr}} ->
- decode_loop(Data, Decoder, Val, Objs, Curr);
EJson ->
EJson
end;
@@ -91,8 +89,6 @@ encode(Data, Options) ->
error(Error);
{partial, IOData} ->
finish_encode(IOData, []);
- {iter, {Encoder, Stack, IOBuf}} ->
- encode_loop(Data, Options, Encoder, Stack, IOBuf);
[Bin] when is_binary(Bin) ->
Bin;
RevIOData when is_list(RevIOData) ->
@@ -186,52 +182,11 @@ init() ->
erlang:load_nif(filename:join(PrivDir, "jiffy"), 0).
-decode_loop(Data, Decoder, Val, Objs, Curr) ->
- case nif_decode_iter(Data, Decoder, Val, Objs, Curr) of
- {error, Error} ->
- error(Error);
- {partial, EJson} ->
- finish_decode(EJson);
- {iter, {_, NewDecoder, NewVal, NewObjs, NewCurr}} ->
- decode_loop(Data, NewDecoder, NewVal, NewObjs, NewCurr);
- EJson ->
- EJson
- end.
-
-
-encode_loop(Data, Options, Encoder, Stack, IOBuf) ->
- ForceUTF8 = lists:member(force_utf8, Options),
- case nif_encode_iter(Encoder, Stack, IOBuf) of
- {error, {invalid_string, _}} when ForceUTF8 == true ->
- FixedData = jiffy_utf8:fix(Data),
- encode(FixedData, Options -- [force_utf8]);
- {error, {invalid_object_member_key, _}} when ForceUTF8 == true ->
- FixedData = jiffy_utf8:fix(Data),
- encode(FixedData, Options -- [force_utf8]);
- {error, Error} ->
- error(Error);
- {partial, IOData} ->
- finish_encode(IOData, []);
- {iter, {NewEncoder, NewStack, NewIOBuf}} ->
- encode_loop(Data, Options, NewEncoder, NewStack, NewIOBuf);
- [Bin] when is_binary(Bin) ->
- Bin;
- RevIOData when is_list(RevIOData) ->
- lists:reverse(RevIOData)
- end.
-
-
not_loaded(Line) ->
erlang:nif_error({not_loaded, [{module, ?MODULE}, {line, Line}]}).
nif_decode_init(_Data, _Opts) ->
?NOT_LOADED.
-nif_decode_iter(_Data, _Decoder, _, _, _) ->
- ?NOT_LOADED.
-
nif_encode_init(_Data, _Options) ->
?NOT_LOADED.
-
-nif_encode_iter(_Encoder, _Stack, _IoList) ->
- ?NOT_LOADED.
(couchdb-jiffy) 03/09: Encode UTF8 atoms (OTP 26+ only)
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 25ad8b52b3f1a09d7a96541b85f2641e0a33ca41
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Wed Apr 22 15:11:16 2026 -0400
Encode UTF8 atoms (OTP 26+ only)
As a nice side-benefit we get to de-duplicate string encoding between atoms and
strings. The only snag is this is an OTP 26+ only feature. Below that ERL NIF
interface doesn't return atom in UTF8 format.
Fix https://github.com/davisp/jiffy/issues/231
---
c_src/encoder.c | 168 +++++++++++++++--------------------------
test/jiffy_04_string_tests.erl | 46 ++++++++++-
2 files changed, 107 insertions(+), 107 deletions(-)
diff --git a/c_src/encoder.c b/c_src/encoder.c
index 196ecf8..731b78b 100644
--- a/c_src/encoder.c
+++ b/c_src/encoder.c
@@ -362,30 +362,32 @@ enc_special_character(Encoder* e, int val) {
}
}
-static int
-enc_atom(Encoder* e, ERL_NIF_TERM val)
+// ERL_NIF_UTF8 was added in NIF 2.17 (OTP 26). We detect it to know
+// if we can pass it to enif_get_atom()
+#if ERL_NIF_MAJOR_VERSION > 2 \
+ || (ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION >= 17)
+#define JIFFY_ENIF_HAS_UTF8 1
+#endif
+
+static inline int
+enc_quoted(Encoder* e,
+ const unsigned char* JIFFY_RESTRICT data,
+ size_t size,
+ int latin1_only)
{
static const int MAX_ESCAPE_LEN = 12;
- unsigned char data[512];
-
- size_t size;
+ size_t i = 0;
size_t start;
- size_t i;
-
- if(!enif_get_atom(e->env, val, (char*)data, 512, ERL_NIF_LATIN1)) {
- return 0;
- }
-
- size = strlen((const char*)data);
+ size_t ulen;
+ int uval;
+ int esc_len;
- /* Reserve space for the first quotation mark and most of the output. */
if(!enc_ensure(e, size + MAX_ESCAPE_LEN + 1)) {
return 0;
}
e->p[e->i++] = '\"';
- i = 0;
while(i < size) {
if(!enc_ensure(e, MAX_ESCAPE_LEN)) {
return 0;
@@ -394,9 +396,7 @@ enc_atom(Encoder* e, ERL_NIF_TERM val)
if(JIFFY_UNLIKELY(enc_special_character(e, data[i]))) {
i++;
} else if(JIFFY_LIKELY(data[i] < 0x80)) {
- // Scan ahead for plain ASCII chars which don't need escaping.
- // Since optionally users could escape forward slashes, too, we
- // stop on them as well
+ // Scan ahead for plain ASCII chars that don't need escaping.
start = i;
i++;
if(e->escape_forward_slashes) {
@@ -417,111 +417,33 @@ enc_atom(Encoder* e, ERL_NIF_TERM val)
}
memcpy(&(e->p[e->i]), &data[start], run);
e->i += run;
- } else if(data[i] >= 0x80) {
- /* The atom encoding is latin1, so we don't need validation
- * as all latin1 characters are valid Unicode codepoints. */
- if (!e->uescape) {
- e->i += unicode_to_utf8(data[i], &e->p[e->i]);
+ } else if(latin1_only) {
+ if(JIFFY_UNLIKELY(e->uescape)) {
+ e->i += unicode_uescape((int)data[i], &(e->p[e->i]));
} else {
- e->i += unicode_uescape(data[i], &e->p[e->i]);
+ e->i += unicode_to_utf8((int)data[i], &(e->p[e->i]));
}
-
- i++;
- }
- }
-
- if(!enc_ensure(e, 1)) {
- return 0;
- }
-
- e->p[e->i++] = '\"';
- e->count++;
-
- return 1;
-}
-
-static int
-enc_string(Encoder* e, ERL_NIF_TERM val)
-{
- static const int MAX_ESCAPE_LEN = 12;
- ErlNifBinary bin;
-
- unsigned char* JIFFY_RESTRICT data;
- size_t size;
- int esc_len;
- size_t ulen;
- int uval;
- size_t start;
- size_t i;
-
- if(!enif_inspect_binary(e->env, val, &bin)) {
- return 0;
- }
-
- data = bin.data;
- size = bin.size;
-
- /* Reserve space for the first quotation mark and most of the output. */
- if(!enc_ensure(e, size + MAX_ESCAPE_LEN + 1)) {
- return 0;
- }
-
- e->p[e->i++] = '\"';
-
- i = 0;
- while(i < size) {
- if(!enc_ensure(e, MAX_ESCAPE_LEN)) {
- return 0;
- }
-
- if(enc_special_character(e, data[i])) {
- i++;
- } else if(data[i] < 0x80) {
- // Scan ahead for plain ASCII char and memcpy them. Stop at quotes,
- // backslashes, and forward slashes, since users can optionally
- // choose to escape them too.
- start = i;
i++;
- if(e->escape_forward_slashes) {
- while(i < size
- && data[i] >= 0x20
- && data[i] < 0x80
- && data[i] != '\"'
- && data[i] != '\\'
- && data[i] != '/') {
- i++;
- }
- } else {
- i = jiffy_scan_string_body(data, size, i);
- }
- size_t run = i - start;
- if(!enc_ensure(e, run)) {
- return 0;
- }
- memcpy(&(e->p[e->i]), &data[start], run);
- e->i += run;
- } else if(JIFFY_UNLIKELY(data[i] >= 0x80)) {
- ulen = utf8_validate(&(data[i]), size - i);
-
- if (JIFFY_UNLIKELY(ulen == 0)) {
+ } else {
+ // UTF-8 2/3/4-byte sequence: validate, then copy as is or
+ // or uencode as \uXXXX
+ ulen = utf8_validate((unsigned char*)&(data[i]), size - i);
+ if(JIFFY_UNLIKELY(ulen == 0)) {
return 0;
- } else if (JIFFY_UNLIKELY(e->uescape)) {
- uval = utf8_to_unicode(&(data[i]), size-i);
+ } else if(JIFFY_UNLIKELY(e->uescape)) {
+ uval = utf8_to_unicode((unsigned char*)&(data[i]), size - i);
if(uval < 0) {
return 0;
}
-
esc_len = unicode_uescape(uval, &(e->p[e->i]));
if(esc_len < 0) {
return 0;
}
-
e->i += esc_len;
} else {
memcpy(&e->p[e->i], &data[i], ulen);
e->i += ulen;
}
-
i += ulen;
}
}
@@ -536,6 +458,40 @@ enc_string(Encoder* e, ERL_NIF_TERM val)
return 1;
}
+static int
+enc_atom(Encoder* e, ERL_NIF_TERM val)
+{
+ // 255 code points * max 4 UTF-8 bytes + NUL fits in 1024.
+ unsigned char data[1024];
+ int n;
+
+#ifdef JIFFY_ENIF_HAS_UTF8
+ n = enif_get_atom(e->env, val, (char*)data, sizeof(data), ERL_NIF_UTF8);
+ if(n <= 0) {
+ return 0;
+ }
+ return enc_quoted(e, data, (size_t)n - 1, 0);
+#else
+ n = enif_get_atom(e->env, val, (char*)data, sizeof(data), ERL_NIF_LATIN1);
+ if(n <= 0) {
+ return 0;
+ }
+ return enc_quoted(e, data, (size_t)n - 1, 1);
+#endif
+}
+
+static int
+enc_string(Encoder* e, ERL_NIF_TERM val)
+{
+ ErlNifBinary bin;
+
+ if(!enif_inspect_binary(e->env, val, &bin)) {
+ return 0;
+ }
+
+ return enc_quoted(e, bin.data, bin.size, 0);
+}
+
static inline int
enc_object_key(ErlNifEnv *env, Encoder* e, ERL_NIF_TERM val)
{
diff --git a/test/jiffy_04_string_tests.erl b/test/jiffy_04_string_tests.erl
index c96e014..88276df 100644
--- a/test/jiffy_04_string_tests.erl
+++ b/test/jiffy_04_string_tests.erl
@@ -11,7 +11,51 @@
latin1_atom_test_() ->
Key = list_to_atom([228]), %% `ä`
Expected = <<"{\"", 195, 164, "\":\"bar\"}">>,
- ?_assertEqual(Expected, jiffy:encode({[{Key, <<"bar">>}]})).
+ ?_assertEqual(Expected, enc({[{Key, <<"bar">>}]})).
+
+% These are slightly sneaky and contain a NUL
+latin1_nul_atom_test_() ->
+ Bad = binary_to_atom(<<0, 1, 255, 255, 255, 255>>, latin1),
+ [
+ ?_assertEqual(<<"\"\\u0000\\u0001ÿÿÿÿ\""/utf8>>, enc(Bad)),
+ ?_assertEqual(<<"\"\\u0000\\u0001\\u00FF\\u00FF\\u00FF\\u00FF\"">>,
+ enc(Bad, [uescape]))
+ ].
+
+% From issue https://github.com/davisp/jiffy/issues/231
+% ERL_NIF_UTF8 was added in NIF 2.17 (OTP 26) though
+-if(?OTP_RELEASE >= 26).
+utf8_atom_test_() ->
+ % 2-byte UTF8
+ Satas = binary_to_atom(<<"ŝatas"/utf8>>, utf8),
+ % 3-byte UTF8 (Google translated this as "Hello")
+ Hello = binary_to_atom(<<"你好"/utf8>>, utf8),
+ % 4-byte UTF8 (Rocket)
+ Rocket = binary_to_atom(<<"🚀"/utf8>>, utf8),
+ [
+ ?_assertEqual(<<"\"", "ŝatas"/utf8, "\"">>, enc(Satas)),
+ ?_assertEqual(<<"\"", "你好"/utf8, "\"">>, enc(Hello)),
+ ?_assertEqual(<<"\"", "🚀"/utf8, "\"">>, enc(Rocket)),
+ ?_assertEqual(<<"\"\\u015Datas\"">>, enc(Satas, [uescape])),
+ ?_assertEqual(<<"\"\\u4F60\\u597D\"">>, enc(Hello, [uescape])),
+ ?_assertEqual(<<"\"\\uD83D\\uDE80\"">>, enc(Rocket, [uescape])),
+ ?_assertEqual(<<"{\"", "ŝatas"/utf8, "\":\"v\"}">>, enc(#{Satas => <<"v">>})),
+ ?_assertEqual(atom_to_binary(Satas, utf8), dec(enc(Satas))),
+ ?_assertEqual(atom_to_binary(Hello, utf8), dec(enc(Hello))),
+ ?_assertEqual(atom_to_binary(Rocket, utf8), dec(enc(Rocket)))
+ ].
+-else.
+utf8_atom_test_() ->
+ % ERL_NIF_UTF8 isn't available so these atoms can't be extracted.
+ Satas = binary_to_atom(<<"ŝatas"/utf8>>, utf8),
+ Hello = binary_to_atom(<<"你好"/utf8>>, utf8),
+ Rocket = binary_to_atom(<<"🚀"/utf8>>, utf8),
+ [
+ ?_assertError({invalid_string, _}, enc(Satas)),
+ ?_assertError({invalid_string, _}, enc(Hello)),
+ ?_assertError({invalid_string, _}, enc(Rocket))
+ ].
+-endif.
atom_key_test_() ->
[
(couchdb-jiffy) 06/09: Implement pre-encoded json
Posted by va...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
nickva pushed a commit to tag 2.0.0
in repository https://gitbox.apache.org/repos/asf/couchdb-jiffy.git
commit 3e3a06bf5cf9d4301bbaab93cb01bd4cd2c8a35e
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Thu Apr 23 22:20:41 2026 -0400
Implement pre-encoded json
There have been issues raised and at at least two PRs trying to implement this over
the years:
https://github.com/davisp/jiffy/issues/128
https://github.com/davisp/jiffy/pull/139
https://github.com/davisp/jiffy/pull/140
Here we'll just go with @davisp's neat idea from
https://github.com/davisp/jiffy/commit/46136403945d03224f9e7fe545ebbfdf5dfae057
with a few tests attached. It's minimal and does what most folks seem to want.
Co-authored-by: Paul J. Davis <pa...@gmail.com>
---
README.md | 14 ++++++++++
c_src/encoder.c | 8 ++++--
src/jiffy.erl | 10 +++++--
test/jiffy_18_pre_encoded_tests.erl | 55 +++++++++++++++++++++++++++++++++++++
4 files changed, 83 insertions(+), 4 deletions(-)
diff --git a/README.md b/README.md
index 5572a4b..0ef11c7 100644
--- a/README.md
+++ b/README.md
@@ -88,6 +88,20 @@ The options for encode are:
* `{bytes_per_red, N}` - Refer to the decode options
* `{bytes_per_iter, N}` - Refer to the decode options
+Pre-encoded JSON
+----------------
+
+A `{json, IoData}` tuple can appear anywhere a JSON value is expected (except
+as an object key). The `IoData` is spliced into the output as is. Jiffy does
+not parse, validate, copy, or pretty-print it.
+
+ 1> jiffy:encode([1, {json, <<"{\"cached\":true}">>}, 3]).
+ <<"[1,{\"cached\":true},3]">>
+ 2> jiffy:encode({[{<<"a">>, {json, [<<"[1,">>, "2,3]"]}}]}).
+ <<"{\"a\":[1,2,3]}">>
+
+The caller is responsible for ensuring it is well-formed JSON.
+
Data Format
-----------
diff --git a/c_src/encoder.c b/c_src/encoder.c
index ca1689e..a9644fd 100644
--- a/c_src/encoder.c
+++ b/c_src/encoder.c
@@ -961,8 +961,12 @@ encode_iter(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
}
} else if(enif_get_tuple(env, curr, &arity, &tuple)) {
if(arity != 1) {
- ret = enc_obj_error(e, "invalid_ejson", curr);
- goto done;
+ // Handle unknown or pre-encoded JSON in finish_encode/2
+ if(!enc_unknown(e, curr)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ continue;
}
if(!enif_is_list(env, tuple[0])) {
ret = enc_obj_error(e, "invalid_object", curr);
diff --git a/src/jiffy.erl b/src/jiffy.erl
index 81275ab..5313e5a 100644
--- a/src/jiffy.erl
+++ b/src/jiffy.erl
@@ -23,6 +23,8 @@
-type json_object() :: {[{json_string(),json_value()}]}
| #{json_string() => json_value()}.
+-type json_preencoded() :: {json, iodata()}.
+
-type jiffy_decode_result() :: json_value()
| {has_trailer, json_value(), binary()}.
@@ -70,12 +72,12 @@ decode(Data, Opts) when is_list(Data) ->
decode(iolist_to_binary(Data), Opts).
--spec encode(json_value()) -> iodata().
+-spec encode(json_value() | json_preencoded()) -> iodata().
encode(Data) ->
encode(Data, []).
--spec encode(json_value(), encode_options()) -> iodata().
+-spec encode(json_value() | json_preencoded(), encode_options()) -> iodata().
encode(Data, Options) ->
ForceUTF8 = lists:member(force_utf8, Options),
case nif_encode_init(Data, Options) of
@@ -162,6 +164,10 @@ finish_encode([<<_/binary>>=B | Rest], Acc) ->
finish_encode(Rest, [B | Acc]);
finish_encode([Val | Rest], Acc) when is_integer(Val) ->
finish_encode(Rest, [integer_to_binary(Val) | Acc]);
+finish_encode([{json, Json} | Rest], Acc) ->
+ %% Pre-encoded JSON spliced into the output as-is. This came from
+ %% enc_unknown.
+ finish_encode(Rest, [Json | Acc]);
finish_encode([InvalidEjson | _], _) ->
error({invalid_ejson, InvalidEjson});
finish_encode(_, _) ->
diff --git a/test/jiffy_18_pre_encoded_tests.erl b/test/jiffy_18_pre_encoded_tests.erl
new file mode 100644
index 0000000..78c3863
--- /dev/null
+++ b/test/jiffy_18_pre_encoded_tests.erl
@@ -0,0 +1,55 @@
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+-module(jiffy_18_pre_encoded_tests).
+
+-include_lib("eunit/include/eunit.hrl").
+-include("jiffy_util.hrl").
+
+bare_pre_encoded_test() ->
+ ?assertEqual(<<"[1,2,3]">>, enc({json, <<"[1,2,3]">>})),
+ ?assertEqual(<<"42">>, enc({json, <<"42">>})),
+ ?assertEqual(<<"\"hi\"">>, enc({json, <<"\"hi\"">>})).
+
+iolist_pre_encoded_test() ->
+ ?assertEqual(<<"[1,2,3]">>, enc({json, [<<"[">>, "1,2,", <<"3]">>]})),
+ ?assertEqual(<<"[1,2,3]">>, enc({json, [$[, [$1, $,, $2], <<",3]">>]})).
+
+inside_array_test() ->
+ Pre = {json, <<"{\"x\":42}">>},
+ ?assertEqual(<<"[1,{\"x\":42},3]">>, enc([1, Pre, 3])).
+
+inside_object_test() ->
+ Pre = {json, <<"[1,2,3]">>},
+ ?assertEqual(
+ <<"{\"a\":[1,2,3],\"b\":2}">>,
+ enc({[{<<"a">>, Pre}, {<<"b">>, 2}]})
+ ),
+ % Map iteration order is unpredictable so round-trip it
+ MapOut = enc(#{<<"a">> => Pre, <<"b">> => 2}),
+ ?assertEqual(
+ #{<<"a">> => [1, 2, 3], <<"b">> => 2},
+ jiffy:decode(MapOut, [return_maps])
+ ).
+
+nested_pre_encoded_test() ->
+ % Nesting
+ Inner = {json, <<"\"raw\"">>},
+ EJson = {[
+ {<<"k1">>, [1, Inner, 3]},
+ {<<"k2">>, {json, <<"null">>}}
+ ]},
+ ?assertEqual(
+ <<"{\"k1\":[1,\"raw\",3],\"k2\":null}">>,
+ enc(EJson)
+ ).
+
+invalid_non_arity_one_tuple_still_errors_test() ->
+ % Other arity-2 things still surface as an error
+ ?assertError({invalid_ejson, {foo, bar}}, enc({foo, bar})).
+
+pretty_with_pre_encoded_test() ->
+ % No pretty-printing or anything for spliced json
+ Pre = {json, <<"[1,2,3]">>},
+ Out = iol2b(jiffy:encode([1, Pre], [pretty])),
+ ?assertNotEqual(nomatch, binary:match(Out, <<"[1,2,3]">>)).