You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by rn...@apache.org on 2013/12/24 00:31:10 UTC
[01/12] Replace ejson with jiffy
Updated Branches:
refs/heads/1843-replace-ejson-with-jiffy [created] 2e6092e4e
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/simple.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/simple.json b/src/jiffy/test/cases/simple.json
new file mode 100644
index 0000000..9ed80c9
--- /dev/null
+++ b/src/jiffy/test/cases/simple.json
@@ -0,0 +1,5 @@
+{
+ "this": "is",
+ "really": "simple",
+ "json": "right?"
+}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_invalid_escape.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_invalid_escape.eterm b/src/jiffy/test/cases/string_invalid_escape.eterm
new file mode 100644
index 0000000..eb20890
--- /dev/null
+++ b/src/jiffy/test/cases/string_invalid_escape.eterm
@@ -0,0 +1 @@
+{error,{63,invalid_string}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_invalid_escape.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_invalid_escape.json b/src/jiffy/test/cases/string_invalid_escape.json
new file mode 100644
index 0000000..54a38ac
--- /dev/null
+++ b/src/jiffy/test/cases/string_invalid_escape.json
@@ -0,0 +1 @@
+["\n foo \/ bar \r\f\\\ufffd\t\b\"\\ and you can't escape thi\s"]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_invalid_hex_char.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_invalid_hex_char.eterm b/src/jiffy/test/cases/string_invalid_hex_char.eterm
new file mode 100644
index 0000000..51de423
--- /dev/null
+++ b/src/jiffy/test/cases/string_invalid_hex_char.eterm
@@ -0,0 +1 @@
+{error,{44,invalid_string}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_invalid_hex_char.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_invalid_hex_char.json b/src/jiffy/test/cases/string_invalid_hex_char.json
new file mode 100644
index 0000000..bde7ee9
--- /dev/null
+++ b/src/jiffy/test/cases/string_invalid_hex_char.json
@@ -0,0 +1 @@
+"foo foo, blah blah \u0123 \u4567 \u89ab \uc/ef \uABCD \uEFFE bar baz bing"
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_with_escapes.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_with_escapes.eterm b/src/jiffy/test/cases/string_with_escapes.eterm
new file mode 100644
index 0000000..51f7f25
--- /dev/null
+++ b/src/jiffy/test/cases/string_with_escapes.eterm
@@ -0,0 +1,5 @@
+[
+ <<"\n foo \/ bar \r\f\\", 239, 191, 186, "\t\b\"\\">>,
+ <<"\"and this string has an escape at the beginning">>,
+ <<"and this string has no escapes">>
+].
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_with_escapes.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_with_escapes.json b/src/jiffy/test/cases/string_with_escapes.json
new file mode 100644
index 0000000..532b5f4
--- /dev/null
+++ b/src/jiffy/test/cases/string_with_escapes.json
@@ -0,0 +1,3 @@
+["\n foo \/ bar \r\f\\\ufffa\t\b\"\\",
+ "\"and this string has an escape at the beginning",
+ "and this string has no escapes" ]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_with_invalid_newline.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_with_invalid_newline.eterm b/src/jiffy/test/cases/string_with_invalid_newline.eterm
new file mode 100644
index 0000000..626a2f4
--- /dev/null
+++ b/src/jiffy/test/cases/string_with_invalid_newline.eterm
@@ -0,0 +1 @@
+{error,{67,invalid_string}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/string_with_invalid_newline.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/string_with_invalid_newline.json b/src/jiffy/test/cases/string_with_invalid_newline.json
new file mode 100644
index 0000000..2756f26
--- /dev/null
+++ b/src/jiffy/test/cases/string_with_invalid_newline.json
@@ -0,0 +1,2 @@
+"la di dah. this is a string, and I can do this, \n, but not this
+"
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/three_byte_utf8.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/three_byte_utf8.eterm b/src/jiffy/test/cases/three_byte_utf8.eterm
new file mode 100644
index 0000000..111676b
--- /dev/null
+++ b/src/jiffy/test/cases/three_byte_utf8.eterm
@@ -0,0 +1,4 @@
+{[
+ {<<"matzue">>, <<230, 157, 190, 230, 177, 159>>},
+ {<<"asakusa">>, <<230, 181, 133, 232, 141, 137>>}
+]}.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/three_byte_utf8.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/three_byte_utf8.json b/src/jiffy/test/cases/three_byte_utf8.json
new file mode 100644
index 0000000..9c9e656
--- /dev/null
+++ b/src/jiffy/test/cases/three_byte_utf8.json
@@ -0,0 +1 @@
+{"matzue": "松江", "asakusa": "浅草"}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/true.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/true.eterm b/src/jiffy/test/cases/true.eterm
new file mode 100644
index 0000000..60c0d88
--- /dev/null
+++ b/src/jiffy/test/cases/true.eterm
@@ -0,0 +1 @@
+true.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/true.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/true.json b/src/jiffy/test/cases/true.json
new file mode 100644
index 0000000..27ba77d
--- /dev/null
+++ b/src/jiffy/test/cases/true.json
@@ -0,0 +1 @@
+true
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/true_then_garbage.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/true_then_garbage.eterm b/src/jiffy/test/cases/true_then_garbage.eterm
new file mode 100644
index 0000000..30b0113
--- /dev/null
+++ b/src/jiffy/test/cases/true_then_garbage.eterm
@@ -0,0 +1 @@
+{error,{5,invalid_trailing_data}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/true_then_garbage.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/true_then_garbage.json b/src/jiffy/test/cases/true_then_garbage.json
new file mode 100644
index 0000000..9151612
--- /dev/null
+++ b/src/jiffy/test/cases/true_then_garbage.json
@@ -0,0 +1 @@
+truex
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/unescaped_bulgarian.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/unescaped_bulgarian.eterm b/src/jiffy/test/cases/unescaped_bulgarian.eterm
new file mode 100644
index 0000000..2a31b61
--- /dev/null
+++ b/src/jiffy/test/cases/unescaped_bulgarian.eterm
@@ -0,0 +1,5 @@
+[
+ <<208, 148, 208, 176, 32, 208, 156, 209, 131, 32, 208, 149, 208,
+ 177, 208, 176, 32, 208, 156, 208, 176, 208, 185, 208, 186, 208,
+ 176, 209, 130, 208, 176>>
+].
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/unescaped_bulgarian.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/unescaped_bulgarian.json b/src/jiffy/test/cases/unescaped_bulgarian.json
new file mode 100644
index 0000000..f9a70a6
--- /dev/null
+++ b/src/jiffy/test/cases/unescaped_bulgarian.json
@@ -0,0 +1 @@
+["Да Му Еба Майката"]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/etap.erl
----------------------------------------------------------------------
diff --git a/src/jiffy/test/etap.erl b/src/jiffy/test/etap.erl
new file mode 100644
index 0000000..6924d09
--- /dev/null
+++ b/src/jiffy/test/etap.erl
@@ -0,0 +1,612 @@
+%% Copyright (c) 2008-2009 Nick Gerakines <ni...@gerakines.net>
+%%
+%% Permission is hereby granted, free of charge, to any person
+%% obtaining a copy of this software and associated documentation
+%% files (the "Software"), to deal in the Software without
+%% restriction, including without limitation the rights to use,
+%% copy, modify, merge, publish, distribute, sublicense, and/or sell
+%% copies of the Software, and to permit persons to whom the
+%% Software is furnished to do so, subject to the following
+%% conditions:
+%%
+%% The above copyright notice and this permission notice shall be
+%% included in all copies or substantial portions of the Software.
+%%
+%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+%% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+%% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+%% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+%% OTHER DEALINGS IN THE SOFTWARE.
+%%
+%% @author Nick Gerakines <ni...@gerakines.net> [http://socklabs.com/]
+%% @author Jeremy Wall <je...@marzhillstudios.com>
+%% @version 0.3.4
+%% @copyright 2007-2008 Jeremy Wall, 2008-2009 Nick Gerakines
+%% @reference http://testanything.org/wiki/index.php/Main_Page
+%% @reference http://en.wikipedia.org/wiki/Test_Anything_Protocol
+%% @todo Finish implementing the skip directive.
+%% @todo Document the messages handled by this receive loop.
+%% @todo Explain in documentation why we use a process to handle test input.
+%% @doc etap is a TAP testing module for Erlang components and applications.
+%% This module allows developers to test their software using the TAP method.
+%%
+%% <blockquote cite="http://en.wikipedia.org/wiki/Test_Anything_Protocol"><p>
+%% TAP, the Test Anything Protocol, is a simple text-based interface between
+%% testing modules in a test harness. TAP started life as part of the test
+%% harness for Perl but now has implementations in C/C++, Python, PHP, Perl
+%% and probably others by the time you read this.
+%% </p></blockquote>
+%%
+%% The testing process begins by defining a plan using etap:plan/1, running
+%% a number of etap tests and then calling eta:end_tests/0. Please refer to
+%% the Erlang modules in the t directory of this project for example tests.
+-module(etap).
+-vsn("0.3.4").
+
+-export([
+ ensure_test_server/0,
+ start_etap_server/0,
+ test_server/1,
+ msg/1, msg/2,
+ diag/1, diag/2,
+ expectation_mismatch_message/3,
+ plan/1,
+ end_tests/0,
+ not_ok/2, ok/2, is_ok/2, is/3, isnt/3, any/3, none/3,
+ fun_is/3, expect_fun/3, expect_fun/4,
+ is_greater/3,
+ skip/1, skip/2,
+ datetime/1,
+ skip/3,
+ bail/0, bail/1,
+ test_state/0, failure_count/0
+]).
+
+-export([
+ contains_ok/3,
+ is_before/4
+]).
+
+-export([
+ is_pid/2,
+ is_alive/2,
+ is_mfa/3
+]).
+
+-export([
+ loaded_ok/2,
+ can_ok/2, can_ok/3,
+ has_attrib/2, is_attrib/3,
+ is_behaviour/2
+]).
+
+-export([
+ dies_ok/2,
+ lives_ok/2,
+ throws_ok/3
+]).
+
+
+-record(test_state, {
+ planned = 0,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+}).
+
+%% @spec plan(N) -> Result
+%% N = unknown | skip | {skip, string()} | integer()
+%% Result = ok
+%% @doc Create a test plan and boot strap the test server.
+plan(unknown) ->
+ ensure_test_server(),
+ etap_server ! {self(), plan, unknown},
+ ok;
+plan(skip) ->
+ io:format("1..0 # skip~n");
+plan({skip, Reason}) ->
+ io:format("1..0 # skip ~s~n", [Reason]);
+plan(N) when is_integer(N), N > 0 ->
+ ensure_test_server(),
+ etap_server ! {self(), plan, N},
+ ok.
+
+%% @spec end_tests() -> ok
+%% @doc End the current test plan and output test results.
+%% @todo This should probably be done in the test_server process.
+end_tests() ->
+ case whereis(etap_server) of
+ undefined -> self() ! true;
+ _ -> etap_server ! {self(), state}
+ end,
+ State = receive X -> X end,
+ if
+ State#test_state.planned == -1 ->
+ io:format("1..~p~n", [State#test_state.count]);
+ true ->
+ ok
+ end,
+ case whereis(etap_server) of
+ undefined -> ok;
+ _ -> etap_server ! done, ok
+ end.
+
+bail() ->
+ bail("").
+
+bail(Reason) ->
+ etap_server ! {self(), diag, "Bail out! " ++ Reason},
+ etap_server ! done, ok,
+ ok.
+
+%% @spec test_state() -> Return
+%% Return = test_state_record() | {error, string()}
+%% @doc Return the current test state
+test_state() ->
+ etap_server ! {self(), state},
+ receive
+ X when is_record(X, test_state) -> X
+ after
+ 1000 -> {error, "Timed out waiting for etap server reply.~n"}
+ end.
+
+%% @spec failure_count() -> Return
+%% Return = integer() | {error, string()}
+%% @doc Return the current failure count
+failure_count() ->
+ case test_state() of
+ #test_state{fail=FailureCount} -> FailureCount;
+ X -> X
+ end.
+
+%% @spec msg(S) -> ok
+%% S = string()
+%% @doc Print a message in the test output.
+msg(S) -> etap_server ! {self(), diag, S}, ok.
+
+%% @spec msg(Format, Data) -> ok
+%% Format = atom() | string() | binary()
+%% Data = [term()]
+%% UnicodeList = [Unicode]
+%% Unicode = int()
+%% @doc Print a message in the test output.
+%% Function arguments are passed through io_lib:format/2.
+msg(Format, Data) -> msg(io_lib:format(Format, Data)).
+
+%% @spec diag(S) -> ok
+%% S = string()
+%% @doc Print a debug/status message related to the test suite.
+diag(S) -> msg("# " ++ S).
+
+%% @spec diag(Format, Data) -> ok
+%% Format = atom() | string() | binary()
+%% Data = [term()]
+%% UnicodeList = [Unicode]
+%% Unicode = int()
+%% @doc Print a debug/status message related to the test suite.
+%% Function arguments are passed through io_lib:format/2.
+diag(Format, Data) -> diag(io_lib:format(Format, Data)).
+
+%% @spec expectation_mismatch_message(Got, Expected, Desc) -> ok
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% @doc Print an expectation mismatch message in the test output.
+expectation_mismatch_message(Got, Expected, Desc) ->
+ msg(" ---"),
+ msg(" description: ~p", [Desc]),
+ msg(" found: ~p", [Got]),
+ msg(" wanted: ~p", [Expected]),
+ msg(" ..."),
+ ok.
+
+% @spec evaluate(Pass, Got, Expected, Desc) -> Result
+%% Pass = true | false
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Evaluate a test statement, printing an expectation mismatch message
+%% if the test failed.
+evaluate(Pass, Got, Expected, Desc) ->
+ case mk_tap(Pass, Desc) of
+ false ->
+ expectation_mismatch_message(Got, Expected, Desc),
+ false;
+ true ->
+ true
+ end.
+
+%% @spec ok(Expr, Desc) -> Result
+%% Expr = true | false
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that a statement is true.
+ok(Expr, Desc) -> evaluate(Expr == true, Expr, true, Desc).
+
+%% @spec not_ok(Expr, Desc) -> Result
+%% Expr = true | false
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that a statement is false.
+not_ok(Expr, Desc) -> evaluate(Expr == false, Expr, false, Desc).
+
+%% @spec is_ok(Expr, Desc) -> Result
+%% Expr = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that two values are the same.
+is_ok(Expr, Desc) -> evaluate(Expr == ok, Expr, ok, Desc).
+
+%% @spec is(Got, Expected, Desc) -> Result
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that two values are the same.
+is(Got, Expected, Desc) -> evaluate(Got == Expected, Got, Expected, Desc).
+
+%% @spec isnt(Got, Expected, Desc) -> Result
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that two values are not the same.
+isnt(Got, Expected, Desc) -> evaluate(Got /= Expected, Got, Expected, Desc).
+
+%% @spec is_greater(ValueA, ValueB, Desc) -> Result
+%% ValueA = number()
+%% ValueB = number()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that an integer is greater than another.
+is_greater(ValueA, ValueB, Desc) when is_integer(ValueA), is_integer(ValueB) ->
+ mk_tap(ValueA > ValueB, Desc).
+
+%% @spec any(Got, Items, Desc) -> Result
+%% Got = any()
+%% Items = [any()]
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that an item is in a list.
+any(Got, Items, Desc) when is_function(Got) ->
+ is(lists:any(Got, Items), true, Desc);
+any(Got, Items, Desc) ->
+ is(lists:member(Got, Items), true, Desc).
+
+%% @spec none(Got, Items, Desc) -> Result
+%% Got = any()
+%% Items = [any()]
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that an item is not in a list.
+none(Got, Items, Desc) when is_function(Got) ->
+ is(lists:any(Got, Items), false, Desc);
+none(Got, Items, Desc) ->
+ is(lists:member(Got, Items), false, Desc).
+
+%% @spec fun_is(Fun, Expected, Desc) -> Result
+%% Fun = function()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Use an anonymous function to assert a pattern match.
+fun_is(Fun, Expected, Desc) when is_function(Fun) ->
+ is(Fun(Expected), true, Desc).
+
+%% @spec expect_fun(ExpectFun, Got, Desc) -> Result
+%% ExpectFun = function()
+%% Got = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Use an anonymous function to assert a pattern match, using actual
+%% value as the argument to the function.
+expect_fun(ExpectFun, Got, Desc) ->
+ evaluate(ExpectFun(Got), Got, ExpectFun, Desc).
+
+%% @spec expect_fun(ExpectFun, Got, Desc, ExpectStr) -> Result
+%% ExpectFun = function()
+%% Got = any()
+%% Desc = string()
+%% ExpectStr = string()
+%% Result = true | false
+%% @doc Use an anonymous function to assert a pattern match, using actual
+%% value as the argument to the function.
+expect_fun(ExpectFun, Got, Desc, ExpectStr) ->
+ evaluate(ExpectFun(Got), Got, ExpectStr, Desc).
+
+%% @equiv skip(TestFun, "")
+skip(TestFun) when is_function(TestFun) ->
+ skip(TestFun, "").
+
+%% @spec skip(TestFun, Reason) -> ok
+%% TestFun = function()
+%% Reason = string()
+%% @doc Skip a test.
+skip(TestFun, Reason) when is_function(TestFun), is_list(Reason) ->
+ begin_skip(Reason),
+ catch TestFun(),
+ end_skip(),
+ ok.
+
+%% @spec skip(Q, TestFun, Reason) -> ok
+%% Q = true | false | function()
+%% TestFun = function()
+%% Reason = string()
+%% @doc Skips a test conditionally. The first argument to this function can
+%% either be the 'true' or 'false' atoms or a function that returns 'true' or
+%% 'false'.
+skip(QFun, TestFun, Reason) when is_function(QFun), is_function(TestFun), is_list(Reason) ->
+ case QFun() of
+ true -> begin_skip(Reason), TestFun(), end_skip();
+ _ -> TestFun()
+ end,
+ ok;
+
+skip(Q, TestFun, Reason) when is_function(TestFun), is_list(Reason), Q == true ->
+ begin_skip(Reason),
+ TestFun(),
+ end_skip(),
+ ok;
+
+skip(_, TestFun, Reason) when is_function(TestFun), is_list(Reason) ->
+ TestFun(),
+ ok.
+
+%% @private
+begin_skip(Reason) ->
+ etap_server ! {self(), begin_skip, Reason}.
+
+%% @private
+end_skip() ->
+ etap_server ! {self(), end_skip}.
+
+%% @spec contains_ok(string(), string(), string()) -> true | false
+%% @doc Assert that a string is contained in another string.
+contains_ok(Source, String, Desc) ->
+ etap:isnt(
+ string:str(Source, String),
+ 0,
+ Desc
+ ).
+
+%% @spec is_before(string(), string(), string(), string()) -> true | false
+%% @doc Assert that a string comes before another string within a larger body.
+is_before(Source, StringA, StringB, Desc) ->
+ etap:is_greater(
+ string:str(Source, StringB),
+ string:str(Source, StringA),
+ Desc
+ ).
+
+%% @doc Assert that a given variable is a pid.
+is_pid(Pid, Desc) when is_pid(Pid) -> etap:ok(true, Desc);
+is_pid(_, Desc) -> etap:ok(false, Desc).
+
+%% @doc Assert that a given process/pid is alive.
+is_alive(Pid, Desc) ->
+ etap:ok(erlang:is_process_alive(Pid), Desc).
+
+%% @doc Assert that the current function of a pid is a given {M, F, A} tuple.
+is_mfa(Pid, MFA, Desc) ->
+ etap:is({current_function, MFA}, erlang:process_info(Pid, current_function), Desc).
+
+%% @spec loaded_ok(atom(), string()) -> true | false
+%% @doc Assert that a module has been loaded successfully.
+loaded_ok(M, Desc) when is_atom(M) ->
+ etap:fun_is(fun({module, _}) -> true; (_) -> false end, code:load_file(M), Desc).
+
+%% @spec can_ok(atom(), atom()) -> true | false
+%% @doc Assert that a module exports a given function.
+can_ok(M, F) when is_atom(M), is_atom(F) ->
+ Matches = [X || {X, _} <- M:module_info(exports), X == F],
+ etap:ok(Matches > 0, lists:concat([M, " can ", F])).
+
+%% @spec can_ok(atom(), atom(), integer()) -> true | false
+%% @doc Assert that a module exports a given function with a given arity.
+can_ok(M, F, A) when is_atom(M); is_atom(F), is_number(A) ->
+ Matches = [X || X <- M:module_info(exports), X == {F, A}],
+ etap:ok(Matches > 0, lists:concat([M, " can ", F, "/", A])).
+
+%% @spec has_attrib(M, A) -> true | false
+%% M = atom()
+%% A = atom()
+%% @doc Asserts that a module has a given attribute.
+has_attrib(M, A) when is_atom(M), is_atom(A) ->
+ etap:isnt(
+ proplists:get_value(A, M:module_info(attributes), 'asdlkjasdlkads'),
+ 'asdlkjasdlkads',
+ lists:concat([M, " has attribute ", A])
+ ).
+
+%% @spec has_attrib(M, A. V) -> true | false
+%% M = atom()
+%% A = atom()
+%% V = any()
+%% @doc Asserts that a module has a given attribute with a given value.
+is_attrib(M, A, V) when is_atom(M) andalso is_atom(A) ->
+ etap:is(
+ proplists:get_value(A, M:module_info(attributes)),
+ [V],
+ lists:concat([M, "'s ", A, " is ", V])
+ ).
+
+%% @spec is_behavior(M, B) -> true | false
+%% M = atom()
+%% B = atom()
+%% @doc Asserts that a given module has a specific behavior.
+is_behaviour(M, B) when is_atom(M) andalso is_atom(B) ->
+ is_attrib(M, behaviour, B).
+
+%% @doc Assert that an exception is raised when running a given function.
+dies_ok(F, Desc) ->
+ case (catch F()) of
+ {'EXIT', _} -> etap:ok(true, Desc);
+ _ -> etap:ok(false, Desc)
+ end.
+
+%% @doc Assert that an exception is not raised when running a given function.
+lives_ok(F, Desc) ->
+ etap:is(try_this(F), success, Desc).
+
+%% @doc Assert that the exception thrown by a function matches the given exception.
+throws_ok(F, Exception, Desc) ->
+ try F() of
+ _ -> etap:ok(nok, Desc)
+ catch
+ _:E ->
+ etap:is(E, Exception, Desc)
+ end.
+
+%% @private
+%% @doc Run a function and catch any exceptions.
+try_this(F) when is_function(F, 0) ->
+ try F() of
+ _ -> success
+ catch
+ throw:E -> {throw, E};
+ error:E -> {error, E};
+ exit:E -> {exit, E}
+ end.
+
+%% @private
+%% @doc Start the etap_server process if it is not running already.
+ensure_test_server() ->
+ case whereis(etap_server) of
+ undefined ->
+ proc_lib:start(?MODULE, start_etap_server,[]);
+ _ ->
+ diag("The test server is already running.")
+ end.
+
+%% @private
+%% @doc Start the etap_server loop and register itself as the etap_server
+%% process.
+start_etap_server() ->
+ catch register(etap_server, self()),
+ proc_lib:init_ack(ok),
+ etap:test_server(#test_state{
+ planned = 0,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+ }).
+
+
+%% @private
+%% @doc The main etap_server receive/run loop. The etap_server receive loop
+%% responds to seven messages apperatining to failure or passing of tests.
+%% It is also used to initiate the testing process with the {_, plan, _}
+%% message that clears the current test state.
+test_server(State) ->
+ NewState = receive
+ {_From, plan, unknown} ->
+ io:format("# Current time local ~s~n", [datetime(erlang:localtime())]),
+ io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]),
+ State#test_state{
+ planned = -1,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+ };
+ {_From, plan, N} ->
+ io:format("# Current time local ~s~n", [datetime(erlang:localtime())]),
+ io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]),
+ io:format("1..~p~n", [N]),
+ State#test_state{
+ planned = N,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+ };
+ {_From, begin_skip, Reason} ->
+ State#test_state{
+ skip = 1,
+ skip_reason = Reason
+ };
+ {_From, end_skip} ->
+ State#test_state{
+ skip = 0,
+ skip_reason = ""
+ };
+ {_From, pass, Desc} ->
+ FullMessage = skip_diag(
+ " - " ++ Desc,
+ State#test_state.skip,
+ State#test_state.skip_reason
+ ),
+ io:format("ok ~p ~s~n", [State#test_state.count + 1, FullMessage]),
+ State#test_state{
+ count = State#test_state.count + 1,
+ pass = State#test_state.pass + 1
+ };
+
+ {_From, fail, Desc} ->
+ FullMessage = skip_diag(
+ " - " ++ Desc,
+ State#test_state.skip,
+ State#test_state.skip_reason
+ ),
+ io:format("not ok ~p ~s~n", [State#test_state.count + 1, FullMessage]),
+ State#test_state{
+ count = State#test_state.count + 1,
+ fail = State#test_state.fail + 1
+ };
+ {From, state} ->
+ From ! State,
+ State;
+ {_From, diag, Message} ->
+ io:format("~s~n", [Message]),
+ State;
+ {From, count} ->
+ From ! State#test_state.count,
+ State;
+ {From, is_skip} ->
+ From ! State#test_state.skip,
+ State;
+ done ->
+ exit(normal)
+ end,
+ test_server(NewState).
+
+%% @private
+%% @doc Process the result of a test and send it to the etap_server process.
+mk_tap(Result, Desc) ->
+ IsSkip = lib:sendw(etap_server, is_skip),
+ case [IsSkip, Result] of
+ [_, true] ->
+ etap_server ! {self(), pass, Desc},
+ true;
+ [1, _] ->
+ etap_server ! {self(), pass, Desc},
+ true;
+ _ ->
+ etap_server ! {self(), fail, Desc},
+ false
+ end.
+
+%% @private
+%% @doc Format a date/time string.
+datetime(DateTime) ->
+ {{Year, Month, Day}, {Hour, Min, Sec}} = DateTime,
+ io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Year, Month, Day, Hour, Min, Sec]).
+
+%% @private
+%% @doc Craft an output message taking skip/todo into consideration.
+skip_diag(Message, 0, _) ->
+ Message;
+skip_diag(_Message, 1, "") ->
+ " # SKIP";
+skip_diag(_Message, 1, Reason) ->
+ " # SKIP : " ++ Reason.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/jiffy_tests.erl
----------------------------------------------------------------------
diff --git a/src/jiffy/test/jiffy_tests.erl b/src/jiffy/test/jiffy_tests.erl
new file mode 100644
index 0000000..0655b0d
--- /dev/null
+++ b/src/jiffy/test/jiffy_tests.erl
@@ -0,0 +1,135 @@
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+-module(jiffy_tests).
+
+-ifdef(JIFFY_DEV).
+
+-include_lib("proper/include/proper.hrl").
+-include_lib("eunit/include/eunit.hrl").
+
+
+proper_test_() ->
+ PropErOpts = [
+ {to_file, user},
+ {max_size, 15},
+ {numtests, 1000}
+ ],
+ {timeout, 3600, ?_assertEqual([], proper:module(jiffy_tests, PropErOpts))}.
+
+
+prop_encode_decode() ->
+ ?FORALL(Data, json(),
+ begin
+ %io:format(standard_error, "Data: ~p~n", [Data]),
+ Data == jiffy:decode(jiffy:encode(Data))
+ end
+ ).
+
+prop_encode_decode_pretty() ->
+ ?FORALL(Data, json(),
+ begin
+ Data == jiffy:decode(jiffy:encode(Data, [pretty]))
+ end
+ ).
+
+prop_encode_not_crash() ->
+ ?FORALL(Data, any(), begin catch jiffy:encode(Data), true end).
+
+prop_decode_not_crash_bin() ->
+ ?FORALL(Data, binary(), begin catch jiffy:decode(Data), true end).
+
+prop_decode_not_crash_any() ->
+ ?FORALL(Data, any(), begin catch jiffy:decode(Data), true end).
+
+
+% JSON Generation
+
+
+json_null() ->
+ null.
+
+
+json_boolean() ->
+ oneof([true, false]).
+
+
+json_number() ->
+ oneof([integer(), float()]).
+
+
+json_string() ->
+ escaped_utf8_bin().
+
+
+json_list(S) when S =< 0 ->
+ [];
+json_list(S) ->
+ ?LETSHRINK(
+ [ListSize],
+ [integer(0, S)],
+ vector(ListSize, json_text(S - ListSize))
+ ).
+
+
+json_object(S) when S =< 0 ->
+ {[]};
+json_object(S) ->
+ ?LETSHRINK(
+ [ObjectSize],
+ [integer(0, S)],
+ {vector(ObjectSize, {json_string(), json_text(S - ObjectSize)})}
+ ).
+
+
+json_value() ->
+ oneof([
+ json_null(),
+ json_boolean(),
+ json_string(),
+ json_number()
+ ]).
+
+
+json_text(S) when S > 0 ->
+ ?LAZY(oneof([
+ json_list(S),
+ json_object(S)
+ ]));
+json_text(_) ->
+ json_value().
+
+
+json() ->
+ ?SIZED(S, json_text(S)).
+
+
+%% XXX: Add generators
+%
+% We should add generators that generate JSON binaries directly
+% so we can test things that aren't produced by the encoder.
+%
+% We should also have a version of the JSON generator that inserts
+% errors into the JSON that we can test for.
+
+
+escaped_utf8_bin() ->
+ ?SUCHTHAT(Bin,
+ ?LET(S, ?SUCHTHAT(L, list(escaped_char()), L /= []),
+ unicode:characters_to_binary(S, unicode, utf8)),
+ is_binary(Bin)
+ ).
+
+
+escaped_char() ->
+ ?LET(C, char(),
+ case C of
+ $" -> "\\\"";
+ C when C == 65534 -> 65533;
+ C when C == 65535 -> 65533;
+ C when C > 1114111 -> 1114111;
+ C -> C
+ end
+ ).
+
+-endif.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/util.erl
----------------------------------------------------------------------
diff --git a/src/jiffy/test/util.erl b/src/jiffy/test/util.erl
new file mode 100644
index 0000000..ceaef89
--- /dev/null
+++ b/src/jiffy/test/util.erl
@@ -0,0 +1,44 @@
+-module(util).
+-export([test_good/1, test_good/2, test_errors/1]).
+
+test_good(Cases) ->
+ test_good(Cases, []).
+
+test_good(Cases, Options) ->
+ lists:foreach(fun(Case) -> check_good(Case, Options) end, Cases).
+
+test_errors(Cases) ->
+ lists:foreach(fun(Case) -> check_error(Case) end, Cases).
+
+ok_dec(J, _E) ->
+ lists:flatten(io_lib:format("Decoded ~p.", [J])).
+
+ok_enc(E, _J) ->
+ lists:flatten(io_lib:format("Encoded ~p", [E])).
+
+do_encode(E, Options) ->
+ iolist_to_binary(jiffy:encode(E, Options)).
+
+error_mesg(J) ->
+ lists:flatten(io_lib:format("Decoding ~p returns an error.", [J])).
+
+check_good({J, E}, Options) ->
+ etap:is(jiffy:decode(J), E, ok_dec(J, E)),
+ etap:is(do_encode(E, Options), J, ok_enc(E, J));
+check_good({J, E, J2}, Options) ->
+ etap:is(jiffy:decode(J), E, ok_dec(J, E)),
+ etap:is(do_encode(E, Options), J2, ok_enc(E, J2)).
+
+check_error({J, E}) ->
+ etap:fun_is(
+ fun({error, E1}) when E1 == E -> true; (E1) -> E1 end,
+ (catch jiffy:decode(J)),
+ error_mesg(J)
+ );
+check_error(J) ->
+ etap:fun_is(
+ fun({error, _}) -> true; (Else) -> Else end,
+ (catch jiffy:decode(J)),
+ error_mesg(J)
+ ).
+
[06/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/strtod.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/strtod.cc b/src/jiffy/c_src/double-conversion/strtod.cc
new file mode 100644
index 0000000..9758989
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/strtod.cc
@@ -0,0 +1,554 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <stdarg.h>
+#include <limits.h>
+
+#include "strtod.h"
+#include "bignum.h"
+#include "cached-powers.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+// 2^53 = 9007199254740992.
+// Any integer with at most 15 decimal digits will hence fit into a double
+// (which has a 53bit significand) without loss of precision.
+static const int kMaxExactDoubleIntegerDecimalDigits = 15;
+// 2^64 = 18446744073709551616 > 10^19
+static const int kMaxUint64DecimalDigits = 19;
+
+// Max double: 1.7976931348623157 x 10^308
+// Min non-zero double: 4.9406564584124654 x 10^-324
+// Any x >= 10^309 is interpreted as +infinity.
+// Any x <= 10^-324 is interpreted as 0.
+// Note that 2.5e-324 (despite being smaller than the min double) will be read
+// as non-zero (equal to the min non-zero double).
+static const int kMaxDecimalPower = 309;
+static const int kMinDecimalPower = -324;
+
+// 2^64 = 18446744073709551616
+static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
+
+
+static const double exact_powers_of_ten[] = {
+ 1.0, // 10^0
+ 10.0,
+ 100.0,
+ 1000.0,
+ 10000.0,
+ 100000.0,
+ 1000000.0,
+ 10000000.0,
+ 100000000.0,
+ 1000000000.0,
+ 10000000000.0, // 10^10
+ 100000000000.0,
+ 1000000000000.0,
+ 10000000000000.0,
+ 100000000000000.0,
+ 1000000000000000.0,
+ 10000000000000000.0,
+ 100000000000000000.0,
+ 1000000000000000000.0,
+ 10000000000000000000.0,
+ 100000000000000000000.0, // 10^20
+ 1000000000000000000000.0,
+ // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
+ 10000000000000000000000.0
+};
+static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
+
+// Maximum number of significant digits in the decimal representation.
+// In fact the value is 772 (see conversions.cc), but to give us some margin
+// we round up to 780.
+static const int kMaxSignificantDecimalDigits = 780;
+
+static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
+ for (int i = 0; i < buffer.length(); i++) {
+ if (buffer[i] != '0') {
+ return buffer.SubVector(i, buffer.length());
+ }
+ }
+ return Vector<const char>(buffer.start(), 0);
+}
+
+
+static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
+ for (int i = buffer.length() - 1; i >= 0; --i) {
+ if (buffer[i] != '0') {
+ return buffer.SubVector(0, i + 1);
+ }
+ }
+ return Vector<const char>(buffer.start(), 0);
+}
+
+
+static void CutToMaxSignificantDigits(Vector<const char> buffer,
+ int exponent,
+ char* significant_buffer,
+ int* significant_exponent) {
+ for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
+ significant_buffer[i] = buffer[i];
+ }
+ // The input buffer has been trimmed. Therefore the last digit must be
+ // different from '0'.
+ ASSERT(buffer[buffer.length() - 1] != '0');
+ // Set the last digit to be non-zero. This is sufficient to guarantee
+ // correct rounding.
+ significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
+ *significant_exponent =
+ exponent + (buffer.length() - kMaxSignificantDecimalDigits);
+}
+
+
+// Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits.
+// If possible the input-buffer is reused, but if the buffer needs to be
+// modified (due to cutting), then the input needs to be copied into the
+// buffer_copy_space.
+static void TrimAndCut(Vector<const char> buffer, int exponent,
+ char* buffer_copy_space, int space_size,
+ Vector<const char>* trimmed, int* updated_exponent) {
+ Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
+ Vector<const char> right_trimmed = TrimTrailingZeros(left_trimmed);
+ exponent += left_trimmed.length() - right_trimmed.length();
+ if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
+ ASSERT(space_size >= kMaxSignificantDecimalDigits);
+ CutToMaxSignificantDigits(right_trimmed, exponent,
+ buffer_copy_space, updated_exponent);
+ *trimmed = Vector<const char>(buffer_copy_space,
+ kMaxSignificantDecimalDigits);
+ } else {
+ *trimmed = right_trimmed;
+ *updated_exponent = exponent;
+ }
+}
+
+
+// Reads digits from the buffer and converts them to a uint64.
+// Reads in as many digits as fit into a uint64.
+// When the string starts with "1844674407370955161" no further digit is read.
+// Since 2^64 = 18446744073709551616 it would still be possible read another
+// digit if it was less or equal than 6, but this would complicate the code.
+static uint64_t ReadUint64(Vector<const char> buffer,
+ int* number_of_read_digits) {
+ uint64_t result = 0;
+ int i = 0;
+ while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
+ int digit = buffer[i++] - '0';
+ ASSERT(0 <= digit && digit <= 9);
+ result = 10 * result + digit;
+ }
+ *number_of_read_digits = i;
+ return result;
+}
+
+
+// Reads a DiyFp from the buffer.
+// The returned DiyFp is not necessarily normalized.
+// If remaining_decimals is zero then the returned DiyFp is accurate.
+// Otherwise it has been rounded and has error of at most 1/2 ulp.
+static void ReadDiyFp(Vector<const char> buffer,
+ DiyFp* result,
+ int* remaining_decimals) {
+ int read_digits;
+ uint64_t significand = ReadUint64(buffer, &read_digits);
+ if (buffer.length() == read_digits) {
+ *result = DiyFp(significand, 0);
+ *remaining_decimals = 0;
+ } else {
+ // Round the significand.
+ if (buffer[read_digits] >= '5') {
+ significand++;
+ }
+ // Compute the binary exponent.
+ int exponent = 0;
+ *result = DiyFp(significand, exponent);
+ *remaining_decimals = buffer.length() - read_digits;
+ }
+}
+
+
+static bool DoubleStrtod(Vector<const char> trimmed,
+ int exponent,
+ double* result) {
+#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
+ // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
+ // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
+ // result is not accurate.
+ // We know that Windows32 uses 64 bits and is therefore accurate.
+ // Note that the ARM simulator is compiled for 32bits. It therefore exhibits
+ // the same problem.
+ return false;
+#endif
+ if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
+ int read_digits;
+ // The trimmed input fits into a double.
+ // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
+ // can compute the result-double simply by multiplying (resp. dividing) the
+ // two numbers.
+ // This is possible because IEEE guarantees that floating-point operations
+ // return the best possible approximation.
+ if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
+ // 10^-exponent fits into a double.
+ *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
+ ASSERT(read_digits == trimmed.length());
+ *result /= exact_powers_of_ten[-exponent];
+ return true;
+ }
+ if (0 <= exponent && exponent < kExactPowersOfTenSize) {
+ // 10^exponent fits into a double.
+ *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
+ ASSERT(read_digits == trimmed.length());
+ *result *= exact_powers_of_ten[exponent];
+ return true;
+ }
+ int remaining_digits =
+ kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
+ if ((0 <= exponent) &&
+ (exponent - remaining_digits < kExactPowersOfTenSize)) {
+ // The trimmed string was short and we can multiply it with
+ // 10^remaining_digits. As a result the remaining exponent now fits
+ // into a double too.
+ *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
+ ASSERT(read_digits == trimmed.length());
+ *result *= exact_powers_of_ten[remaining_digits];
+ *result *= exact_powers_of_ten[exponent - remaining_digits];
+ return true;
+ }
+ }
+ return false;
+}
+
+
+// Returns 10^exponent as an exact DiyFp.
+// The given exponent must be in the range [1; kDecimalExponentDistance[.
+static DiyFp AdjustmentPowerOfTen(int exponent) {
+ ASSERT(0 < exponent);
+ ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
+ // Simply hardcode the remaining powers for the given decimal exponent
+ // distance.
+ ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
+ switch (exponent) {
+ case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60);
+ case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57);
+ case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54);
+ case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50);
+ case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47);
+ case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44);
+ case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40);
+ default:
+ UNREACHABLE();
+ return DiyFp(0, 0);
+ }
+}
+
+
+// If the function returns true then the result is the correct double.
+// Otherwise it is either the correct double or the double that is just below
+// the correct double.
+static bool DiyFpStrtod(Vector<const char> buffer,
+ int exponent,
+ double* result) {
+ DiyFp input;
+ int remaining_decimals;
+ ReadDiyFp(buffer, &input, &remaining_decimals);
+ // Since we may have dropped some digits the input is not accurate.
+ // If remaining_decimals is different than 0 than the error is at most
+ // .5 ulp (unit in the last place).
+ // We don't want to deal with fractions and therefore keep a common
+ // denominator.
+ const int kDenominatorLog = 3;
+ const int kDenominator = 1 << kDenominatorLog;
+ // Move the remaining decimals into the exponent.
+ exponent += remaining_decimals;
+ int error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
+
+ int old_e = input.e();
+ input.Normalize();
+ error <<= old_e - input.e();
+
+ ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
+ if (exponent < PowersOfTenCache::kMinDecimalExponent) {
+ *result = 0.0;
+ return true;
+ }
+ DiyFp cached_power;
+ int cached_decimal_exponent;
+ PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
+ &cached_power,
+ &cached_decimal_exponent);
+
+ if (cached_decimal_exponent != exponent) {
+ int adjustment_exponent = exponent - cached_decimal_exponent;
+ DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
+ input.Multiply(adjustment_power);
+ if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
+ // The product of input with the adjustment power fits into a 64 bit
+ // integer.
+ ASSERT(DiyFp::kSignificandSize == 64);
+ } else {
+ // The adjustment power is exact. There is hence only an error of 0.5.
+ error += kDenominator / 2;
+ }
+ }
+
+ input.Multiply(cached_power);
+ // The error introduced by a multiplication of a*b equals
+ // error_a + error_b + error_a*error_b/2^64 + 0.5
+ // Substituting a with 'input' and b with 'cached_power' we have
+ // error_b = 0.5 (all cached powers have an error of less than 0.5 ulp),
+ // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
+ int error_b = kDenominator / 2;
+ int error_ab = (error == 0 ? 0 : 1); // We round up to 1.
+ int fixed_error = kDenominator / 2;
+ error += error_b + error_ab + fixed_error;
+
+ old_e = input.e();
+ input.Normalize();
+ error <<= old_e - input.e();
+
+ // See if the double's significand changes if we add/subtract the error.
+ int order_of_magnitude = DiyFp::kSignificandSize + input.e();
+ int effective_significand_size =
+ Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
+ int precision_digits_count =
+ DiyFp::kSignificandSize - effective_significand_size;
+ if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
+ // This can only happen for very small denormals. In this case the
+ // half-way multiplied by the denominator exceeds the range of an uint64.
+ // Simply shift everything to the right.
+ int shift_amount = (precision_digits_count + kDenominatorLog) -
+ DiyFp::kSignificandSize + 1;
+ input.set_f(input.f() >> shift_amount);
+ input.set_e(input.e() + shift_amount);
+ // We add 1 for the lost precision of error, and kDenominator for
+ // the lost precision of input.f().
+ error = (error >> shift_amount) + 1 + kDenominator;
+ precision_digits_count -= shift_amount;
+ }
+ // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
+ ASSERT(DiyFp::kSignificandSize == 64);
+ ASSERT(precision_digits_count < 64);
+ uint64_t one64 = 1;
+ uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
+ uint64_t precision_bits = input.f() & precision_bits_mask;
+ uint64_t half_way = one64 << (precision_digits_count - 1);
+ precision_bits *= kDenominator;
+ half_way *= kDenominator;
+ DiyFp rounded_input(input.f() >> precision_digits_count,
+ input.e() + precision_digits_count);
+ if (precision_bits >= half_way + error) {
+ rounded_input.set_f(rounded_input.f() + 1);
+ }
+ // If the last_bits are too close to the half-way case than we are too
+ // inaccurate and round down. In this case we return false so that we can
+ // fall back to a more precise algorithm.
+
+ *result = Double(rounded_input).value();
+ if (half_way - error < precision_bits && precision_bits < half_way + error) {
+ // Too imprecise. The caller will have to fall back to a slower version.
+ // However the returned number is guaranteed to be either the correct
+ // double, or the next-lower double.
+ return false;
+ } else {
+ return true;
+ }
+}
+
+
+// Returns
+// - -1 if buffer*10^exponent < diy_fp.
+// - 0 if buffer*10^exponent == diy_fp.
+// - +1 if buffer*10^exponent > diy_fp.
+// Preconditions:
+// buffer.length() + exponent <= kMaxDecimalPower + 1
+// buffer.length() + exponent > kMinDecimalPower
+// buffer.length() <= kMaxDecimalSignificantDigits
+static int CompareBufferWithDiyFp(Vector<const char> buffer,
+ int exponent,
+ DiyFp diy_fp) {
+ ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
+ ASSERT(buffer.length() + exponent > kMinDecimalPower);
+ ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
+ // Make sure that the Bignum will be able to hold all our numbers.
+ // Our Bignum implementation has a separate field for exponents. Shifts will
+ // consume at most one bigit (< 64 bits).
+ // ln(10) == 3.3219...
+ ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
+ Bignum buffer_bignum;
+ Bignum diy_fp_bignum;
+ buffer_bignum.AssignDecimalString(buffer);
+ diy_fp_bignum.AssignUInt64(diy_fp.f());
+ if (exponent >= 0) {
+ buffer_bignum.MultiplyByPowerOfTen(exponent);
+ } else {
+ diy_fp_bignum.MultiplyByPowerOfTen(-exponent);
+ }
+ if (diy_fp.e() > 0) {
+ diy_fp_bignum.ShiftLeft(diy_fp.e());
+ } else {
+ buffer_bignum.ShiftLeft(-diy_fp.e());
+ }
+ return Bignum::Compare(buffer_bignum, diy_fp_bignum);
+}
+
+
+// Returns true if the guess is the correct double.
+// Returns false, when guess is either correct or the next-lower double.
+static bool ComputeGuess(Vector<const char> trimmed, int exponent,
+ double* guess) {
+ if (trimmed.length() == 0) {
+ *guess = 0.0;
+ return true;
+ }
+ if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) {
+ *guess = Double::Infinity();
+ return true;
+ }
+ if (exponent + trimmed.length() <= kMinDecimalPower) {
+ *guess = 0.0;
+ return true;
+ }
+
+ if (DoubleStrtod(trimmed, exponent, guess) ||
+ DiyFpStrtod(trimmed, exponent, guess)) {
+ return true;
+ }
+ if (*guess == Double::Infinity()) {
+ return true;
+ }
+ return false;
+}
+
+double Strtod(Vector<const char> buffer, int exponent) {
+ char copy_buffer[kMaxSignificantDecimalDigits];
+ Vector<const char> trimmed;
+ int updated_exponent;
+ TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
+ &trimmed, &updated_exponent);
+ exponent = updated_exponent;
+
+ double guess;
+ bool is_correct = ComputeGuess(trimmed, exponent, &guess);
+ if (is_correct) return guess;
+
+ DiyFp upper_boundary = Double(guess).UpperBoundary();
+ int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
+ if (comparison < 0) {
+ return guess;
+ } else if (comparison > 0) {
+ return Double(guess).NextDouble();
+ } else if ((Double(guess).Significand() & 1) == 0) {
+ // Round towards even.
+ return guess;
+ } else {
+ return Double(guess).NextDouble();
+ }
+}
+
+float Strtof(Vector<const char> buffer, int exponent) {
+ char copy_buffer[kMaxSignificantDecimalDigits];
+ Vector<const char> trimmed;
+ int updated_exponent;
+ TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
+ &trimmed, &updated_exponent);
+ exponent = updated_exponent;
+
+ double double_guess;
+ bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
+
+ float float_guess = static_cast<float>(double_guess);
+ if (float_guess == double_guess) {
+ // This shortcut triggers for integer values.
+ return float_guess;
+ }
+
+ // We must catch double-rounding. Say the double has been rounded up, and is
+ // now a boundary of a float, and rounds up again. This is why we have to
+ // look at previous too.
+ // Example (in decimal numbers):
+ // input: 12349
+ // high-precision (4 digits): 1235
+ // low-precision (3 digits):
+ // when read from input: 123
+ // when rounded from high precision: 124.
+ // To do this we simply look at the neigbors of the correct result and see
+ // if they would round to the same float. If the guess is not correct we have
+ // to look at four values (since two different doubles could be the correct
+ // double).
+
+ double double_next = Double(double_guess).NextDouble();
+ double double_previous = Double(double_guess).PreviousDouble();
+
+ float f1 = static_cast<float>(double_previous);
+ float f2 = float_guess;
+ float f3 = static_cast<float>(double_next);
+ float f4;
+ if (is_correct) {
+ f4 = f3;
+ } else {
+ double double_next2 = Double(double_next).NextDouble();
+ f4 = static_cast<float>(double_next2);
+ }
+ ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
+
+ // If the guess doesn't lie near a single-precision boundary we can simply
+ // return its float-value.
+ if (f1 == f4) {
+ return float_guess;
+ }
+
+ ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
+ (f1 == f2 && f2 != f3 && f3 == f4) ||
+ (f1 == f2 && f2 == f3 && f3 != f4));
+
+ // guess and next are the two possible canditates (in the same way that
+ // double_guess was the lower candidate for a double-precision guess).
+ float guess = f1;
+ float next = f4;
+ DiyFp upper_boundary;
+ if (guess == 0.0f) {
+ float min_float = 1e-45f;
+ upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp();
+ } else {
+ upper_boundary = Single(guess).UpperBoundary();
+ }
+ int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
+ if (comparison < 0) {
+ return guess;
+ } else if (comparison > 0) {
+ return next;
+ } else if ((Single(guess).Significand() & 1) == 0) {
+ // Round towards even.
+ return guess;
+ } else {
+ return next;
+ }
+}
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/strtod.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/strtod.h b/src/jiffy/c_src/double-conversion/strtod.h
new file mode 100644
index 0000000..ed0293b
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/strtod.h
@@ -0,0 +1,45 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_STRTOD_H_
+#define DOUBLE_CONVERSION_STRTOD_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+// The buffer must only contain digits in the range [0-9]. It must not
+// contain a dot or a sign. It must not start with '0', and must not be empty.
+double Strtod(Vector<const char> buffer, int exponent);
+
+// The buffer must only contain digits in the range [0-9]. It must not
+// contain a dot or a sign. It must not start with '0', and must not be empty.
+float Strtof(Vector<const char> buffer, int exponent);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_STRTOD_H_
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/utils.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/utils.h b/src/jiffy/c_src/double-conversion/utils.h
new file mode 100644
index 0000000..9ebb9ee
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/utils.h
@@ -0,0 +1,326 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_UTILS_H_
+#define DOUBLE_CONVERSION_UTILS_H_
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <assert.h>
+#ifndef ASSERT
+#define ASSERT(condition) (assert(condition))
+#endif
+#ifndef UNIMPLEMENTED
+#define UNIMPLEMENTED() (abort())
+#endif
+#ifndef UNREACHABLE
+#define UNREACHABLE() (abort())
+#endif
+
+// Double operations detection based on target architecture.
+// Linux uses a 80bit wide floating point stack on x86. This induces double
+// rounding, which in turn leads to wrong results.
+// An easy way to test if the floating-point operations are correct is to
+// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then
+// the result is equal to 89255e-22.
+// The best way to test this, is to create a division-function and to compare
+// the output of the division with the expected result. (Inlining must be
+// disabled.)
+// On Linux,x86 89255e-22 != Div_double(89255.0/1e22)
+#if defined(_M_X64) || defined(__x86_64__) || \
+ defined(__ARMEL__) || defined(__avr32__) || \
+ defined(__hppa__) || defined(__ia64__) || \
+ defined(__mips__) || defined(__powerpc__) || \
+ defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
+ defined(__SH4__) || defined(__alpha__) || \
+ defined(_MIPS_ARCH_MIPS32R2)
+#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
+#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
+#if defined(_WIN32)
+// Windows uses a 64bit wide floating point stack.
+#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
+#else
+#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
+#endif // _WIN32
+#else
+#error Target architecture was not detected as supported by Double-Conversion.
+#endif
+
+
+#if defined(_WIN32) && !defined(__MINGW32__)
+
+typedef signed char int8_t;
+typedef unsigned char uint8_t;
+typedef short int16_t; // NOLINT
+typedef unsigned short uint16_t; // NOLINT
+typedef int int32_t;
+typedef unsigned int uint32_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+// intptr_t and friends are defined in crtdefs.h through stdio.h.
+
+#else
+
+#include <stdint.h>
+
+#endif
+
+// The following macro works on both 32 and 64-bit platforms.
+// Usage: instead of writing 0x1234567890123456
+// write UINT64_2PART_C(0x12345678,90123456);
+#define UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
+
+
+// The expression ARRAY_SIZE(a) is a compile-time constant of type
+// size_t which represents the number of elements of the given
+// array. You should only use ARRAY_SIZE on statically allocated
+// arrays.
+#ifndef ARRAY_SIZE
+#define ARRAY_SIZE(a) \
+ ((sizeof(a) / sizeof(*(a))) / \
+ static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
+#endif
+
+// A macro to disallow the evil copy constructor and operator= functions
+// This should be used in the private: declarations for a class
+#ifndef DISALLOW_COPY_AND_ASSIGN
+#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
+ TypeName(const TypeName&); \
+ void operator=(const TypeName&)
+#endif
+
+// A macro to disallow all the implicit constructors, namely the
+// default constructor, copy constructor and operator= functions.
+//
+// This should be used in the private: declarations for a class
+// that wants to prevent anyone from instantiating it. This is
+// especially useful for classes containing only static methods.
+#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS
+#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
+ TypeName(); \
+ DISALLOW_COPY_AND_ASSIGN(TypeName)
+#endif
+
+namespace double_conversion {
+
+static const int kCharSize = sizeof(char);
+
+// Returns the maximum of the two parameters.
+template <typename T>
+static T Max(T a, T b) {
+ return a < b ? b : a;
+}
+
+
+// Returns the minimum of the two parameters.
+template <typename T>
+static T Min(T a, T b) {
+ return a < b ? a : b;
+}
+
+
+inline int StrLength(const char* string) {
+ size_t length = strlen(string);
+ ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
+ return static_cast<int>(length);
+}
+
+// This is a simplified version of V8's Vector class.
+template <typename T>
+class Vector {
+ public:
+ Vector() : start_(NULL), length_(0) {}
+ Vector(T* data, int length) : start_(data), length_(length) {
+ ASSERT(length == 0 || (length > 0 && data != NULL));
+ }
+
+ // Returns a vector using the same backing storage as this one,
+ // spanning from and including 'from', to but not including 'to'.
+ Vector<T> SubVector(int from, int to) {
+ ASSERT(to <= length_);
+ ASSERT(from < to);
+ ASSERT(0 <= from);
+ return Vector<T>(start() + from, to - from);
+ }
+
+ // Returns the length of the vector.
+ int length() const { return length_; }
+
+ // Returns whether or not the vector is empty.
+ bool is_empty() const { return length_ == 0; }
+
+ // Returns the pointer to the start of the data in the vector.
+ T* start() const { return start_; }
+
+ // Access individual vector elements - checks bounds in debug mode.
+ T& operator[](int index) const {
+ ASSERT(0 <= index && index < length_);
+ return start_[index];
+ }
+
+ T& first() { return start_[0]; }
+
+ T& last() { return start_[length_ - 1]; }
+
+ private:
+ T* start_;
+ int length_;
+};
+
+
+// Helper class for building result strings in a character buffer. The
+// purpose of the class is to use safe operations that checks the
+// buffer bounds on all operations in debug mode.
+class StringBuilder {
+ public:
+ StringBuilder(char* buffer, int size)
+ : buffer_(buffer, size), position_(0) { }
+
+ ~StringBuilder() { if (!is_finalized()) Finalize(); }
+
+ int size() const { return buffer_.length(); }
+
+ // Get the current position in the builder.
+ int position() const {
+ ASSERT(!is_finalized());
+ return position_;
+ }
+
+ // Reset the position.
+ void Reset() { position_ = 0; }
+
+ // Add a single character to the builder. It is not allowed to add
+ // 0-characters; use the Finalize() method to terminate the string
+ // instead.
+ void AddCharacter(char c) {
+ ASSERT(c != '\0');
+ ASSERT(!is_finalized() && position_ < buffer_.length());
+ buffer_[position_++] = c;
+ }
+
+ // Add an entire string to the builder. Uses strlen() internally to
+ // compute the length of the input string.
+ void AddString(const char* s) {
+ AddSubstring(s, StrLength(s));
+ }
+
+ // Add the first 'n' characters of the given string 's' to the
+ // builder. The input string must have enough characters.
+ void AddSubstring(const char* s, int n) {
+ ASSERT(!is_finalized() && position_ + n < buffer_.length());
+ ASSERT(static_cast<size_t>(n) <= strlen(s));
+ memmove(&buffer_[position_], s, n * kCharSize);
+ position_ += n;
+ }
+
+
+ // Add character padding to the builder. If count is non-positive,
+ // nothing is added to the builder.
+ void AddPadding(char c, int count) {
+ for (int i = 0; i < count; i++) {
+ AddCharacter(c);
+ }
+ }
+
+ // Finalize the string by 0-terminating it and returning the buffer.
+ char* Finalize() {
+ ASSERT(!is_finalized() && position_ < buffer_.length());
+ buffer_[position_] = '\0';
+ // Make sure nobody managed to add a 0-character to the
+ // buffer while building the string.
+ ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
+ position_ = -1;
+ ASSERT(is_finalized());
+ return buffer_.start();
+ }
+
+ private:
+ Vector<char> buffer_;
+ int position_;
+
+ bool is_finalized() const { return position_ < 0; }
+
+ DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
+};
+
+// The type-based aliasing rule allows the compiler to assume that pointers of
+// different types (for some definition of different) never alias each other.
+// Thus the following code does not work:
+//
+// float f = foo();
+// int fbits = *(int*)(&f);
+//
+// The compiler 'knows' that the int pointer can't refer to f since the types
+// don't match, so the compiler may cache f in a register, leaving random data
+// in fbits. Using C++ style casts makes no difference, however a pointer to
+// char data is assumed to alias any other pointer. This is the 'memcpy
+// exception'.
+//
+// Bit_cast uses the memcpy exception to move the bits from a variable of one
+// type of a variable of another type. Of course the end result is likely to
+// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
+// will completely optimize BitCast away.
+//
+// There is an additional use for BitCast.
+// Recent gccs will warn when they see casts that may result in breakage due to
+// the type-based aliasing rule. If you have checked that there is no breakage
+// you can use BitCast to cast one pointer type to another. This confuses gcc
+// enough that it can no longer see that you have cast one pointer type to
+// another thus avoiding the warning.
+//
+// Adding an unused attribute for this static check. Apparently GCC 4.8
+// now throws an error for unused typedefs which triggers -Werror.
+//
+// PJD: 4-24-2013
+//
+
+#if defined(__GNUC__)
+#define UNUSED __attribute__((unused))
+#else
+#define UNUSED
+#endif
+
+template <class Dest, class Source>
+inline Dest BitCast(const Source& source) {
+ // Compile time assertion: sizeof(Dest) == sizeof(Source)
+ // A compile error here means your Dest and Source have different sizes.
+ UNUSED typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
+
+ Dest dest;
+ memmove(&dest, &source, sizeof(dest));
+ return dest;
+}
+
+template <class Dest, class Source>
+inline Dest BitCast(Source* source) {
+ return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
+}
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_UTILS_H_
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/doubles.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/doubles.cc b/src/jiffy/c_src/doubles.cc
new file mode 100644
index 0000000..0cedfd3
--- /dev/null
+++ b/src/jiffy/c_src/doubles.cc
@@ -0,0 +1,33 @@
+#include "double-conversion/double-conversion.h"
+
+#define BEGIN_C extern "C" {
+#define END_C }
+
+
+namespace dc = double_conversion;
+
+
+BEGIN_C
+
+int
+double_to_shortest(char* buf, size_t size, size_t* len, double val)
+{
+ int flags = dc::DoubleToStringConverter::UNIQUE_ZERO |
+ dc::DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN |
+ dc::DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT |
+ dc::DoubleToStringConverter::EMIT_TRAILING_ZERO_AFTER_POINT;
+
+ dc::StringBuilder builder(buf, size);
+ dc::DoubleToStringConverter conv(flags, NULL, NULL, 'e', -6, 21, 6, 0);
+
+ if(!conv.ToShortest(val, &builder)) {
+ return 0;
+ }
+
+ *len = (size_t) builder.position();
+ builder.Finalize();
+
+ return 1;
+}
+
+END_C
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/encoder.c
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/encoder.c b/src/jiffy/c_src/encoder.c
new file mode 100644
index 0000000..c23b309
--- /dev/null
+++ b/src/jiffy/c_src/encoder.c
@@ -0,0 +1,709 @@
+// This file is part of Jiffy released under the MIT license.
+// See the LICENSE file for more information.
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "erl_nif.h"
+#include "jiffy.h"
+
+#define BIN_INC_SIZE 2048
+
+#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
+
+#define MAYBE_PRETTY(e) \
+do { \
+ if(e->pretty) { \
+ if(!enc_shift(e)) \
+ return 0; \
+ } \
+} while(0)
+
+#if WINDOWS || WIN32
+#define inline __inline
+#define snprintf _snprintf
+#endif
+
+typedef struct {
+ ErlNifEnv* env;
+ jiffy_st* atoms;
+ int uescape;
+ int pretty;
+
+ int shiftcnt;
+ int count;
+
+ int iolen;
+ ERL_NIF_TERM iolist;
+ ErlNifBinary* curr;
+
+
+ char* p;
+ unsigned char* u;
+ size_t i;
+} Encoder;
+
+
+// String constants for pretty printing.
+// Every string starts with its length.
+#define NUM_SHIFTS 8
+static char* shifts[NUM_SHIFTS] = {
+ "\x01\n",
+ "\x03\n ",
+ "\x05\n ",
+ "\x07\n ",
+ "\x09\n ",
+ "\x0b\n ",
+ "\x0d\n ",
+ "\x0f\n "
+};
+
+
+int
+enc_init(Encoder* e, ErlNifEnv* env, ERL_NIF_TERM opts, ErlNifBinary* bin)
+{
+ ERL_NIF_TERM val;
+
+ e->env = env;
+ e->atoms = enif_priv_data(env);
+ e->uescape = 0;
+ e->pretty = 0;
+ e->shiftcnt = 0;
+ e->count = 0;
+
+ if(!enif_is_list(env, opts)) {
+ return 0;
+ }
+
+ while(enif_get_list_cell(env, opts, &val, &opts)) {
+ if(enif_compare(val, e->atoms->atom_uescape) == 0) {
+ e->uescape = 1;
+ } else if(enif_compare(val, e->atoms->atom_pretty) == 0) {
+ e->pretty = 1;
+ } else if(enif_compare(val, e->atoms->atom_force_utf8) == 0) {
+ // Ignore, handled in Erlang
+ } else {
+ return 0;
+ }
+ }
+
+ e->iolen = 0;
+ e->iolist = enif_make_list(env, 0);
+ e->curr = bin;
+ if(!enif_alloc_binary(BIN_INC_SIZE, e->curr)) {
+ return 0;
+ }
+
+ memset(e->curr->data, 0, e->curr->size);
+
+ e->p = (char*) e->curr->data;
+ e->u = (unsigned char*) e->curr->data;
+ e->i = 0;
+
+ return 1;
+}
+
+void
+enc_destroy(Encoder* e)
+{
+ if(e->curr != NULL) {
+ enif_release_binary(e->curr);
+ }
+}
+
+ERL_NIF_TERM
+enc_error(Encoder* e, const char* msg)
+{
+ //assert(0 && msg);
+ return make_error(e->atoms, e->env, msg);
+}
+
+static inline int
+enc_ensure(Encoder* e, size_t req)
+{
+ size_t need = e->curr->size;
+ while(req >= (need - e->i)) need <<= 1;
+
+ if(need != e->curr->size) {
+ if(!enif_realloc_binary(e->curr, need)) {
+ return 0;
+ }
+ e->p = (char*) e->curr->data;
+ e->u = (unsigned char*) e->curr->data;
+ }
+
+ return 1;
+}
+
+int
+enc_result(Encoder* e, ERL_NIF_TERM* value)
+{
+ if(e->i != e->curr->size) {
+ if(!enif_realloc_binary(e->curr, e->i)) {
+ return 0;
+ }
+ }
+
+ *value = enif_make_binary(e->env, e->curr);
+ e->curr = NULL;
+ return 1;
+}
+
+int
+enc_done(Encoder* e, ERL_NIF_TERM* value)
+{
+ ERL_NIF_TERM last;
+
+ if(e->iolen == 0) {
+ return enc_result(e, value);
+ }
+
+ if(e->i > 0 ) {
+ if(!enc_result(e, &last)) {
+ return 0;
+ }
+
+ e->iolist = enif_make_list_cell(e->env, last, e->iolist);
+ e->iolen++;
+ }
+
+ *value = e->iolist;
+ return 1;
+}
+
+static inline int
+enc_unknown(Encoder* e, ERL_NIF_TERM value)
+{
+ ErlNifBinary* bin = e->curr;
+ ERL_NIF_TERM curr;
+
+ if(e->i > 0) {
+ if(!enc_result(e, &curr)) {
+ return 0;
+ }
+
+ e->iolist = enif_make_list_cell(e->env, curr, e->iolist);
+ e->iolen++;
+ }
+
+ e->iolist = enif_make_list_cell(e->env, value, e->iolist);
+ e->iolen++;
+
+ // Reinitialize our binary for the next buffer.
+ e->curr = bin;
+ if(!enif_alloc_binary(BIN_INC_SIZE, e->curr)) {
+ return 0;
+ }
+
+ memset(e->curr->data, 0, e->curr->size);
+
+ e->p = (char*) e->curr->data;
+ e->u = (unsigned char*) e->curr->data;
+ e->i = 0;
+
+ return 1;
+}
+
+static inline int
+enc_literal(Encoder* e, const char* literal, size_t len)
+{
+ if(!enc_ensure(e, len)) {
+ return 0;
+ }
+
+ memcpy(&(e->p[e->i]), literal, len);
+ e->i += len;
+ e->count++;
+ return 1;
+}
+
+static inline int
+enc_string(Encoder* e, ERL_NIF_TERM val)
+{
+ ErlNifBinary bin;
+ char atom[512];
+
+ unsigned char* data;
+ size_t size;
+
+ int esc_extra = 0;
+ int ulen;
+ int uval;
+ int i;
+
+ if(enif_is_binary(e->env, val)) {
+ if(!enif_inspect_binary(e->env, val, &bin)) {
+ return 0;
+ }
+ data = bin.data;
+ size = bin.size;
+ } else if(enif_is_atom(e->env, val)) {
+ if(!enif_get_atom(e->env, val, atom, 512, ERL_NIF_LATIN1)) {
+ return 0;
+ }
+ data = (unsigned char*) atom;
+ size = strlen(atom);
+ } else {
+ return 0;
+ }
+
+ i = 0;
+ while(i < size) {
+ switch((char) data[i]) {
+ case '\"':
+ case '\\':
+ case '\b':
+ case '\f':
+ case '\n':
+ case '\r':
+ case '\t':
+ esc_extra += 1;
+ i++;
+ continue;
+ default:
+ if(data[i] < 0x20) {
+ esc_extra += 5;
+ i++;
+ continue;
+ } else if(data[i] < 0x80) {
+ i++;
+ continue;
+ }
+ ulen = utf8_validate(&(data[i]), size - i);
+ if(ulen < 0) {
+ return 0;
+ }
+ if(e->uescape) {
+ uval = utf8_to_unicode(&(data[i]), ulen);
+ if(uval < 0) {
+ return 0;
+ }
+ esc_extra += utf8_esc_len(uval);
+ if(ulen < 0) {
+ return 0;
+ }
+ }
+ i += ulen;
+ }
+ }
+
+ if(!enc_ensure(e, size + esc_extra + 2)) {
+ return 0;
+ }
+
+ e->p[e->i++] = '\"';
+
+ i = 0;
+ while(i < size) {
+ switch((char) data[i]) {
+ case '\"':
+ case '\\':
+ e->p[e->i++] = '\\';
+ e->u[e->i++] = data[i];
+ i++;
+ continue;
+ case '\b':
+ e->p[e->i++] = '\\';
+ e->p[e->i++] = 'b';
+ i++;
+ continue;
+ case '\f':
+ e->p[e->i++] = '\\';
+ e->p[e->i++] = 'f';
+ i++;
+ continue;
+ case '\n':
+ e->p[e->i++] = '\\';
+ e->p[e->i++] = 'n';
+ i++;
+ continue;
+ case '\r':
+ e->p[e->i++] = '\\';
+ e->p[e->i++] = 'r';
+ i++;
+ continue;
+ case '\t':
+ e->p[e->i++] = '\\';
+ e->p[e->i++] = 't';
+ i++;
+ continue;
+ default:
+ if(data[i] < 0x20) {
+ ulen = unicode_uescape(data[i], &(e->p[e->i]));
+ if(ulen < 0) {
+ return 0;
+ }
+ e->i += ulen;
+ i++;
+ } else if((data[i] & 0x80) && e->uescape) {
+ uval = utf8_to_unicode(&(data[i]), size-i);
+ if(uval < 0) {
+ return 0;
+ }
+
+ ulen = unicode_uescape(uval, &(e->p[e->i]));
+ if(ulen < 0) {
+ return 0;
+ }
+ e->i += ulen;
+
+ ulen = utf8_len(uval);
+ if(ulen < 0) {
+ return 0;
+ }
+ i += ulen;
+ } else {
+ e->u[e->i++] = data[i++];
+ }
+ }
+ }
+
+ e->p[e->i++] = '\"';
+ e->count++;
+
+ return 1;
+}
+
+static inline int
+enc_long(Encoder* e, ErlNifSInt64 val)
+{
+ if(!enc_ensure(e, 32)) {
+ return 0;
+ }
+
+#if (defined(__WIN32__) || defined(_WIN32) || defined(_WIN32_))
+ snprintf(&(e->p[e->i]), 32, "%ld", val);
+#elif SIZEOF_LONG == 8
+ snprintf(&(e->p[e->i]), 32, "%ld", val);
+#else
+ snprintf(&(e->p[e->i]), 32, "%lld", val);
+#endif
+
+ e->i += strlen(&(e->p[e->i]));
+ e->count++;
+
+ return 1;
+}
+
+static inline int
+enc_double(Encoder* e, double val)
+{
+ char* start;
+ size_t len;
+
+ if(!enc_ensure(e, 32)) {
+ return 0;
+ }
+
+ start = &(e->p[e->i]);
+
+ if(!double_to_shortest(start, e->curr->size, &len, val)) {
+ return 0;
+ }
+
+ e->i += len;
+ e->count++;
+ return 1;
+}
+
+static inline int
+enc_char(Encoder* e, char c)
+{
+ if(!enc_ensure(e, 1)) {
+ return 0;
+ }
+
+ e->p[e->i++] = c;
+ return 1;
+}
+
+static int
+enc_shift(Encoder* e) {
+ int i;
+ char* shift;
+ assert(e->shiftcnt >= 0 && "Invalid shift count.");
+ shift = shifts[MIN(e->shiftcnt, NUM_SHIFTS-1)];
+
+ if(!enc_literal(e, shift + 1, *shift))
+ return 0;
+
+ // Finish the rest of this shift it's it bigger than
+ // our largest predefined constant.
+ for(i = NUM_SHIFTS - 1; i < e->shiftcnt; i++) {
+ if(!enc_literal(e, " ", 2))
+ return 0;
+ }
+
+ return 1;
+}
+
+static inline int
+enc_start_object(Encoder* e)
+{
+ e->count++;
+ e->shiftcnt++;
+ if(!enc_char(e, '{'))
+ return 0;
+ MAYBE_PRETTY(e);
+ return 1;
+}
+
+static inline int
+enc_end_object(Encoder* e)
+{
+ e->shiftcnt--;
+ MAYBE_PRETTY(e);
+ return enc_char(e, '}');
+}
+
+static inline int
+enc_start_array(Encoder* e)
+{
+ e->count++;
+ e->shiftcnt++;
+ if(!enc_char(e, '['))
+ return 0;
+ MAYBE_PRETTY(e);
+ return 1;
+}
+
+static inline int
+enc_end_array(Encoder* e)
+{
+ e->shiftcnt--;
+ MAYBE_PRETTY(e);
+ return enc_char(e, ']');
+}
+
+static inline int
+enc_colon(Encoder* e)
+{
+ if(e->pretty)
+ return enc_literal(e, " : ", 3);
+ return enc_char(e, ':');
+}
+
+static inline int
+enc_comma(Encoder* e)
+{
+ if(!enc_char(e, ','))
+ return 0;
+ MAYBE_PRETTY(e);
+ return 1;
+}
+
+ERL_NIF_TERM
+encode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{
+ Encoder enc;
+ Encoder* e = &enc;
+
+ ErlNifBinary bin;
+ ERL_NIF_TERM ret;
+
+ ERL_NIF_TERM stack;
+ ERL_NIF_TERM curr;
+ ERL_NIF_TERM item;
+ const ERL_NIF_TERM* tuple;
+ int arity;
+ ErlNifSInt64 lval;
+ double dval;
+
+ if(argc != 2) {
+ return enif_make_badarg(env);
+ }
+
+ if(!enc_init(e, env, argv[1], &bin)) {
+ return enif_make_badarg(env);
+ }
+
+ stack = enif_make_list(env, 1, argv[0]);
+
+ while(!enif_is_empty_list(env, stack)) {
+ if(!enif_get_list_cell(env, stack, &curr, &stack)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(enif_is_identical(curr, e->atoms->ref_object)) {
+ if(!enif_get_list_cell(env, stack, &curr, &stack)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(enif_is_empty_list(env, curr)) {
+ if(!enc_end_object(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ continue;
+ }
+ if(!enif_get_list_cell(env, curr, &item, &curr)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(!enif_get_tuple(env, item, &arity, &tuple)) {
+ ret = enc_error(e, "invalid_object_pair");
+ goto done;
+ }
+ if(arity != 2) {
+ ret = enc_error(e, "invalid_object_pair");
+ goto done;
+ }
+ if(!enc_comma(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(!enc_string(e, tuple[0])) {
+ ret = enc_error(e, "invalid_object_key");
+ goto done;
+ }
+ if(!enc_colon(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ stack = enif_make_list_cell(env, curr, stack);
+ stack = enif_make_list_cell(env, e->atoms->ref_object, stack);
+ stack = enif_make_list_cell(env, tuple[1], stack);
+ } else if(enif_is_identical(curr, e->atoms->ref_array)) {
+ if(!enif_get_list_cell(env, stack, &curr, &stack)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(enif_is_empty_list(env, curr)) {
+ if(!enc_end_array(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ continue;
+ }
+ if(!enc_comma(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(!enif_get_list_cell(env, curr, &item, &curr)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ stack = enif_make_list_cell(env, curr, stack);
+ stack = enif_make_list_cell(env, e->atoms->ref_array, stack);
+ stack = enif_make_list_cell(env, item, stack);
+ } else if(enif_compare(curr, e->atoms->atom_null) == 0) {
+ if(!enc_literal(e, "null", 4)) {
+ ret = enc_error(e, "null");
+ goto done;
+ }
+ } else if(enif_compare(curr, e->atoms->atom_true) == 0) {
+ if(!enc_literal(e, "true", 4)) {
+ ret = enc_error(e, "true");
+ goto done;
+ }
+ } else if(enif_compare(curr, e->atoms->atom_false) == 0) {
+ if(!enc_literal(e, "false", 5)) {
+ ret = enc_error(e, "false");
+ goto done;
+ }
+ } else if(enif_is_binary(env, curr)) {
+ if(!enc_string(e, curr)) {
+ ret = enc_error(e, "invalid_string");
+ goto done;
+ }
+ } else if(enif_is_atom(env, curr)) {
+ if(!enc_string(e, curr)) {
+ ret = enc_error(e, "invalid_string");
+ goto done;
+ }
+ } else if(enif_get_int64(env, curr, &lval)) {
+ if(!enc_long(e, lval)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ } else if(enif_get_double(env, curr, &dval)) {
+ if(!enc_double(e, dval)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ } else if(enif_get_tuple(env, curr, &arity, &tuple)) {
+ if(arity != 1) {
+ ret = enc_error(e, "invalid_ejson");
+ goto done;
+ }
+ if(!enif_is_list(env, tuple[0])) {
+ ret = enc_error(e, "invalid_object");
+ goto done;
+ }
+ if(!enc_start_object(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(enif_is_empty_list(env, tuple[0])) {
+ if(!enc_end_object(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ continue;
+ }
+ if(!enif_get_list_cell(env, tuple[0], &item, &curr)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(!enif_get_tuple(env, item, &arity, &tuple)) {
+ ret = enc_error(e, "invalid_object_member");
+ goto done;
+ }
+ if(arity != 2) {
+ ret = enc_error(e, "invalid_object_member_arity");
+ goto done;
+ }
+ if(!enc_string(e, tuple[0])) {
+ ret = enc_error(e, "invalid_object_member_key");
+ goto done;
+ }
+ if(!enc_colon(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ stack = enif_make_list_cell(env, curr, stack);
+ stack = enif_make_list_cell(env, e->atoms->ref_object, stack);
+ stack = enif_make_list_cell(env, tuple[1], stack);
+ } else if(enif_is_list(env, curr)) {
+ if(!enc_start_array(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ if(enif_is_empty_list(env, curr)) {
+ if(!enc_end_array(e)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ continue;
+ }
+ if(!enif_get_list_cell(env, curr, &item, &curr)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ stack = enif_make_list_cell(env, curr, stack);
+ stack = enif_make_list_cell(env, e->atoms->ref_array, stack);
+ stack = enif_make_list_cell(env, item, stack);
+ } else {
+ if(!enc_unknown(e, curr)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+ }
+ }
+
+ if(!enc_done(e, &item)) {
+ ret = enc_error(e, "internal_error");
+ goto done;
+ }
+
+ if(e->iolen == 0) {
+ ret = item;
+ } else {
+ ret = enif_make_tuple2(env, e->atoms->atom_partial, item);
+ }
+
+done:
+ enc_destroy(e);
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/jiffy.c
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/jiffy.c b/src/jiffy/c_src/jiffy.c
new file mode 100644
index 0000000..964222c
--- /dev/null
+++ b/src/jiffy/c_src/jiffy.c
@@ -0,0 +1,61 @@
+// This file is part of Jiffy released under the MIT license.
+// See the LICENSE file for more information.
+
+#include "jiffy.h"
+
+static int
+load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)
+{
+ jiffy_st* st = enif_alloc(sizeof(jiffy_st));
+ if(st == NULL) {
+ return 1;
+ }
+
+ st->atom_ok = make_atom(env, "ok");
+ st->atom_error = make_atom(env, "error");
+ st->atom_null = make_atom(env, "null");
+ 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");
+ st->atom_pretty = make_atom(env, "pretty");
+ st->atom_force_utf8 = make_atom(env, "force_utf8");
+
+ // Markers used in encoding
+ st->ref_object = make_atom(env, "$object_ref$");
+ st->ref_array = make_atom(env, "$array_ref$");
+
+ *priv = (void*) st;
+
+ return 0;
+}
+
+static int
+reload(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)
+{
+ return 0;
+}
+
+static int
+upgrade(ErlNifEnv* env, void** priv, void** old_priv, ERL_NIF_TERM info)
+{
+ return load(env, priv, info);
+}
+
+static void
+unload(ErlNifEnv* env, void* priv)
+{
+ enif_free(priv);
+ return;
+}
+
+static ErlNifFunc funcs[] =
+{
+ {"nif_decode", 1, decode},
+ {"nif_encode", 2, encode}
+};
+
+ERL_NIF_INIT(jiffy, funcs, &load, &reload, &upgrade, &unload);
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/jiffy.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/jiffy.h b/src/jiffy/c_src/jiffy.h
new file mode 100644
index 0000000..3dda545
--- /dev/null
+++ b/src/jiffy/c_src/jiffy.h
@@ -0,0 +1,45 @@
+// This file is part of Jiffy released under the MIT license.
+// See the LICENSE file for more information.
+
+#ifndef JIFFY_H
+#define JIFFY_H
+
+#include "erl_nif.h"
+
+typedef struct {
+ ERL_NIF_TERM atom_ok;
+ ERL_NIF_TERM atom_error;
+ ERL_NIF_TERM atom_null;
+ 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;
+ ERL_NIF_TERM atom_pretty;
+ ERL_NIF_TERM atom_force_utf8;
+
+ ERL_NIF_TERM ref_object;
+ ERL_NIF_TERM ref_array;
+} jiffy_st;
+
+ERL_NIF_TERM make_atom(ErlNifEnv* env, const char* name);
+ERL_NIF_TERM make_ok(jiffy_st* st, ErlNifEnv* env, ERL_NIF_TERM data);
+ERL_NIF_TERM make_error(jiffy_st* st, ErlNifEnv* env, const char* error);
+
+ERL_NIF_TERM decode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+ERL_NIF_TERM encode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
+
+int int_from_hex(const unsigned char* p);
+int int_to_hex(int val, char* p);
+int utf8_len(int c);
+int utf8_esc_len(int c);
+int utf8_validate(unsigned char* data, size_t size);
+int utf8_to_unicode(unsigned char* buf, size_t size);
+int unicode_to_utf8(int c, unsigned char* buf);
+int unicode_from_pair(int hi, int lo);
+int unicode_uescape(int c, char* buf);
+int double_to_shortest(char *buf, size_t size, size_t* len, double val);
+
+#endif // Included JIFFY_H
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/utf8.c
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/utf8.c b/src/jiffy/c_src/utf8.c
new file mode 100644
index 0000000..3ac65cb
--- /dev/null
+++ b/src/jiffy/c_src/utf8.c
@@ -0,0 +1,249 @@
+// This file is part of Jiffy released under the MIT license.
+// See the LICENSE file for more information.
+#include "jiffy.h"
+#include <stdio.h>
+
+static const char hexvals[256] = {
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
+ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
+};
+
+static const char hexdigits[16] = {
+ '0', '1', '2', '3',
+ '4', '5', '6', '7',
+ '8', '9', 'A', 'B',
+ 'C', 'D', 'E', 'F'
+};
+
+int
+int_from_hex(const unsigned char* p)
+{
+ unsigned char* h = (unsigned char*) p;
+ int ret;
+
+ if(hexvals[*(h+0)] < 0) return -1;
+ if(hexvals[*(h+1)] < 0) return -1;
+ if(hexvals[*(h+2)] < 0) return -1;
+ if(hexvals[*(h+3)] < 0) return -1;
+
+ ret = (hexvals[*(h+0)] << 12)
+ + (hexvals[*(h+1)] << 8)
+ + (hexvals[*(h+2)] << 4)
+ + (hexvals[*(h+3)] << 0);
+
+ return ret;
+}
+
+int
+int_to_hex(int val, char* p)
+{
+ if(val < 0 || val > 65535)
+ return -1;
+
+ p[0] = hexdigits[(val >> 12) & 0xF];
+ p[1] = hexdigits[(val >> 8) & 0xF];
+ p[2] = hexdigits[(val >> 4) & 0xF];
+ p[3] = hexdigits[val & 0xF];
+
+ return 1;
+}
+
+int
+utf8_len(int c)
+{
+ if(c < 128) {
+ return 1;
+ } else if(c < 0x800) {
+ return 2;
+ } else if(c < 0x10000) {
+ if(c < 0xD800 || (c > 0xDFFF && c < 0xFFFE)) {
+ return 3;
+ } else {
+ return -1;
+ }
+ } else if(c <= 0x10FFFF) {
+ return 4;
+ } else {
+ return -1;
+ }
+}
+
+int
+utf8_esc_len(int c)
+{
+ if(c < 0x10000) {
+ return 6;
+ } else if(c <= 0x10FFFF) {
+ return 12;
+ } else {
+ return -1;
+ }
+}
+
+int
+utf8_validate(unsigned char* data, size_t size)
+{
+ int ulen = -1;
+ int ui;
+
+ if((data[0] & 0x80) == 0x00) {
+ ulen = 1;
+ } if((data[0] & 0xE0) == 0xC0) {
+ ulen = 2;
+ } else if((data[0] & 0xF0) == 0xE0) {
+ ulen = 3;
+ } else if((data[0] & 0xF8) == 0xF0) {
+ ulen = 4;
+ }
+ if(ulen < 0 || ulen > size) {
+ return -1;
+ }
+
+ // Check each continuation byte.
+ for(ui = 1; ui < ulen; ui++) {
+ if((data[ui] & 0xC0) != 0x80) return -1;
+ }
+
+ // Wikipedia says I have to check that a UTF-8 encoding
+ // uses as few bits as possible. This means that we
+ // can't do things like encode 't' in three bytes.
+ // To check this all we need to ensure is that for each
+ // of the following bit patterns that there is at least
+ // one 1 bit in any of the x's
+ // 1: 0yyyyyyy
+ // 2: 110xxxxy 10yyyyyy
+ // 3: 1110xxxx 10xyyyyy 10yyyyyy
+ // 4: 11110xxx 10xxyyyy 10yyyyyy 10yyyyyy
+
+ // ulen == 1 passes by definition
+ if(ulen == 2) {
+ if((data[0] & 0x1E) == 0)
+ return -1;
+ } else if(ulen == 3) {
+ if((data[0] & 0x0F) + (data[1] & 0x20) == 0)
+ return -1;
+ } else if(ulen == 4) {
+ if((data[0] & 0x07) + (data[1] & 0x30) == 0)
+ return -1;
+ }
+
+ // Lastly we need to check some miscellaneous ranges for
+ // some of the larger code point values.
+ if(ulen >= 3) {
+ ui = utf8_to_unicode(data, ulen);
+ if(ui < 0) {
+ return -1;
+ } else if(ui >= 0xD800 && ui <= 0xDFFF) {
+ return -1;
+ } else if(ui == 0xFFFE || ui == 0xFFFF) {
+ return -1;
+ } else if(ui > 0x10FFFF) {
+ return -1;
+ }
+ }
+
+ return ulen;
+}
+
+int
+utf8_to_unicode(unsigned char* buf, size_t size)
+{
+ int ret;
+ if((buf[0] & 0x80) == 0x00) {
+ // 0xxxxxxx
+ ret = (int) buf[0];
+ } else if((buf[0] & 0xE0) == 0xC0 && size >= 2) {
+ // 110xxxxy 10yyyyyy
+ ret = ((buf[0] & 0x1F) << 6)
+ | ((buf[1] & 0x3F));
+ } else if((buf[0] & 0xF0) == 0xE0 && size >= 3) {
+ // 1110xxxx 10xyyyyy 10yyyyyy
+ ret = ((buf[0] & 0x0F) << 12)
+ | ((buf[1] & 0x3F) << 6)
+ | ((buf[2] & 0x3F));
+ if(ret >= 0xD800 && ret <= 0xDFFF) {
+ ret = -1;
+ }
+ } else if((buf[0] & 0xF8) == 0xF0 && size >= 4) {
+ // 11110xxx 10xxyyyy 10yyyyyy 10yyyyyy
+ ret = ((buf[0] & 0x07) << 18)
+ | ((buf[1] & 0x3F) << 12)
+ | ((buf[2] & 0x3F) << 6)
+ | ((buf[3] & 0x3F));
+ } else {
+ ret = -1;
+ }
+ return ret;
+}
+
+int
+unicode_to_utf8(int c, unsigned char* buf)
+{
+ if(c < 0x80) {
+ buf[0] = (unsigned char) c;
+ return 1;
+ } else if(c < 0x800) {
+ buf[0] = (unsigned char) 0xC0 + (c >> 6);
+ buf[1] = (unsigned char) 0x80 + (c & 0x3F);
+ return 2;
+ } else if(c < 0x10000) {
+ if(c < 0xD800 || (c > 0xDFFF && c < 0xFFFE)) {
+ buf[0] = (unsigned char) 0xE0 + (c >> 12);
+ buf[1] = (unsigned char) 0x80 + ((c >> 6) & 0x3F);
+ buf[2] = (unsigned char) 0x80 + (c & 0x3F);
+ return 3;
+ } else {
+ return -1;
+ }
+ } else if(c < 0x10FFFF) {
+ buf[0] = (unsigned char) 0xF0 + (c >> 18);
+ buf[1] = (unsigned char) 0x80 + ((c >> 12) & 0x3F);
+ buf[2] = (unsigned char) 0x80 + ((c >> 6) & 0x3F);
+ buf[3] = (unsigned char) 0x80 + (c & 0x3F);
+ return 4;
+ }
+ return -1;
+}
+
+int
+unicode_from_pair(int hi, int lo)
+{
+ if(hi < 0xD800 || hi >= 0xDC00) return -1;
+ if(lo < 0xDC00 || lo > 0xDFFF) return -1;
+ return ((hi & 0x3FF) << 10) + (lo & 0x3FF) + 0x10000;
+}
+
+int
+unicode_uescape(int val, char* p)
+{
+ int n;
+ if(val < 0x10000) {
+ p[0] = '\\';
+ p[1] = 'u';
+ if(int_to_hex(val, p+2) < 0) {
+ return -1;
+ }
+ return 6;
+ } else if (val <= 0x10FFFF) {
+ n = val - 0x10000;
+ p[0] = '\\';
+ p[1] = 'u';
+ if(int_to_hex((0xD800 | ((n >> 10) & 0x03FF)), p+2) < 0) {
+ return -1;
+ }
+ p[6] = '\\';
+ p[7] = 'u';
+ if(int_to_hex((0xDC00 | (n & 0x03FF)), p+8) < 0) {
+ return -1;
+ }
+ return 12;
+ }
+ return -1;
+}
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/util.c
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/util.c b/src/jiffy/c_src/util.c
new file mode 100644
index 0000000..f1be3ec
--- /dev/null
+++ b/src/jiffy/c_src/util.c
@@ -0,0 +1,26 @@
+// This file is part of Jiffy released under the MIT license.
+// See the LICENSE file for more information.
+
+#include "jiffy.h"
+
+ERL_NIF_TERM
+make_atom(ErlNifEnv* env, const char* name)
+{
+ ERL_NIF_TERM ret;
+ if(enif_make_existing_atom(env, name, &ret, ERL_NIF_LATIN1)) {
+ return ret;
+ }
+ return enif_make_atom(env, name);
+}
+
+ERL_NIF_TERM
+make_ok(jiffy_st* st, ErlNifEnv* env, ERL_NIF_TERM value)
+{
+ return enif_make_tuple2(env, st->atom_ok, value);
+}
+
+ERL_NIF_TERM
+make_error(jiffy_st* st, ErlNifEnv* env, const char* error)
+{
+ return enif_make_tuple2(env, st->atom_error, make_atom(env, error));
+}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/rebar.config
----------------------------------------------------------------------
diff --git a/src/jiffy/rebar.config b/src/jiffy/rebar.config
new file mode 100644
index 0000000..f992d04
--- /dev/null
+++ b/src/jiffy/rebar.config
@@ -0,0 +1,34 @@
+{port_specs, [
+ {"priv/jiffy.so", [
+ "c_src/*.c",
+ "c_src/*.cc",
+ "c_src/double-conversion/*.cc"
+ ]}
+]}.
+
+{port_env, [
+ {".*", "CXXFLAGS", "$CXXFLAGS -g -Wall -Werror -O3"},
+
+ {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin)",
+ "LDFLAGS", "$LDFLAGS -lstdc++"},
+
+ %% OS X Leopard flags for 64-bit
+ {"darwin9.*-64$", "CXXFLAGS", "-m64"},
+ {"darwin9.*-64$", "LDFLAGS", "-arch x86_64"},
+
+ %% OS X Snow Leopard flags for 32-bit
+ {"darwin10.*-32$", "CXXFLAGS", "-m32"},
+ {"darwin10.*-32$", "LDFLAGS", "-arch i386"},
+
+ %% This will merge into basho/rebar/rebar.config eventually
+ {"win32", "CFLAGS", "/Wall /DWIN32 /D_WINDOWS /D_WIN32 /DWINDOWS"},
+ {"win32", "CXXFLAGS", "-g -Wall -O3"}
+]}.
+
+
+{eunit_opts, [
+ verbose,
+ {report, {
+ eunit_surefire, [{dir,"."}]
+ }}
+]}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/rebar.config.script
----------------------------------------------------------------------
diff --git a/src/jiffy/rebar.config.script b/src/jiffy/rebar.config.script
new file mode 100644
index 0000000..58d4ff7
--- /dev/null
+++ b/src/jiffy/rebar.config.script
@@ -0,0 +1,33 @@
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+% Only include PropEr as a dependency when the JIFFY_DEV
+% environment variable is defined. This allows downstream
+% applications to avoid requiring PropEr.
+%
+% This script is based on the example provided with Rebar.
+
+ErlOpts = {erl_opts, [
+ {d, 'JIFFY_DEV'}
+]},
+
+Proper = [
+ {proper, ".*", {git, "git://github.com/manopapad/proper.git", "master"}}
+],
+
+ConfigPath = filename:dirname(SCRIPT),
+DevMarker = filename:join([ConfigPath, ".jiffy.dev"]),
+
+case filelib:is_file(DevMarker) of
+ true ->
+ % Don't override existing dependencies
+ NewConfig = case lists:keyfind(deps, 1, CONFIG) of
+ false ->
+ CONFIG ++ [{deps, Proper}];
+ {deps, DepsList} ->
+ lists:keyreplace(deps, 1, CONFIG, {deps, DepsList ++ Proper})
+ end,
+ NewConfig ++ [ErlOpts];
+ false ->
+ CONFIG
+end.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/src/jiffy.app.src
----------------------------------------------------------------------
diff --git a/src/jiffy/src/jiffy.app.src b/src/jiffy/src/jiffy.app.src
new file mode 100644
index 0000000..4ea304a
--- /dev/null
+++ b/src/jiffy/src/jiffy.app.src
@@ -0,0 +1,6 @@
+{application, jiffy, [
+ {description, "JSON Decoder/Encoder."},
+ {vsn, git},
+ {registered, []},
+ {applications, [kernel]}
+]}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/src/jiffy.erl
----------------------------------------------------------------------
diff --git a/src/jiffy/src/jiffy.erl b/src/jiffy/src/jiffy.erl
new file mode 100644
index 0000000..c4b3d69
--- /dev/null
+++ b/src/jiffy/src/jiffy.erl
@@ -0,0 +1,107 @@
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+-module(jiffy).
+-export([decode/1, encode/1, encode/2]).
+-define(NOT_LOADED, not_loaded(?LINE)).
+
+-on_load(init/0).
+
+decode(Data) when is_binary(Data) ->
+ case nif_decode(Data) of
+ {error, _} = Error ->
+ throw(Error);
+ {partial, EJson} ->
+ finish_decode(EJson);
+ EJson ->
+ EJson
+ end;
+decode(Data) when is_list(Data) ->
+ decode(iolist_to_binary(Data)).
+
+
+encode(Data) ->
+ encode(Data, []).
+
+
+encode(Data, Options) ->
+ ForceUTF8 = lists:member(force_utf8, Options),
+ case nif_encode(Data, Options) of
+ {error, invalid_string} when ForceUTF8 == true ->
+ FixedData = jiffy_utf8:fix(Data),
+ encode(FixedData, Options -- [force_utf8]);
+ {error, _} = Error ->
+ throw(Error);
+ {partial, IOData} ->
+ finish_encode(IOData, []);
+ IOData ->
+ IOData
+ end.
+
+
+finish_decode({bignum, Value}) ->
+ list_to_integer(binary_to_list(Value));
+finish_decode({bignum_e, Value}) ->
+ {IVal, EVal} = case string:to_integer(binary_to_list(Value)) of
+ {I, [$e | ExpStr]} ->
+ {E, []} = string:to_integer(ExpStr),
+ {I, E};
+ {I, [$E | ExpStr]} ->
+ {E, []} = string:to_integer(ExpStr),
+ {I, E}
+ end,
+ IVal * math:pow(10, EVal);
+finish_decode({bigdbl, Value}) ->
+ list_to_float(binary_to_list(Value));
+finish_decode({Pairs}) when is_list(Pairs) ->
+ finish_decode_obj(Pairs, []);
+finish_decode(Vals) when is_list(Vals) ->
+ finish_decode_arr(Vals, []);
+finish_decode(Val) ->
+ Val.
+
+finish_decode_obj([], Acc) ->
+ {lists:reverse(Acc)};
+finish_decode_obj([{K, V} | Pairs], Acc) ->
+ finish_decode_obj(Pairs, [{K, finish_decode(V)} | Acc]).
+
+finish_decode_arr([], Acc) ->
+ lists:reverse(Acc);
+finish_decode_arr([V | Vals], Acc) ->
+ finish_decode_arr(Vals, [finish_decode(V) | Acc]).
+
+
+finish_encode([], Acc) ->
+ %% No reverse! The NIF returned us
+ %% the pieces in reverse order.
+ Acc;
+finish_encode([<<_/binary>>=B | Rest], Acc) ->
+ finish_encode(Rest, [B | Acc]);
+finish_encode([Val | Rest], Acc) when is_integer(Val) ->
+ Bin = list_to_binary(integer_to_list(Val)),
+ finish_encode(Rest, [Bin | Acc]);
+finish_encode(_, _) ->
+ throw({error, invalid_ejson}).
+
+
+init() ->
+ PrivDir = case code:priv_dir(?MODULE) of
+ {error, _} ->
+ EbinDir = filename:dirname(code:which(?MODULE)),
+ AppPath = filename:dirname(EbinDir),
+ filename:join(AppPath, "priv");
+ Path ->
+ Path
+ end,
+ erlang:load_nif(filename:join(PrivDir, "jiffy"), 0).
+
+
+not_loaded(Line) ->
+ erlang:nif_error({not_loaded, [{module, ?MODULE}, {line, Line}]}).
+
+nif_decode(_Data) ->
+ ?NOT_LOADED.
+
+nif_encode(_Data, _Options) ->
+ ?NOT_LOADED.
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/src/jiffy_utf8.erl
----------------------------------------------------------------------
diff --git a/src/jiffy/src/jiffy_utf8.erl b/src/jiffy/src/jiffy_utf8.erl
new file mode 100644
index 0000000..ee937fe
--- /dev/null
+++ b/src/jiffy/src/jiffy_utf8.erl
@@ -0,0 +1,104 @@
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+-module(jiffy_utf8).
+-export([fix/1]).
+
+
+fix({Props}) ->
+ fix_props(Props, []);
+fix(Values) when is_list(Values) ->
+ fix_array(Values, []);
+fix(Bin) when is_binary(Bin) ->
+ fix_bin(Bin);
+fix(Val) ->
+ Val.
+
+
+fix_props([], Acc) ->
+ {lists:reverse(Acc)};
+fix_props([{K0, V0} | Rest], Acc) ->
+ K = fix(K0),
+ V = fix(V0),
+ fix_props(Rest, [{K, V} | Acc]).
+
+
+fix_array([], Acc) ->
+ lists:reverse(Acc);
+fix_array([Val | Rest], Acc0) ->
+ Acc = [fix(Val) | Acc0],
+ fix_array(Rest, Acc).
+
+
+fix_bin(Bin) ->
+ Dec0 = loose_decode(Bin, 0, []),
+ Dec1 = try_combining(Dec0, []),
+ Dec2 = replace_garbage(Dec1, []),
+ list_to_binary(xmerl_ucs:to_utf8(Dec2)).
+
+
+loose_decode(Bin, O, Acc) ->
+ case Bin of
+ <<_:O/binary>> ->
+ lists:reverse(Acc);
+ <<_:O/binary, 0:1/integer, V:7/integer, _/binary>> ->
+ loose_decode(Bin, O+1, [V | Acc]);
+ <<_:O/binary, 6:3/integer, V0:5/integer,
+ 2:2/integer, V1:6/integer, _/binary>> ->
+ B = <<0:5/integer, V0:5/integer, V1:6/integer>>,
+ <<V:16/integer>> = B,
+ loose_decode(Bin, O+2, [V | Acc]);
+ <<_:O/binary, 14:4/integer, V0:4/integer,
+ 2:2/integer, V1:6/integer,
+ 2:2/integer, V2:6/integer, _/binary>> ->
+ B = <<V0:4/integer, V1:6/integer, V2:6/integer>>,
+ <<V:16/integer>> = B,
+ loose_decode(Bin, O+3, [V | Acc]);
+ <<_:O/binary, 30:5/integer, V0:3/integer,
+ 2:2/integer, V1:6/integer,
+ 2:2/integer, V2:6/integer,
+ 2:2/integer, V3:6/integer, _/binary>> ->
+ B = <<0:11/integer, V0:3/integer, V1:6/integer,
+ V2:6/integer, V3:6/integer>>,
+ <<V:32/integer>> = B,
+ loose_decode(Bin, O+4, [V | Acc]);
+ <<_:O/binary, _:8/integer, R/binary>> ->
+ % Broken lead or continuation byte. Discard first
+ % byte and all broken continuations. Replace the
+ % whole mess with a replacment code point.
+ T = 1 + count_continuation_bytes(R, 0),
+ loose_decode(Bin, O+T, [16#FFFD | Acc])
+ end.
+
+
+count_continuation_bytes(R, O) ->
+ case R of
+ <<_:O/binary, 2:2/integer, _:6/integer, _/binary>> ->
+ count_continuation_bytes(R, O+1);
+ _ ->
+ O
+ end.
+
+
+try_combining([], Acc) ->
+ lists:reverse(Acc);
+try_combining([H, L | Rest], Acc) when H >= 16#D800, H =< 16#DFFF,
+ L >= 16#D800, L =< 16#DFFF ->
+ Bin = <<H:16/big-unsigned-integer, L:16/big-unsigned-integer>>,
+ try
+ [C] = xmerl_ucs:from_utf16be(Bin),
+ try_combining(Rest, [C | Acc])
+ catch _:_ ->
+ try_combining(Rest, [L, H | Acc])
+ end;
+try_combining([C | Rest], Acc) ->
+ try_combining(Rest, [C | Acc]).
+
+
+replace_garbage([], Acc) ->
+ lists:reverse(Acc);
+replace_garbage([C | Rest], Acc) ->
+ case xmerl_ucs:is_unicode(C) of
+ true -> replace_garbage(Rest, [C | Acc]);
+ false -> replace_garbage(Rest, [16#FFFD | Acc])
+ end.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/001-yajl-tests.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/001-yajl-tests.t b/src/jiffy/test/001-yajl-tests.t
new file mode 100755
index 0000000..b89fbee
--- /dev/null
+++ b/src/jiffy/test/001-yajl-tests.t
@@ -0,0 +1,30 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("test"),
+ code:add_pathz("ebin"),
+
+ Cases = read_cases(),
+
+ etap:plan(length(Cases)),
+ lists:foreach(fun(Case) -> test(Case) end, Cases),
+ etap:end_tests().
+
+test({Name, Json, {error, _}=Erl}) ->
+ etap:is((catch jiffy:decode(Json)), Erl, Name);
+test({Name, Json, Erl}) ->
+ etap:is(jiffy:decode(Json), Erl, Name).
+
+read_cases() ->
+ CasesPath = filename:join(["test", "cases", "*.json"]),
+ FileNames = lists:sort(filelib:wildcard(CasesPath)),
+ lists:map(fun(F) -> make_pair(F) end, FileNames).
+
+make_pair(FileName) ->
+ {ok, Json} = file:read_file(FileName),
+ {BaseName, _} = lists:splitwith(fun(C) -> C /= $. end, FileName),
+ ErlFname = BaseName ++ ".eterm",
+ {ok, [Term]} = file:consult(ErlFname),
+ {BaseName, Json, Term}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/002-literals.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/002-literals.t b/src/jiffy/test/002-literals.t
new file mode 100755
index 0000000..8df7255
--- /dev/null
+++ b/src/jiffy/test/002-literals.t
@@ -0,0 +1,21 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(6),
+ etap:is(jiffy:decode(<<"true">>), true, "DEC: true -> true"),
+ etap:is(jiffy:encode(true), <<"true">>, "ENC: true -> true"),
+
+ etap:is(jiffy:decode(<<"false">>), false, "DEC: false -> false"),
+ etap:is(jiffy:encode(false), <<"false">>, "ENC: false -> false"),
+
+ etap:is(jiffy:decode(<<"null">>), null, "DEC: null -> null"),
+ etap:is(jiffy:encode(null), <<"null">>, "ENC: null -> null"),
+
+ etap:end_tests().
+
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/003-numbers.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/003-numbers.t b/src/jiffy/test/003-numbers.t
new file mode 100755
index 0000000..2ac2ab4
--- /dev/null
+++ b/src/jiffy/test/003-numbers.t
@@ -0,0 +1,118 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(59 + 2 * length(double_conversion_tests())),
+ util:test_good(good()),
+ util:test_errors(errors()),
+ run_double_conversion_tests(),
+ etap:end_tests().
+
+
+run_double_conversion_tests() ->
+ lists:foreach(fun(Double) ->
+ Descr = io_lib:format("~f", [Double]),
+ etap:is(jiffy:decode(jiffy:encode(Double)), Double, Descr),
+ NegDouble = -1.0 * Double,
+ NegDescr = io_lib:format("~f", [NegDouble]),
+ etap:is(jiffy:decode(jiffy:encode(NegDouble)), NegDouble, NegDescr)
+ end, double_conversion_tests()).
+
+good() ->
+ [
+ {<<"0">>, 0},
+ {<<"-0">>, 0, <<"0">>},
+ {<<"1">>, 1},
+ {<<"12">>, 12},
+ {<<"-3">>, -3},
+ {<<"1234567890123456789012345">>, 1234567890123456789012345},
+ {<<"1310050760199">>, 1310050760199},
+ {
+ <<"1234567890123456789012345.0">>,
+ 1.23456789012345678e24,
+ <<"1.2345678901234568e+24">>
+ },
+ {
+ <<"1234567890123456789012345.0E3">>,
+ 1.2345678901234569e27,
+ <<"1.2345678901234569e+27">>
+ },
+ {
+ <<"1234567890123456789012345012">>,
+ 1234567890123456789012345012,
+ <<"1234567890123456789012345012">>
+ },
+ {<<"1.0">>, 1.0},
+ {
+ <<"0.000000000000000000000000000000000001">>,
+ 1.0E-36,
+ <<"1e-36">>
+ },
+ {<<"0.75">>, 0.75},
+ {<<"2.0123456789">>, 2.0123456789, <<"2.0123456789">>},
+ {<<"2.4234324E24">>, 2.4234324E24, <<"2.4234324e+24">>},
+ {<<"-3.1416">>, -3.1416, <<"-3.1416">>},
+ {<<"1E4">>, 10000.0, <<"10000.0">>},
+ {<<"1.0E+01">>, 10.0, <<"10.0">>},
+ {<<"1e1">>, 10.0, <<"10.0">>},
+ {<<"3.0E2">>, 300.0, <<"300.0">>},
+ {<<"0E3">>, 0.0, <<"0.0">>},
+ {<<"1.5E3">>, 1500.0, <<"1500.0">>},
+ {<<"2.5E-1">>, 0.25, <<"0.25">>},
+ {<<"-0.325E+2">>, -32.5, <<"-32.5">>}
+ ].
+
+
+errors() ->
+ [
+ <<"02">>,
+ <<"-01">>,
+ <<"+12">>,
+ <<"-">>,
+ <<"1.">>,
+ <<".1">>,
+ <<"1.-1">>,
+ <<"1E">>,
+ <<"1-E2">>,
+ <<"2E +3">>,
+ <<"1EA">>
+ ].
+
+
+double_conversion_tests() ->
+ [
+ 0.0,
+ 0.00000001,
+ 0.000000012,
+ 0.0000000123,
+ 0.0000001,
+ 0.00000012,
+ 0.000000123,
+ 0.000001,
+ 0.00001,
+ 0.01,
+ 0.0123,
+ 0.1,
+ 0.3,
+ 1.0,
+ 1.0e20,
+ 1.0e21,
+ 9.0,
+ 10.0,
+ 90.0,
+ 90.12,
+ 10000.0,
+ 12345.0,
+ 12345.0e23,
+ 100000.0,
+ 100000000000000000000.0,
+ 111111111111111111111.0,
+ 1111111111111111111111.0,
+ 11111111111111111111111.0
+ ].
+
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/004-strings.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/004-strings.t b/src/jiffy/test/004-strings.t
new file mode 100755
index 0000000..d5e5161
--- /dev/null
+++ b/src/jiffy/test/004-strings.t
@@ -0,0 +1,131 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(119),
+ util:test_good(good()),
+ util:test_good(uescaped(), [uescape]),
+ util:test_errors(errors()),
+
+ test_utf8(utf8_cases()),
+
+ etap:end_tests().
+
+good() ->
+ [
+ {<<"\"\"">>, <<"">>},
+ {<<"\"/\"">>, <<"/">>},
+ {<<"\"0\"">>, <<"0">>},
+ {<<"\"foo\"">>, <<"foo">>},
+ {<<"\"\\\"foobar\\\"\"">>, <<"\"foobar\"">>},
+ {<<"\"\\n\\n\\n\"">>, <<"\n\n\n">>},
+ {<<"\"\\\" \\b\\f\\r\\n\\t\\\"\"">>, <<"\" \b\f\r\n\t\"">>},
+ {<<"\"foo\\u0005bar\"">>, <<"foo", 5, "bar">>},
+ {
+ <<"\"\\uD834\\uDD1E\"">>,
+ <<240, 157, 132, 158>>,
+ <<34, 240, 157, 132, 158, 34>>
+ }
+ ].
+
+uescaped() ->
+ [
+ {
+ <<"\"\\u8CA8\\u5481\\u3002\\u0091\\u0091\"">>,
+ <<232,178,168,229,146,129,227,128,130,194,145,194,145>>
+ },
+ {
+ <<"\"\\uD834\\uDD1E\"">>,
+ <<240, 157, 132, 158>>
+ },
+ {
+ <<"\"\\uD83D\\uDE0A\"">>,
+ <<240, 159, 152, 138>>
+ }
+ ].
+
+errors() ->
+ [
+ "\"",
+ <<"\"foo">>,
+ <<"\"", 0, "\"">>,
+ <<"\"\\g\"">>,
+ <<"\"\\uFFFF\"">>,
+ <<"\"\\uFFFE\"">>,
+ <<"\"\\uD834foo\\uDD1E\"">>,
+ % CouchDB-345
+ <<34,78,69,73,77,69,78,32,70,216,82,82,32,70,65,69,78,33,34>>
+ ].
+
+test_utf8([]) ->
+ ok;
+test_utf8([{Case, Fixed} | Rest]) ->
+ etap:fun_is(
+ fun({error, invalid_string}) -> true; (Else) -> Else end,
+ (catch jiffy:encode(Case)),
+ lists:flatten(io_lib:format("Invalid utf-8: ~p", [Case]))
+ ),
+ etap:fun_is(
+ fun(Fixed) -> true; (Else) -> Else end,
+ jiffy:encode(Case, [force_utf8]),
+ lists:flatten(io_lib:format("Fixed correctly: ~p", [Fixed]))
+ ),
+ Case2 = <<34, Case/binary, 34>>,
+ etap:fun_is(
+ fun({error, {_, invalid_string}}) -> true; (Else) -> Else end,
+ (catch jiffy:decode(Case2)),
+ lists:flatten(io_lib:format("Invalid utf-8: ~p", [Case2]))
+ ),
+ test_utf8(Rest).
+
+utf8_cases() ->
+ [
+ % Stray continuation byte
+ {<<16#C2, 16#81, 16#80>>, <<16#C2, 16#81, 16#EF, 16#BF, 16#BD>>},
+ {<<"foo", 16#80, "bar">>, <<"foo", 16#EF, 16#BF, 16#BD, "bar">>},
+
+ % Invalid Unicode code points
+ {<<239, 191, 190>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<237, 160, 129>>, <<16#EF, 16#BF, 16#BD>>},
+
+ % Not enough extension bytes
+ {<<16#C0>>, <<16#EF, 16#BF, 16#BD>>},
+
+ {<<16#E0>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#E0, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+
+ {<<16#F0>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#F0, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#F0, 16#80, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+
+ {<<16#F8>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#F8, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#F8, 16#80, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#F8, 16#80, 16#80, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+
+ {<<16#FC>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#FC, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#FC, 16#80, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#FC, 16#80, 16#80, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+ {<<16#FC, 16#80, 16#80, 16#80, 16#80>>, <<16#EF, 16#BF, 16#BD>>},
+
+ % No data in high bits.
+ {<<16#C0, 16#80>>, <<"\"\\u0000\"">>},
+ {<<16#C1, 16#80>>, <<"\"\\u0000\"">>},
+
+ {<<16#E0, 16#80, 16#80>>, <<"\"\\u0000\"">>},
+ {<<16#E0, 16#90, 16#80>>, <<"\"\\u0000\"">>},
+
+ {<<16#F0, 16#80, 16#80, 16#80>>, <<"\"\\u0000\"">>},
+ {<<16#F0, 16#88, 16#80, 16#80>>, <<"\"\\u0000\"">>},
+
+ {<<16#F8, 16#80, 16#80, 16#80, 16#80>>, <<"\"\\u0000\"">>},
+ {<<16#F8, 16#84, 16#80, 16#80, 16#80>>, <<"\"\\u0000\"">>},
+
+ {<<16#FC, 16#80, 16#80, 16#80, 16#80, 16#80>>, <<"\"\\u0000\"">>},
+ {<<16#FC, 16#82, 16#80, 16#80, 16#80, 16#80>>, <<"\"\\u0000\"">>}
+ ].
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/005-arrays.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/005-arrays.t b/src/jiffy/test/005-arrays.t
new file mode 100755
index 0000000..1c43c0e
--- /dev/null
+++ b/src/jiffy/test/005-arrays.t
@@ -0,0 +1,36 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(18),
+ util:test_good(good()),
+ util:test_errors(errors()),
+ etap:end_tests().
+
+good() ->
+ [
+ {<<"[]">>, []},
+ {<<"[\t[\n]\r]">>, [[]], <<"[[]]">>},
+ {<<"[\t123, \r true\n]">>, [123, true], <<"[123,true]">>},
+ {<<"[1,\"foo\"]">>, [1, <<"foo">>]},
+ {<<"[11993444355.0,1]">>, [11993444355.0,1]},
+ {
+ <<"[\"\\u00A1\",\"\\u00FC\"]">>,
+ [<<194, 161>>, <<195, 188>>],
+ <<"[\"", 194, 161, "\",\"", 195, 188, "\"]">>
+ }
+ ].
+
+errors() ->
+ [
+ <<"[">>,
+ <<"]">>,
+ <<"[,]">>,
+ <<"[123">>,
+ <<"[123,]">>,
+ <<"[32 true]">>
+ ].
[07/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/fast-dtoa.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/fast-dtoa.cc b/src/jiffy/c_src/double-conversion/fast-dtoa.cc
new file mode 100644
index 0000000..b2f7b8d
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/fast-dtoa.cc
@@ -0,0 +1,666 @@
+// Copyright 2012 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "fast-dtoa.h"
+
+#include "cached-powers.h"
+#include "diy-fp.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+// The minimal and maximal target exponent define the range of w's binary
+// exponent, where 'w' is the result of multiplying the input by a cached power
+// of ten.
+//
+// A different range might be chosen on a different platform, to optimize digit
+// generation, but a smaller range requires more powers of ten to be cached.
+static const int kMinimalTargetExponent = -60;
+static const int kMaximalTargetExponent = -32;
+
+
+// Adjusts the last digit of the generated number, and screens out generated
+// solutions that may be inaccurate. A solution may be inaccurate if it is
+// outside the safe interval, or if we cannot prove that it is closer to the
+// input than a neighboring representation of the same length.
+//
+// Input: * buffer containing the digits of too_high / 10^kappa
+// * the buffer's length
+// * distance_too_high_w == (too_high - w).f() * unit
+// * unsafe_interval == (too_high - too_low).f() * unit
+// * rest = (too_high - buffer * 10^kappa).f() * unit
+// * ten_kappa = 10^kappa * unit
+// * unit = the common multiplier
+// Output: returns true if the buffer is guaranteed to contain the closest
+// representable number to the input.
+// Modifies the generated digits in the buffer to approach (round towards) w.
+static bool RoundWeed(Vector<char> buffer,
+ int length,
+ uint64_t distance_too_high_w,
+ uint64_t unsafe_interval,
+ uint64_t rest,
+ uint64_t ten_kappa,
+ uint64_t unit) {
+ uint64_t small_distance = distance_too_high_w - unit;
+ uint64_t big_distance = distance_too_high_w + unit;
+ // Let w_low = too_high - big_distance, and
+ // w_high = too_high - small_distance.
+ // Note: w_low < w < w_high
+ //
+ // The real w (* unit) must lie somewhere inside the interval
+ // ]w_low; w_high[ (often written as "(w_low; w_high)")
+
+ // Basically the buffer currently contains a number in the unsafe interval
+ // ]too_low; too_high[ with too_low < w < too_high
+ //
+ // too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ // ^v 1 unit ^ ^ ^ ^
+ // boundary_high --------------------- . . . .
+ // ^v 1 unit . . . .
+ // - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
+ // . . ^ . .
+ // . big_distance . . .
+ // . . . . rest
+ // small_distance . . . .
+ // v . . . .
+ // w_high - - - - - - - - - - - - - - - - - - . . . .
+ // ^v 1 unit . . . .
+ // w ---------------------------------------- . . . .
+ // ^v 1 unit v . . .
+ // w_low - - - - - - - - - - - - - - - - - - - - - . . .
+ // . . v
+ // buffer --------------------------------------------------+-------+--------
+ // . .
+ // safe_interval .
+ // v .
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
+ // ^v 1 unit .
+ // boundary_low ------------------------- unsafe_interval
+ // ^v 1 unit v
+ // too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ //
+ //
+ // Note that the value of buffer could lie anywhere inside the range too_low
+ // to too_high.
+ //
+ // boundary_low, boundary_high and w are approximations of the real boundaries
+ // and v (the input number). They are guaranteed to be precise up to one unit.
+ // In fact the error is guaranteed to be strictly less than one unit.
+ //
+ // Anything that lies outside the unsafe interval is guaranteed not to round
+ // to v when read again.
+ // Anything that lies inside the safe interval is guaranteed to round to v
+ // when read again.
+ // If the number inside the buffer lies inside the unsafe interval but not
+ // inside the safe interval then we simply do not know and bail out (returning
+ // false).
+ //
+ // Similarly we have to take into account the imprecision of 'w' when finding
+ // the closest representation of 'w'. If we have two potential
+ // representations, and one is closer to both w_low and w_high, then we know
+ // it is closer to the actual value v.
+ //
+ // By generating the digits of too_high we got the largest (closest to
+ // too_high) buffer that is still in the unsafe interval. In the case where
+ // w_high < buffer < too_high we try to decrement the buffer.
+ // This way the buffer approaches (rounds towards) w.
+ // There are 3 conditions that stop the decrementation process:
+ // 1) the buffer is already below w_high
+ // 2) decrementing the buffer would make it leave the unsafe interval
+ // 3) decrementing the buffer would yield a number below w_high and farther
+ // away than the current number. In other words:
+ // (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
+ // Instead of using the buffer directly we use its distance to too_high.
+ // Conceptually rest ~= too_high - buffer
+ // We need to do the following tests in this order to avoid over- and
+ // underflows.
+ ASSERT(rest <= unsafe_interval);
+ while (rest < small_distance && // Negated condition 1
+ unsafe_interval - rest >= ten_kappa && // Negated condition 2
+ (rest + ten_kappa < small_distance || // buffer{-1} > w_high
+ small_distance - rest >= rest + ten_kappa - small_distance)) {
+ buffer[length - 1]--;
+ rest += ten_kappa;
+ }
+
+ // We have approached w+ as much as possible. We now test if approaching w-
+ // would require changing the buffer. If yes, then we have two possible
+ // representations close to w, but we cannot decide which one is closer.
+ if (rest < big_distance &&
+ unsafe_interval - rest >= ten_kappa &&
+ (rest + ten_kappa < big_distance ||
+ big_distance - rest > rest + ten_kappa - big_distance)) {
+ return false;
+ }
+
+ // Weeding test.
+ // The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
+ // Since too_low = too_high - unsafe_interval this is equivalent to
+ // [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
+ // Conceptually we have: rest ~= too_high - buffer
+ return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
+}
+
+
+// Rounds the buffer upwards if the result is closer to v by possibly adding
+// 1 to the buffer. If the precision of the calculation is not sufficient to
+// round correctly, return false.
+// The rounding might shift the whole buffer in which case the kappa is
+// adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
+//
+// If 2*rest > ten_kappa then the buffer needs to be round up.
+// rest can have an error of +/- 1 unit. This function accounts for the
+// imprecision and returns false, if the rounding direction cannot be
+// unambiguously determined.
+//
+// Precondition: rest < ten_kappa.
+static bool RoundWeedCounted(Vector<char> buffer,
+ int length,
+ uint64_t rest,
+ uint64_t ten_kappa,
+ uint64_t unit,
+ int* kappa) {
+ ASSERT(rest < ten_kappa);
+ // The following tests are done in a specific order to avoid overflows. They
+ // will work correctly with any uint64 values of rest < ten_kappa and unit.
+ //
+ // If the unit is too big, then we don't know which way to round. For example
+ // a unit of 50 means that the real number lies within rest +/- 50. If
+ // 10^kappa == 40 then there is no way to tell which way to round.
+ if (unit >= ten_kappa) return false;
+ // Even if unit is just half the size of 10^kappa we are already completely
+ // lost. (And after the previous test we know that the expression will not
+ // over/underflow.)
+ if (ten_kappa - unit <= unit) return false;
+ // If 2 * (rest + unit) <= 10^kappa we can safely round down.
+ if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
+ return true;
+ }
+ // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
+ if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
+ // Increment the last digit recursively until we find a non '9' digit.
+ buffer[length - 1]++;
+ for (int i = length - 1; i > 0; --i) {
+ if (buffer[i] != '0' + 10) break;
+ buffer[i] = '0';
+ buffer[i - 1]++;
+ }
+ // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
+ // exception of the first digit all digits are now '0'. Simply switch the
+ // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
+ // the power (the kappa) is increased.
+ if (buffer[0] == '0' + 10) {
+ buffer[0] = '1';
+ (*kappa) += 1;
+ }
+ return true;
+ }
+ return false;
+}
+
+// Returns the biggest power of ten that is less than or equal to the given
+// number. We furthermore receive the maximum number of bits 'number' has.
+//
+// Returns power == 10^(exponent_plus_one-1) such that
+// power <= number < power * 10.
+// If number_bits == 0 then 0^(0-1) is returned.
+// The number of bits must be <= 32.
+// Precondition: number < (1 << (number_bits + 1)).
+
+// Inspired by the method for finding an integer log base 10 from here:
+// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
+static unsigned int const kSmallPowersOfTen[] =
+ {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
+ 1000000000};
+
+static void BiggestPowerTen(uint32_t number,
+ int number_bits,
+ uint32_t* power,
+ int* exponent_plus_one) {
+ ASSERT(number < (1u << (number_bits + 1)));
+ // 1233/4096 is approximately 1/lg(10).
+ int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
+ // We increment to skip over the first entry in the kPowersOf10 table.
+ // Note: kPowersOf10[i] == 10^(i-1).
+ exponent_plus_one_guess++;
+ // We don't have any guarantees that 2^number_bits <= number.
+ // TODO(floitsch): can we change the 'while' into an 'if'? We definitely see
+ // number < (2^number_bits - 1), but I haven't encountered
+ // number < (2^number_bits - 2) yet.
+ while (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
+ exponent_plus_one_guess--;
+ if (exponent_plus_one_guess <= 0)
+ break;
+ }
+ *power = kSmallPowersOfTen[exponent_plus_one_guess];
+ *exponent_plus_one = exponent_plus_one_guess;
+}
+
+// Generates the digits of input number w.
+// w is a floating-point number (DiyFp), consisting of a significand and an
+// exponent. Its exponent is bounded by kMinimalTargetExponent and
+// kMaximalTargetExponent.
+// Hence -60 <= w.e() <= -32.
+//
+// Returns false if it fails, in which case the generated digits in the buffer
+// should not be used.
+// Preconditions:
+// * low, w and high are correct up to 1 ulp (unit in the last place). That
+// is, their error must be less than a unit of their last digits.
+// * low.e() == w.e() == high.e()
+// * low < w < high, and taking into account their error: low~ <= high~
+// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
+// Postconditions: returns false if procedure fails.
+// otherwise:
+// * buffer is not null-terminated, but len contains the number of digits.
+// * buffer contains the shortest possible decimal digit-sequence
+// such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
+// correct values of low and high (without their error).
+// * if more than one decimal representation gives the minimal number of
+// decimal digits then the one closest to W (where W is the correct value
+// of w) is chosen.
+// Remark: this procedure takes into account the imprecision of its input
+// numbers. If the precision is not enough to guarantee all the postconditions
+// then false is returned. This usually happens rarely (~0.5%).
+//
+// Say, for the sake of example, that
+// w.e() == -48, and w.f() == 0x1234567890abcdef
+// w's value can be computed by w.f() * 2^w.e()
+// We can obtain w's integral digits by simply shifting w.f() by -w.e().
+// -> w's integral part is 0x1234
+// w's fractional part is therefore 0x567890abcdef.
+// Printing w's integral part is easy (simply print 0x1234 in decimal).
+// In order to print its fraction we repeatedly multiply the fraction by 10 and
+// get each digit. Example the first digit after the point would be computed by
+// (0x567890abcdef * 10) >> 48. -> 3
+// The whole thing becomes slightly more complicated because we want to stop
+// once we have enough digits. That is, once the digits inside the buffer
+// represent 'w' we can stop. Everything inside the interval low - high
+// represents w. However we have to pay attention to low, high and w's
+// imprecision.
+static bool DigitGen(DiyFp low,
+ DiyFp w,
+ DiyFp high,
+ Vector<char> buffer,
+ int* length,
+ int* kappa) {
+ ASSERT(low.e() == w.e() && w.e() == high.e());
+ ASSERT(low.f() + 1 <= high.f() - 1);
+ ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
+ // low, w and high are imprecise, but by less than one ulp (unit in the last
+ // place).
+ // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
+ // the new numbers are outside of the interval we want the final
+ // representation to lie in.
+ // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
+ // numbers that are certain to lie in the interval. We will use this fact
+ // later on.
+ // We will now start by generating the digits within the uncertain
+ // interval. Later we will weed out representations that lie outside the safe
+ // interval and thus _might_ lie outside the correct interval.
+ uint64_t unit = 1;
+ DiyFp too_low = DiyFp(low.f() - unit, low.e());
+ DiyFp too_high = DiyFp(high.f() + unit, high.e());
+ // too_low and too_high are guaranteed to lie outside the interval we want the
+ // generated number in.
+ DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
+ // We now cut the input number into two parts: the integral digits and the
+ // fractionals. We will not write any decimal separator though, but adapt
+ // kappa instead.
+ // Reminder: we are currently computing the digits (stored inside the buffer)
+ // such that: too_low < buffer * 10^kappa < too_high
+ // We use too_high for the digit_generation and stop as soon as possible.
+ // If we stop early we effectively round down.
+ DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
+ // Division by one is a shift.
+ uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
+ // Modulo by one is an and.
+ uint64_t fractionals = too_high.f() & (one.f() - 1);
+ uint32_t divisor;
+ int divisor_exponent_plus_one;
+ BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
+ &divisor, &divisor_exponent_plus_one);
+ *kappa = divisor_exponent_plus_one;
+ *length = 0;
+ // Loop invariant: buffer = too_high / 10^kappa (integer division)
+ // The invariant holds for the first iteration: kappa has been initialized
+ // with the divisor exponent + 1. And the divisor is the biggest power of ten
+ // that is smaller than integrals.
+ while (*kappa > 0) {
+ int digit = integrals / divisor;
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ integrals %= divisor;
+ (*kappa)--;
+ // Note that kappa now equals the exponent of the divisor and that the
+ // invariant thus holds again.
+ uint64_t rest =
+ (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
+ // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
+ // Reminder: unsafe_interval.e() == one.e()
+ if (rest < unsafe_interval.f()) {
+ // Rounding down (by not emitting the remaining digits) yields a number
+ // that lies within the unsafe interval.
+ return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
+ unsafe_interval.f(), rest,
+ static_cast<uint64_t>(divisor) << -one.e(), unit);
+ }
+ divisor /= 10;
+ }
+
+ // The integrals have been generated. We are at the point of the decimal
+ // separator. In the following loop we simply multiply the remaining digits by
+ // 10 and divide by one. We just need to pay attention to multiply associated
+ // data (like the interval or 'unit'), too.
+ // Note that the multiplication by 10 does not overflow, because w.e >= -60
+ // and thus one.e >= -60.
+ ASSERT(one.e() >= -60);
+ ASSERT(fractionals < one.f());
+ ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
+ while (true) {
+ fractionals *= 10;
+ unit *= 10;
+ unsafe_interval.set_f(unsafe_interval.f() * 10);
+ // Integer division by one.
+ int digit = static_cast<int>(fractionals >> -one.e());
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ fractionals &= one.f() - 1; // Modulo by one.
+ (*kappa)--;
+ if (fractionals < unsafe_interval.f()) {
+ return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
+ unsafe_interval.f(), fractionals, one.f(), unit);
+ }
+ }
+}
+
+
+
+// Generates (at most) requested_digits digits of input number w.
+// w is a floating-point number (DiyFp), consisting of a significand and an
+// exponent. Its exponent is bounded by kMinimalTargetExponent and
+// kMaximalTargetExponent.
+// Hence -60 <= w.e() <= -32.
+//
+// Returns false if it fails, in which case the generated digits in the buffer
+// should not be used.
+// Preconditions:
+// * w is correct up to 1 ulp (unit in the last place). That
+// is, its error must be strictly less than a unit of its last digit.
+// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
+//
+// Postconditions: returns false if procedure fails.
+// otherwise:
+// * buffer is not null-terminated, but length contains the number of
+// digits.
+// * the representation in buffer is the most precise representation of
+// requested_digits digits.
+// * buffer contains at most requested_digits digits of w. If there are less
+// than requested_digits digits then some trailing '0's have been removed.
+// * kappa is such that
+// w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
+//
+// Remark: This procedure takes into account the imprecision of its input
+// numbers. If the precision is not enough to guarantee all the postconditions
+// then false is returned. This usually happens rarely, but the failure-rate
+// increases with higher requested_digits.
+static bool DigitGenCounted(DiyFp w,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* kappa) {
+ ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
+ ASSERT(kMinimalTargetExponent >= -60);
+ ASSERT(kMaximalTargetExponent <= -32);
+ // w is assumed to have an error less than 1 unit. Whenever w is scaled we
+ // also scale its error.
+ uint64_t w_error = 1;
+ // We cut the input number into two parts: the integral digits and the
+ // fractional digits. We don't emit any decimal separator, but adapt kappa
+ // instead. Example: instead of writing "1.2" we put "12" into the buffer and
+ // increase kappa by 1.
+ DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
+ // Division by one is a shift.
+ uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
+ // Modulo by one is an and.
+ uint64_t fractionals = w.f() & (one.f() - 1);
+ uint32_t divisor;
+ int divisor_exponent_plus_one;
+ BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
+ &divisor, &divisor_exponent_plus_one);
+ *kappa = divisor_exponent_plus_one;
+ *length = 0;
+
+ // Loop invariant: buffer = w / 10^kappa (integer division)
+ // The invariant holds for the first iteration: kappa has been initialized
+ // with the divisor exponent + 1. And the divisor is the biggest power of ten
+ // that is smaller than 'integrals'.
+ while (*kappa > 0) {
+ int digit = integrals / divisor;
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ requested_digits--;
+ integrals %= divisor;
+ (*kappa)--;
+ // Note that kappa now equals the exponent of the divisor and that the
+ // invariant thus holds again.
+ if (requested_digits == 0) break;
+ divisor /= 10;
+ }
+
+ if (requested_digits == 0) {
+ uint64_t rest =
+ (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
+ return RoundWeedCounted(buffer, *length, rest,
+ static_cast<uint64_t>(divisor) << -one.e(), w_error,
+ kappa);
+ }
+
+ // The integrals have been generated. We are at the point of the decimal
+ // separator. In the following loop we simply multiply the remaining digits by
+ // 10 and divide by one. We just need to pay attention to multiply associated
+ // data (the 'unit'), too.
+ // Note that the multiplication by 10 does not overflow, because w.e >= -60
+ // and thus one.e >= -60.
+ ASSERT(one.e() >= -60);
+ ASSERT(fractionals < one.f());
+ ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
+ while (requested_digits > 0 && fractionals > w_error) {
+ fractionals *= 10;
+ w_error *= 10;
+ // Integer division by one.
+ int digit = static_cast<int>(fractionals >> -one.e());
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ requested_digits--;
+ fractionals &= one.f() - 1; // Modulo by one.
+ (*kappa)--;
+ }
+ if (requested_digits != 0) return false;
+ return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
+ kappa);
+}
+
+
+// Provides a decimal representation of v.
+// Returns true if it succeeds, otherwise the result cannot be trusted.
+// There will be *length digits inside the buffer (not null-terminated).
+// If the function returns true then
+// v == (double) (buffer * 10^decimal_exponent).
+// The digits in the buffer are the shortest representation possible: no
+// 0.09999999999999999 instead of 0.1. The shorter representation will even be
+// chosen even if the longer one would be closer to v.
+// The last digit will be closest to the actual v. That is, even if several
+// digits might correctly yield 'v' when read again, the closest will be
+// computed.
+static bool Grisu3(double v,
+ FastDtoaMode mode,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_exponent) {
+ DiyFp w = Double(v).AsNormalizedDiyFp();
+ // boundary_minus and boundary_plus are the boundaries between v and its
+ // closest floating-point neighbors. Any number strictly between
+ // boundary_minus and boundary_plus will round to v when convert to a double.
+ // Grisu3 will never output representations that lie exactly on a boundary.
+ DiyFp boundary_minus, boundary_plus;
+ if (mode == FAST_DTOA_SHORTEST) {
+ Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
+ } else {
+ ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
+ float single_v = static_cast<float>(v);
+ Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
+ }
+ ASSERT(boundary_plus.e() == w.e());
+ DiyFp ten_mk; // Cached power of ten: 10^-k
+ int mk; // -k
+ int ten_mk_minimal_binary_exponent =
+ kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ int ten_mk_maximal_binary_exponent =
+ kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
+ ten_mk_minimal_binary_exponent,
+ ten_mk_maximal_binary_exponent,
+ &ten_mk, &mk);
+ ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize) &&
+ (kMaximalTargetExponent >= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize));
+ // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
+ // 64 bit significand and ten_mk is thus only precise up to 64 bits.
+
+ // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
+ // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
+ // off by a small amount.
+ // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
+ // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
+ // (f-1) * 2^e < w*10^k < (f+1) * 2^e
+ DiyFp scaled_w = DiyFp::Times(w, ten_mk);
+ ASSERT(scaled_w.e() ==
+ boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
+ // In theory it would be possible to avoid some recomputations by computing
+ // the difference between w and boundary_minus/plus (a power of 2) and to
+ // compute scaled_boundary_minus/plus by subtracting/adding from
+ // scaled_w. However the code becomes much less readable and the speed
+ // enhancements are not terriffic.
+ DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
+ DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
+
+ // DigitGen will generate the digits of scaled_w. Therefore we have
+ // v == (double) (scaled_w * 10^-mk).
+ // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
+ // integer than it will be updated. For instance if scaled_w == 1.23 then
+ // the buffer will be filled with "123" und the decimal_exponent will be
+ // decreased by 2.
+ int kappa;
+ bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
+ buffer, length, &kappa);
+ *decimal_exponent = -mk + kappa;
+ return result;
+}
+
+
+// The "counted" version of grisu3 (see above) only generates requested_digits
+// number of digits. This version does not generate the shortest representation,
+// and with enough requested digits 0.1 will at some point print as 0.9999999...
+// Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
+// therefore the rounding strategy for halfway cases is irrelevant.
+static bool Grisu3Counted(double v,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_exponent) {
+ DiyFp w = Double(v).AsNormalizedDiyFp();
+ DiyFp ten_mk; // Cached power of ten: 10^-k
+ int mk; // -k
+ int ten_mk_minimal_binary_exponent =
+ kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ int ten_mk_maximal_binary_exponent =
+ kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
+ ten_mk_minimal_binary_exponent,
+ ten_mk_maximal_binary_exponent,
+ &ten_mk, &mk);
+ ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize) &&
+ (kMaximalTargetExponent >= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize));
+ // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
+ // 64 bit significand and ten_mk is thus only precise up to 64 bits.
+
+ // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
+ // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
+ // off by a small amount.
+ // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
+ // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
+ // (f-1) * 2^e < w*10^k < (f+1) * 2^e
+ DiyFp scaled_w = DiyFp::Times(w, ten_mk);
+
+ // We now have (double) (scaled_w * 10^-mk).
+ // DigitGen will generate the first requested_digits digits of scaled_w and
+ // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
+ // will not always be exactly the same since DigitGenCounted only produces a
+ // limited number of digits.)
+ int kappa;
+ bool result = DigitGenCounted(scaled_w, requested_digits,
+ buffer, length, &kappa);
+ *decimal_exponent = -mk + kappa;
+ return result;
+}
+
+
+bool FastDtoa(double v,
+ FastDtoaMode mode,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_point) {
+ ASSERT(v > 0);
+ ASSERT(!Double(v).IsSpecial());
+
+ bool result = false;
+ int decimal_exponent = 0;
+ switch (mode) {
+ case FAST_DTOA_SHORTEST:
+ case FAST_DTOA_SHORTEST_SINGLE:
+ result = Grisu3(v, mode, buffer, length, &decimal_exponent);
+ break;
+ case FAST_DTOA_PRECISION:
+ result = Grisu3Counted(v, requested_digits,
+ buffer, length, &decimal_exponent);
+ break;
+ default:
+ UNREACHABLE();
+ }
+ if (result) {
+ *decimal_point = *length + decimal_exponent;
+ buffer[*length] = '\0';
+ }
+ return result;
+}
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/fast-dtoa.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/fast-dtoa.h b/src/jiffy/c_src/double-conversion/fast-dtoa.h
new file mode 100644
index 0000000..5f1e8ee
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/fast-dtoa.h
@@ -0,0 +1,88 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_FAST_DTOA_H_
+#define DOUBLE_CONVERSION_FAST_DTOA_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+enum FastDtoaMode {
+ // Computes the shortest representation of the given input. The returned
+ // result will be the most accurate number of this length. Longer
+ // representations might be more accurate.
+ FAST_DTOA_SHORTEST,
+ // Same as FAST_DTOA_SHORTEST but for single-precision floats.
+ FAST_DTOA_SHORTEST_SINGLE,
+ // Computes a representation where the precision (number of digits) is
+ // given as input. The precision is independent of the decimal point.
+ FAST_DTOA_PRECISION
+};
+
+// FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not
+// include the terminating '\0' character.
+static const int kFastDtoaMaximalLength = 17;
+// Same for single-precision numbers.
+static const int kFastDtoaMaximalSingleLength = 9;
+
+// Provides a decimal representation of v.
+// The result should be interpreted as buffer * 10^(point - length).
+//
+// Precondition:
+// * v must be a strictly positive finite double.
+//
+// Returns true if it succeeds, otherwise the result can not be trusted.
+// There will be *length digits inside the buffer followed by a null terminator.
+// If the function returns true and mode equals
+// - FAST_DTOA_SHORTEST, then
+// the parameter requested_digits is ignored.
+// The result satisfies
+// v == (double) (buffer * 10^(point - length)).
+// The digits in the buffer are the shortest representation possible. E.g.
+// if 0.099999999999 and 0.1 represent the same double then "1" is returned
+// with point = 0.
+// The last digit will be closest to the actual v. That is, even if several
+// digits might correctly yield 'v' when read again, the buffer will contain
+// the one closest to v.
+// - FAST_DTOA_PRECISION, then
+// the buffer contains requested_digits digits.
+// the difference v - (buffer * 10^(point-length)) is closest to zero for
+// all possible representations of requested_digits digits.
+// If there are two values that are equally close, then FastDtoa returns
+// false.
+// For both modes the buffer must be large enough to hold the result.
+bool FastDtoa(double d,
+ FastDtoaMode mode,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_point);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_FAST_DTOA_H_
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/fixed-dtoa.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/fixed-dtoa.cc b/src/jiffy/c_src/double-conversion/fixed-dtoa.cc
new file mode 100644
index 0000000..d56b144
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/fixed-dtoa.cc
@@ -0,0 +1,402 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <math.h>
+
+#include "fixed-dtoa.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+// Represents a 128bit type. This class should be replaced by a native type on
+// platforms that support 128bit integers.
+class UInt128 {
+ public:
+ UInt128() : high_bits_(0), low_bits_(0) { }
+ UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
+
+ void Multiply(uint32_t multiplicand) {
+ uint64_t accumulator;
+
+ accumulator = (low_bits_ & kMask32) * multiplicand;
+ uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
+ accumulator >>= 32;
+ accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
+ low_bits_ = (accumulator << 32) + part;
+ accumulator >>= 32;
+ accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
+ part = static_cast<uint32_t>(accumulator & kMask32);
+ accumulator >>= 32;
+ accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
+ high_bits_ = (accumulator << 32) + part;
+ ASSERT((accumulator >> 32) == 0);
+ }
+
+ void Shift(int shift_amount) {
+ ASSERT(-64 <= shift_amount && shift_amount <= 64);
+ if (shift_amount == 0) {
+ return;
+ } else if (shift_amount == -64) {
+ high_bits_ = low_bits_;
+ low_bits_ = 0;
+ } else if (shift_amount == 64) {
+ low_bits_ = high_bits_;
+ high_bits_ = 0;
+ } else if (shift_amount <= 0) {
+ high_bits_ <<= -shift_amount;
+ high_bits_ += low_bits_ >> (64 + shift_amount);
+ low_bits_ <<= -shift_amount;
+ } else {
+ low_bits_ >>= shift_amount;
+ low_bits_ += high_bits_ << (64 - shift_amount);
+ high_bits_ >>= shift_amount;
+ }
+ }
+
+ // Modifies *this to *this MOD (2^power).
+ // Returns *this DIV (2^power).
+ int DivModPowerOf2(int power) {
+ if (power >= 64) {
+ int result = static_cast<int>(high_bits_ >> (power - 64));
+ high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
+ return result;
+ } else {
+ uint64_t part_low = low_bits_ >> power;
+ uint64_t part_high = high_bits_ << (64 - power);
+ int result = static_cast<int>(part_low + part_high);
+ high_bits_ = 0;
+ low_bits_ -= part_low << power;
+ return result;
+ }
+ }
+
+ bool IsZero() const {
+ return high_bits_ == 0 && low_bits_ == 0;
+ }
+
+ int BitAt(int position) {
+ if (position >= 64) {
+ return static_cast<int>(high_bits_ >> (position - 64)) & 1;
+ } else {
+ return static_cast<int>(low_bits_ >> position) & 1;
+ }
+ }
+
+ private:
+ static const uint64_t kMask32 = 0xFFFFFFFF;
+ // Value == (high_bits_ << 64) + low_bits_
+ uint64_t high_bits_;
+ uint64_t low_bits_;
+};
+
+
+static const int kDoubleSignificandSize = 53; // Includes the hidden bit.
+
+
+static void FillDigits32FixedLength(uint32_t number, int requested_length,
+ Vector<char> buffer, int* length) {
+ for (int i = requested_length - 1; i >= 0; --i) {
+ buffer[(*length) + i] = '0' + number % 10;
+ number /= 10;
+ }
+ *length += requested_length;
+}
+
+
+static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
+ int number_length = 0;
+ // We fill the digits in reverse order and exchange them afterwards.
+ while (number != 0) {
+ int digit = number % 10;
+ number /= 10;
+ buffer[(*length) + number_length] = '0' + digit;
+ number_length++;
+ }
+ // Exchange the digits.
+ int i = *length;
+ int j = *length + number_length - 1;
+ while (i < j) {
+ char tmp = buffer[i];
+ buffer[i] = buffer[j];
+ buffer[j] = tmp;
+ i++;
+ j--;
+ }
+ *length += number_length;
+}
+
+
+static void FillDigits64FixedLength(uint64_t number, int requested_length,
+ Vector<char> buffer, int* length) {
+ const uint32_t kTen7 = 10000000;
+ // For efficiency cut the number into 3 uint32_t parts, and print those.
+ uint32_t part2 = static_cast<uint32_t>(number % kTen7);
+ number /= kTen7;
+ uint32_t part1 = static_cast<uint32_t>(number % kTen7);
+ uint32_t part0 = static_cast<uint32_t>(number / kTen7);
+
+ FillDigits32FixedLength(part0, 3, buffer, length);
+ FillDigits32FixedLength(part1, 7, buffer, length);
+ FillDigits32FixedLength(part2, 7, buffer, length);
+}
+
+
+static void FillDigits64(uint64_t number, Vector<char> buffer, int* length) {
+ const uint32_t kTen7 = 10000000;
+ // For efficiency cut the number into 3 uint32_t parts, and print those.
+ uint32_t part2 = static_cast<uint32_t>(number % kTen7);
+ number /= kTen7;
+ uint32_t part1 = static_cast<uint32_t>(number % kTen7);
+ uint32_t part0 = static_cast<uint32_t>(number / kTen7);
+
+ if (part0 != 0) {
+ FillDigits32(part0, buffer, length);
+ FillDigits32FixedLength(part1, 7, buffer, length);
+ FillDigits32FixedLength(part2, 7, buffer, length);
+ } else if (part1 != 0) {
+ FillDigits32(part1, buffer, length);
+ FillDigits32FixedLength(part2, 7, buffer, length);
+ } else {
+ FillDigits32(part2, buffer, length);
+ }
+}
+
+
+static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
+ // An empty buffer represents 0.
+ if (*length == 0) {
+ buffer[0] = '1';
+ *decimal_point = 1;
+ *length = 1;
+ return;
+ }
+ // Round the last digit until we either have a digit that was not '9' or until
+ // we reached the first digit.
+ buffer[(*length) - 1]++;
+ for (int i = (*length) - 1; i > 0; --i) {
+ if (buffer[i] != '0' + 10) {
+ return;
+ }
+ buffer[i] = '0';
+ buffer[i - 1]++;
+ }
+ // If the first digit is now '0' + 10, we would need to set it to '0' and add
+ // a '1' in front. However we reach the first digit only if all following
+ // digits had been '9' before rounding up. Now all trailing digits are '0' and
+ // we simply switch the first digit to '1' and update the decimal-point
+ // (indicating that the point is now one digit to the right).
+ if (buffer[0] == '0' + 10) {
+ buffer[0] = '1';
+ (*decimal_point)++;
+ }
+}
+
+
+// The given fractionals number represents a fixed-point number with binary
+// point at bit (-exponent).
+// Preconditions:
+// -128 <= exponent <= 0.
+// 0 <= fractionals * 2^exponent < 1
+// The buffer holds the result.
+// The function will round its result. During the rounding-process digits not
+// generated by this function might be updated, and the decimal-point variable
+// might be updated. If this function generates the digits 99 and the buffer
+// already contained "199" (thus yielding a buffer of "19999") then a
+// rounding-up will change the contents of the buffer to "20000".
+static void FillFractionals(uint64_t fractionals, int exponent,
+ int fractional_count, Vector<char> buffer,
+ int* length, int* decimal_point) {
+ ASSERT(-128 <= exponent && exponent <= 0);
+ // 'fractionals' is a fixed-point number, with binary point at bit
+ // (-exponent). Inside the function the non-converted remainder of fractionals
+ // is a fixed-point number, with binary point at bit 'point'.
+ if (-exponent <= 64) {
+ // One 64 bit number is sufficient.
+ ASSERT(fractionals >> 56 == 0);
+ int point = -exponent;
+ for (int i = 0; i < fractional_count; ++i) {
+ if (fractionals == 0) break;
+ // Instead of multiplying by 10 we multiply by 5 and adjust the point
+ // location. This way the fractionals variable will not overflow.
+ // Invariant at the beginning of the loop: fractionals < 2^point.
+ // Initially we have: point <= 64 and fractionals < 2^56
+ // After each iteration the point is decremented by one.
+ // Note that 5^3 = 125 < 128 = 2^7.
+ // Therefore three iterations of this loop will not overflow fractionals
+ // (even without the subtraction at the end of the loop body). At this
+ // time point will satisfy point <= 61 and therefore fractionals < 2^point
+ // and any further multiplication of fractionals by 5 will not overflow.
+ fractionals *= 5;
+ point--;
+ int digit = static_cast<int>(fractionals >> point);
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ fractionals -= static_cast<uint64_t>(digit) << point;
+ }
+ // If the first bit after the point is set we have to round up.
+ if (((fractionals >> (point - 1)) & 1) == 1) {
+ RoundUp(buffer, length, decimal_point);
+ }
+ } else { // We need 128 bits.
+ ASSERT(64 < -exponent && -exponent <= 128);
+ UInt128 fractionals128 = UInt128(fractionals, 0);
+ fractionals128.Shift(-exponent - 64);
+ int point = 128;
+ for (int i = 0; i < fractional_count; ++i) {
+ if (fractionals128.IsZero()) break;
+ // As before: instead of multiplying by 10 we multiply by 5 and adjust the
+ // point location.
+ // This multiplication will not overflow for the same reasons as before.
+ fractionals128.Multiply(5);
+ point--;
+ int digit = fractionals128.DivModPowerOf2(point);
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ }
+ if (fractionals128.BitAt(point - 1) == 1) {
+ RoundUp(buffer, length, decimal_point);
+ }
+ }
+}
+
+
+// Removes leading and trailing zeros.
+// If leading zeros are removed then the decimal point position is adjusted.
+static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
+ while (*length > 0 && buffer[(*length) - 1] == '0') {
+ (*length)--;
+ }
+ int first_non_zero = 0;
+ while (first_non_zero < *length && buffer[first_non_zero] == '0') {
+ first_non_zero++;
+ }
+ if (first_non_zero != 0) {
+ for (int i = first_non_zero; i < *length; ++i) {
+ buffer[i - first_non_zero] = buffer[i];
+ }
+ *length -= first_non_zero;
+ *decimal_point -= first_non_zero;
+ }
+}
+
+
+bool FastFixedDtoa(double v,
+ int fractional_count,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_point) {
+ const uint32_t kMaxUInt32 = 0xFFFFFFFF;
+ uint64_t significand = Double(v).Significand();
+ int exponent = Double(v).Exponent();
+ // v = significand * 2^exponent (with significand a 53bit integer).
+ // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
+ // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
+ // If necessary this limit could probably be increased, but we don't need
+ // more.
+ if (exponent > 20) return false;
+ if (fractional_count > 20) return false;
+ *length = 0;
+ // At most kDoubleSignificandSize bits of the significand are non-zero.
+ // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
+ // bits: 0..11*..0xxx..53*..xx
+ if (exponent + kDoubleSignificandSize > 64) {
+ // The exponent must be > 11.
+ //
+ // We know that v = significand * 2^exponent.
+ // And the exponent > 11.
+ // We simplify the task by dividing v by 10^17.
+ // The quotient delivers the first digits, and the remainder fits into a 64
+ // bit number.
+ // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
+ const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
+ uint64_t divisor = kFive17;
+ int divisor_power = 17;
+ uint64_t dividend = significand;
+ uint32_t quotient;
+ uint64_t remainder;
+ // Let v = f * 2^e with f == significand and e == exponent.
+ // Then need q (quotient) and r (remainder) as follows:
+ // v = q * 10^17 + r
+ // f * 2^e = q * 10^17 + r
+ // f * 2^e = q * 5^17 * 2^17 + r
+ // If e > 17 then
+ // f * 2^(e-17) = q * 5^17 + r/2^17
+ // else
+ // f = q * 5^17 * 2^(17-e) + r/2^e
+ if (exponent > divisor_power) {
+ // We only allow exponents of up to 20 and therefore (17 - e) <= 3
+ dividend <<= exponent - divisor_power;
+ quotient = static_cast<uint32_t>(dividend / divisor);
+ remainder = (dividend % divisor) << divisor_power;
+ } else {
+ divisor <<= divisor_power - exponent;
+ quotient = static_cast<uint32_t>(dividend / divisor);
+ remainder = (dividend % divisor) << exponent;
+ }
+ FillDigits32(quotient, buffer, length);
+ FillDigits64FixedLength(remainder, divisor_power, buffer, length);
+ *decimal_point = *length;
+ } else if (exponent >= 0) {
+ // 0 <= exponent <= 11
+ significand <<= exponent;
+ FillDigits64(significand, buffer, length);
+ *decimal_point = *length;
+ } else if (exponent > -kDoubleSignificandSize) {
+ // We have to cut the number.
+ uint64_t integrals = significand >> -exponent;
+ uint64_t fractionals = significand - (integrals << -exponent);
+ if (integrals > kMaxUInt32) {
+ FillDigits64(integrals, buffer, length);
+ } else {
+ FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
+ }
+ *decimal_point = *length;
+ FillFractionals(fractionals, exponent, fractional_count,
+ buffer, length, decimal_point);
+ } else if (exponent < -128) {
+ // This configuration (with at most 20 digits) means that all digits must be
+ // 0.
+ ASSERT(fractional_count <= 20);
+ buffer[0] = '\0';
+ *length = 0;
+ *decimal_point = -fractional_count;
+ } else {
+ *decimal_point = 0;
+ FillFractionals(significand, exponent, fractional_count,
+ buffer, length, decimal_point);
+ }
+ TrimZeros(buffer, length, decimal_point);
+ buffer[*length] = '\0';
+ if ((*length) == 0) {
+ // The string is empty and the decimal_point thus has no importance. Mimick
+ // Gay's dtoa and and set it to -fractional_count.
+ *decimal_point = -fractional_count;
+ }
+ return true;
+}
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/fixed-dtoa.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/fixed-dtoa.h b/src/jiffy/c_src/double-conversion/fixed-dtoa.h
new file mode 100644
index 0000000..3bdd08e
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/fixed-dtoa.h
@@ -0,0 +1,56 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_FIXED_DTOA_H_
+#define DOUBLE_CONVERSION_FIXED_DTOA_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+// Produces digits necessary to print a given number with
+// 'fractional_count' digits after the decimal point.
+// The buffer must be big enough to hold the result plus one terminating null
+// character.
+//
+// The produced digits might be too short in which case the caller has to fill
+// the gaps with '0's.
+// Example: FastFixedDtoa(0.001, 5, ...) is allowed to return buffer = "1", and
+// decimal_point = -2.
+// Halfway cases are rounded towards +/-Infinity (away from 0). The call
+// FastFixedDtoa(0.15, 2, ...) thus returns buffer = "2", decimal_point = 0.
+// The returned buffer may contain digits that would be truncated from the
+// shortest representation of the input.
+//
+// This method only works for some parameters. If it can't handle the input it
+// returns false. The output is null-terminated when the function succeeds.
+bool FastFixedDtoa(double v, int fractional_count,
+ Vector<char> buffer, int* length, int* decimal_point);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_FIXED_DTOA_H_
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/ieee.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/ieee.h b/src/jiffy/c_src/double-conversion/ieee.h
new file mode 100644
index 0000000..839dc47
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/ieee.h
@@ -0,0 +1,398 @@
+// Copyright 2012 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_DOUBLE_H_
+#define DOUBLE_CONVERSION_DOUBLE_H_
+
+#include "diy-fp.h"
+
+namespace double_conversion {
+
+// We assume that doubles and uint64_t have the same endianness.
+static uint64_t double_to_uint64(double d) { return BitCast<uint64_t>(d); }
+static double uint64_to_double(uint64_t d64) { return BitCast<double>(d64); }
+static uint32_t float_to_uint32(float f) { return BitCast<uint32_t>(f); }
+static float uint32_to_float(uint32_t d32) { return BitCast<float>(d32); }
+
+// Helper functions for doubles.
+class Double {
+ public:
+ static const uint64_t kSignMask = UINT64_2PART_C(0x80000000, 00000000);
+ static const uint64_t kExponentMask = UINT64_2PART_C(0x7FF00000, 00000000);
+ static const uint64_t kSignificandMask = UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
+ static const uint64_t kHiddenBit = UINT64_2PART_C(0x00100000, 00000000);
+ static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit.
+ static const int kSignificandSize = 53;
+
+ Double() : d64_(0) {}
+ explicit Double(double d) : d64_(double_to_uint64(d)) {}
+ explicit Double(uint64_t d64) : d64_(d64) {}
+ explicit Double(DiyFp diy_fp)
+ : d64_(DiyFpToUint64(diy_fp)) {}
+
+ // The value encoded by this Double must be greater or equal to +0.0.
+ // It must not be special (infinity, or NaN).
+ DiyFp AsDiyFp() const {
+ ASSERT(Sign() > 0);
+ ASSERT(!IsSpecial());
+ return DiyFp(Significand(), Exponent());
+ }
+
+ // The value encoded by this Double must be strictly greater than 0.
+ DiyFp AsNormalizedDiyFp() const {
+ ASSERT(value() > 0.0);
+ uint64_t f = Significand();
+ int e = Exponent();
+
+ // The current double could be a denormal.
+ while ((f & kHiddenBit) == 0) {
+ f <<= 1;
+ e--;
+ }
+ // Do the final shifts in one go.
+ f <<= DiyFp::kSignificandSize - kSignificandSize;
+ e -= DiyFp::kSignificandSize - kSignificandSize;
+ return DiyFp(f, e);
+ }
+
+ // Returns the double's bit as uint64.
+ uint64_t AsUint64() const {
+ return d64_;
+ }
+
+ // Returns the next greater double. Returns +infinity on input +infinity.
+ double NextDouble() const {
+ if (d64_ == kInfinity) return Double(kInfinity).value();
+ if (Sign() < 0 && Significand() == 0) {
+ // -0.0
+ return 0.0;
+ }
+ if (Sign() < 0) {
+ return Double(d64_ - 1).value();
+ } else {
+ return Double(d64_ + 1).value();
+ }
+ }
+
+ double PreviousDouble() const {
+ if (d64_ == (kInfinity | kSignMask)) return -Double::Infinity();
+ if (Sign() < 0) {
+ return Double(d64_ + 1).value();
+ } else {
+ if (Significand() == 0) return -0.0;
+ return Double(d64_ - 1).value();
+ }
+ }
+
+ int Exponent() const {
+ if (IsDenormal()) return kDenormalExponent;
+
+ uint64_t d64 = AsUint64();
+ int biased_e =
+ static_cast<int>((d64 & kExponentMask) >> kPhysicalSignificandSize);
+ return biased_e - kExponentBias;
+ }
+
+ uint64_t Significand() const {
+ uint64_t d64 = AsUint64();
+ uint64_t significand = d64 & kSignificandMask;
+ if (!IsDenormal()) {
+ return significand + kHiddenBit;
+ } else {
+ return significand;
+ }
+ }
+
+ // Returns true if the double is a denormal.
+ bool IsDenormal() const {
+ uint64_t d64 = AsUint64();
+ return (d64 & kExponentMask) == 0;
+ }
+
+ // We consider denormals not to be special.
+ // Hence only Infinity and NaN are special.
+ bool IsSpecial() const {
+ uint64_t d64 = AsUint64();
+ return (d64 & kExponentMask) == kExponentMask;
+ }
+
+ bool IsNan() const {
+ uint64_t d64 = AsUint64();
+ return ((d64 & kExponentMask) == kExponentMask) &&
+ ((d64 & kSignificandMask) != 0);
+ }
+
+ bool IsInfinite() const {
+ uint64_t d64 = AsUint64();
+ return ((d64 & kExponentMask) == kExponentMask) &&
+ ((d64 & kSignificandMask) == 0);
+ }
+
+ int Sign() const {
+ uint64_t d64 = AsUint64();
+ return (d64 & kSignMask) == 0? 1: -1;
+ }
+
+ // Precondition: the value encoded by this Double must be greater or equal
+ // than +0.0.
+ DiyFp UpperBoundary() const {
+ ASSERT(Sign() > 0);
+ return DiyFp(Significand() * 2 + 1, Exponent() - 1);
+ }
+
+ // Computes the two boundaries of this.
+ // The bigger boundary (m_plus) is normalized. The lower boundary has the same
+ // exponent as m_plus.
+ // Precondition: the value encoded by this Double must be greater than 0.
+ void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
+ ASSERT(value() > 0.0);
+ DiyFp v = this->AsDiyFp();
+ DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
+ DiyFp m_minus;
+ if (LowerBoundaryIsCloser()) {
+ m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
+ } else {
+ m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
+ }
+ m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
+ m_minus.set_e(m_plus.e());
+ *out_m_plus = m_plus;
+ *out_m_minus = m_minus;
+ }
+
+ bool LowerBoundaryIsCloser() const {
+ // The boundary is closer if the significand is of the form f == 2^p-1 then
+ // the lower boundary is closer.
+ // Think of v = 1000e10 and v- = 9999e9.
+ // Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
+ // at a distance of 1e8.
+ // The only exception is for the smallest normal: the largest denormal is
+ // at the same distance as its successor.
+ // Note: denormals have the same exponent as the smallest normals.
+ bool physical_significand_is_zero = ((AsUint64() & kSignificandMask) == 0);
+ return physical_significand_is_zero && (Exponent() != kDenormalExponent);
+ }
+
+ double value() const { return uint64_to_double(d64_); }
+
+ // Returns the significand size for a given order of magnitude.
+ // If v = f*2^e with 2^p-1 <= f <= 2^p then p+e is v's order of magnitude.
+ // This function returns the number of significant binary digits v will have
+ // once it's encoded into a double. In almost all cases this is equal to
+ // kSignificandSize. The only exceptions are denormals. They start with
+ // leading zeroes and their effective significand-size is hence smaller.
+ static int SignificandSizeForOrderOfMagnitude(int order) {
+ if (order >= (kDenormalExponent + kSignificandSize)) {
+ return kSignificandSize;
+ }
+ if (order <= kDenormalExponent) return 0;
+ return order - kDenormalExponent;
+ }
+
+ static double Infinity() {
+ return Double(kInfinity).value();
+ }
+
+ static double NaN() {
+ return Double(kNaN).value();
+ }
+
+ private:
+ static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
+ static const int kDenormalExponent = -kExponentBias + 1;
+ static const int kMaxExponent = 0x7FF - kExponentBias;
+ static const uint64_t kInfinity = UINT64_2PART_C(0x7FF00000, 00000000);
+ static const uint64_t kNaN = UINT64_2PART_C(0x7FF80000, 00000000);
+
+ const uint64_t d64_;
+
+ static uint64_t DiyFpToUint64(DiyFp diy_fp) {
+ uint64_t significand = diy_fp.f();
+ int exponent = diy_fp.e();
+ while (significand > kHiddenBit + kSignificandMask) {
+ significand >>= 1;
+ exponent++;
+ }
+ if (exponent >= kMaxExponent) {
+ return kInfinity;
+ }
+ if (exponent < kDenormalExponent) {
+ return 0;
+ }
+ while (exponent > kDenormalExponent && (significand & kHiddenBit) == 0) {
+ significand <<= 1;
+ exponent--;
+ }
+ uint64_t biased_exponent;
+ if (exponent == kDenormalExponent && (significand & kHiddenBit) == 0) {
+ biased_exponent = 0;
+ } else {
+ biased_exponent = static_cast<uint64_t>(exponent + kExponentBias);
+ }
+ return (significand & kSignificandMask) |
+ (biased_exponent << kPhysicalSignificandSize);
+ }
+};
+
+class Single {
+ public:
+ static const uint32_t kSignMask = 0x80000000;
+ static const uint32_t kExponentMask = 0x7F800000;
+ static const uint32_t kSignificandMask = 0x007FFFFF;
+ static const uint32_t kHiddenBit = 0x00800000;
+ static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit.
+ static const int kSignificandSize = 24;
+
+ Single() : d32_(0) {}
+ explicit Single(float f) : d32_(float_to_uint32(f)) {}
+ explicit Single(uint32_t d32) : d32_(d32) {}
+
+ // The value encoded by this Single must be greater or equal to +0.0.
+ // It must not be special (infinity, or NaN).
+ DiyFp AsDiyFp() const {
+ ASSERT(Sign() > 0);
+ ASSERT(!IsSpecial());
+ return DiyFp(Significand(), Exponent());
+ }
+
+ // Returns the single's bit as uint64.
+ uint32_t AsUint32() const {
+ return d32_;
+ }
+
+ int Exponent() const {
+ if (IsDenormal()) return kDenormalExponent;
+
+ uint32_t d32 = AsUint32();
+ int biased_e =
+ static_cast<int>((d32 & kExponentMask) >> kPhysicalSignificandSize);
+ return biased_e - kExponentBias;
+ }
+
+ uint32_t Significand() const {
+ uint32_t d32 = AsUint32();
+ uint32_t significand = d32 & kSignificandMask;
+ if (!IsDenormal()) {
+ return significand + kHiddenBit;
+ } else {
+ return significand;
+ }
+ }
+
+ // Returns true if the single is a denormal.
+ bool IsDenormal() const {
+ uint32_t d32 = AsUint32();
+ return (d32 & kExponentMask) == 0;
+ }
+
+ // We consider denormals not to be special.
+ // Hence only Infinity and NaN are special.
+ bool IsSpecial() const {
+ uint32_t d32 = AsUint32();
+ return (d32 & kExponentMask) == kExponentMask;
+ }
+
+ bool IsNan() const {
+ uint32_t d32 = AsUint32();
+ return ((d32 & kExponentMask) == kExponentMask) &&
+ ((d32 & kSignificandMask) != 0);
+ }
+
+ bool IsInfinite() const {
+ uint32_t d32 = AsUint32();
+ return ((d32 & kExponentMask) == kExponentMask) &&
+ ((d32 & kSignificandMask) == 0);
+ }
+
+ int Sign() const {
+ uint32_t d32 = AsUint32();
+ return (d32 & kSignMask) == 0? 1: -1;
+ }
+
+ // Computes the two boundaries of this.
+ // The bigger boundary (m_plus) is normalized. The lower boundary has the same
+ // exponent as m_plus.
+ // Precondition: the value encoded by this Single must be greater than 0.
+ void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
+ ASSERT(value() > 0.0);
+ DiyFp v = this->AsDiyFp();
+ DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
+ DiyFp m_minus;
+ if (LowerBoundaryIsCloser()) {
+ m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
+ } else {
+ m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
+ }
+ m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
+ m_minus.set_e(m_plus.e());
+ *out_m_plus = m_plus;
+ *out_m_minus = m_minus;
+ }
+
+ // Precondition: the value encoded by this Single must be greater or equal
+ // than +0.0.
+ DiyFp UpperBoundary() const {
+ ASSERT(Sign() > 0);
+ return DiyFp(Significand() * 2 + 1, Exponent() - 1);
+ }
+
+ bool LowerBoundaryIsCloser() const {
+ // The boundary is closer if the significand is of the form f == 2^p-1 then
+ // the lower boundary is closer.
+ // Think of v = 1000e10 and v- = 9999e9.
+ // Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
+ // at a distance of 1e8.
+ // The only exception is for the smallest normal: the largest denormal is
+ // at the same distance as its successor.
+ // Note: denormals have the same exponent as the smallest normals.
+ bool physical_significand_is_zero = ((AsUint32() & kSignificandMask) == 0);
+ return physical_significand_is_zero && (Exponent() != kDenormalExponent);
+ }
+
+ float value() const { return uint32_to_float(d32_); }
+
+ static float Infinity() {
+ return Single(kInfinity).value();
+ }
+
+ static float NaN() {
+ return Single(kNaN).value();
+ }
+
+ private:
+ static const int kExponentBias = 0x7F + kPhysicalSignificandSize;
+ static const int kDenormalExponent = -kExponentBias + 1;
+ static const int kMaxExponent = 0xFF - kExponentBias;
+ static const uint32_t kInfinity = 0x7F800000;
+ static const uint32_t kNaN = 0x7FC00000;
+
+ const uint32_t d32_;
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_DOUBLE_H_
[05/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/006-maps.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/006-maps.t b/src/jiffy/test/006-maps.t
new file mode 100755
index 0000000..45e715c
--- /dev/null
+++ b/src/jiffy/test/006-maps.t
@@ -0,0 +1,36 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(15),
+ util:test_good(good()),
+ util:test_errors(errors()),
+ etap:end_tests().
+
+good() ->
+ [
+ {<<"{}">>, {[]}},
+ {<<"{\"foo\": \"bar\"}">>,
+ {[{<<"foo">>, <<"bar">>}]},
+ <<"{\"foo\":\"bar\"}">>},
+ {<<"\n\n{\"foo\":\r \"bar\",\n \"baz\"\t: 123 }">>,
+ {[{<<"foo">>, <<"bar">>}, {<<"baz">>, 123}]},
+ <<"{\"foo\":\"bar\",\"baz\":123}">>}
+ ].
+
+errors() ->
+ [
+ <<"{">>,
+ <<"{,}">>,
+ <<"{123:true}">>,
+ <<"{false:123}">>,
+ <<"{:\"stuff\"}">>,
+ <<"{\"key\":}">>,
+ <<"{\"key\": 123">>,
+ <<"{\"key\": 123 true">>,
+ <<"{\"key\": 123,}">>
+ ].
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/007-compound.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/007-compound.t b/src/jiffy/test/007-compound.t
new file mode 100755
index 0000000..2770971
--- /dev/null
+++ b/src/jiffy/test/007-compound.t
@@ -0,0 +1,41 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(12),
+ util:test_good(good()),
+ util:test_errors(errors()),
+ etap:end_tests().
+
+good() ->
+ [
+ {<<"[{}]">>, [{[]}]},
+ {<<"{\"foo\":[123]}">>, {[{<<"foo">>, [123]}]}},
+ {<<"{\"foo\":{\"bar\":true}}">>,
+ {[{<<"foo">>, {[{<<"bar">>, true}]} }]} },
+ {<<"{\"foo\":[],\"bar\":{\"baz\":true},\"alice\":\"bob\"}">>,
+ {[
+ {<<"foo">>, []},
+ {<<"bar">>, {[{<<"baz">>, true}]}},
+ {<<"alice">>, <<"bob">>}
+ ]}
+ },
+ {<<"[-123,\"foo\",{\"bar\":[]},null]">>,
+ [
+ -123,
+ <<"foo">>,
+ {[{<<"bar">>, []}]},
+ null
+ ]
+ }
+ ].
+
+errors() ->
+ [
+ <<"[{}">>,
+ <<"}]">>
+ ].
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/008-halfword.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/008-halfword.t b/src/jiffy/test/008-halfword.t
new file mode 100755
index 0000000..56f0439
--- /dev/null
+++ b/src/jiffy/test/008-halfword.t
@@ -0,0 +1,15 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(unknown),
+
+ etap:is(jiffy:decode(<<"1">>) =:= 1, true, "1 =:= 1"),
+ etap:is(jiffy:decode(<<"1">>) == 1, true, "1 == 1"),
+
+ etap:end_tests().
+
[12/12] git commit: updated refs/heads/1843-replace-ejson-with-jiffy
to 2e6092e
Posted by rn...@apache.org.
Replace ejson with jiffy
Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/2e6092e4
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/2e6092e4
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/2e6092e4
Branch: refs/heads/1843-replace-ejson-with-jiffy
Commit: 2e6092e4ee0fb3f42da9a6e5b361f0de010486af
Parents: 81b75f5
Author: Robert Newson <rn...@apache.org>
Authored: Mon Dec 23 12:21:14 2013 +0000
Committer: Robert Newson <rn...@apache.org>
Committed: Mon Dec 23 13:36:24 2013 +0000
----------------------------------------------------------------------
rebar.config | 2 +-
src/couch/include/couch_db.hrl | 4 +-
.../couch_ejson_compare/couch_ejson_compare.c | 457 -
src/couch/src/couch_ejson_compare.erl | 113 -
src/couch/src/couch_util.erl | 12 +
src/ejson/c_src/decode.c | 308 -
src/ejson/c_src/ejson.c | 30 -
src/ejson/c_src/encode.c | 200 -
src/ejson/c_src/erl_nif_compat.h | 120 -
src/ejson/c_src/yajl/yajl.c | 159 -
src/ejson/c_src/yajl/yajl_alloc.c | 65 -
src/ejson/c_src/yajl/yajl_alloc.h | 50 -
src/ejson/c_src/yajl/yajl_buf.c | 119 -
src/ejson/c_src/yajl/yajl_buf.h | 73 -
src/ejson/c_src/yajl/yajl_bytestack.h | 85 -
src/ejson/c_src/yajl/yajl_common.h | 85 -
src/ejson/c_src/yajl/yajl_encode.c | 188 -
src/ejson/c_src/yajl/yajl_encode.h | 50 -
src/ejson/c_src/yajl/yajl_gen.c | 322 -
src/ejson/c_src/yajl/yajl_gen.h | 159 -
src/ejson/c_src/yajl/yajl_lex.c | 737 -
src/ejson/c_src/yajl/yajl_lex.h | 133 -
src/ejson/c_src/yajl/yajl_parse.h | 193 -
src/ejson/c_src/yajl/yajl_parser.c | 470 -
src/ejson/c_src/yajl/yajl_parser.h | 95 -
src/ejson/src/ejson.app.src | 9 -
src/ejson/src/ejson.erl | 168 -
src/ejson/src/mochijson2.erl | 849 -
src/ejson/src/mochinum.erl | 354 -
src/jiffy/.gitignore | 7 +
src/jiffy/LICENSE | 90 +
src/jiffy/Makefile | 47 +
src/jiffy/README.md | 58 +
src/jiffy/c_src/decoder.c | 914 +
src/jiffy/c_src/double-conversion/AUTHORS | 12 +
src/jiffy/c_src/double-conversion/COPYING | 26 +
src/jiffy/c_src/double-conversion/DOWNLOADED | 3 +
src/jiffy/c_src/double-conversion/LICENSE | 26 +
src/jiffy/c_src/double-conversion/README | 11 +
.../c_src/double-conversion/bignum-dtoa.cc | 640 +
src/jiffy/c_src/double-conversion/bignum-dtoa.h | 84 +
src/jiffy/c_src/double-conversion/bignum.cc | 764 +
src/jiffy/c_src/double-conversion/bignum.h | 145 +
.../c_src/double-conversion/cached-powers.cc | 175 +
.../c_src/double-conversion/cached-powers.h | 64 +
src/jiffy/c_src/double-conversion/diy-fp.cc | 57 +
src/jiffy/c_src/double-conversion/diy-fp.h | 118 +
.../double-conversion/double-conversion.cc | 889 +
.../c_src/double-conversion/double-conversion.h | 536 +
src/jiffy/c_src/double-conversion/fast-dtoa.cc | 666 +
src/jiffy/c_src/double-conversion/fast-dtoa.h | 88 +
src/jiffy/c_src/double-conversion/fixed-dtoa.cc | 402 +
src/jiffy/c_src/double-conversion/fixed-dtoa.h | 56 +
src/jiffy/c_src/double-conversion/ieee.h | 398 +
src/jiffy/c_src/double-conversion/strtod.cc | 554 +
src/jiffy/c_src/double-conversion/strtod.h | 45 +
src/jiffy/c_src/double-conversion/utils.h | 326 +
src/jiffy/c_src/doubles.cc | 33 +
src/jiffy/c_src/encoder.c | 709 +
src/jiffy/c_src/jiffy.c | 61 +
src/jiffy/c_src/jiffy.h | 45 +
src/jiffy/c_src/utf8.c | 249 +
src/jiffy/c_src/util.c | 26 +
src/jiffy/rebar.config | 34 +
src/jiffy/rebar.config.script | 33 +
src/jiffy/src/jiffy.app.src | 6 +
src/jiffy/src/jiffy.erl | 107 +
src/jiffy/src/jiffy_utf8.erl | 104 +
src/jiffy/test/001-yajl-tests.t | 30 +
src/jiffy/test/002-literals.t | 21 +
src/jiffy/test/003-numbers.t | 118 +
src/jiffy/test/004-strings.t | 131 +
src/jiffy/test/005-arrays.t | 36 +
src/jiffy/test/006-maps.t | 36 +
src/jiffy/test/007-compound.t | 41 +
src/jiffy/test/008-halfword.t | 15 +
src/jiffy/test/009-reg-issue-24.t | 3459 +
src/jiffy/test/010-short-doubles.t | 29 +
src/jiffy/test/cases/array.eterm | 16 +
src/jiffy/test/cases/array.json | 6 +
src/jiffy/test/cases/array_close.eterm | 1 +
src/jiffy/test/cases/array_close.json | 1 +
src/jiffy/test/cases/array_open.eterm | 1 +
src/jiffy/test/cases/array_open.json | 1 +
src/jiffy/test/cases/bogus_char.eterm | 1 +
src/jiffy/test/cases/bogus_char.json | 4 +
.../cases/codepoints_from_unicode_org.eterm | 1 +
.../test/cases/codepoints_from_unicode_org.json | 1 +
src/jiffy/test/cases/deep_arrays.eterm | 1 +
src/jiffy/test/cases/deep_arrays.json | 1 +
.../test/cases/difficult_json_c_test_case.eterm | 19 +
.../test/cases/difficult_json_c_test_case.json | 1 +
src/jiffy/test/cases/doubles.eterm | 1 +
src/jiffy/test/cases/doubles.json | 1 +
src/jiffy/test/cases/empty_array.eterm | 1 +
src/jiffy/test/cases/empty_array.json | 1 +
src/jiffy/test/cases/empty_string.eterm | 1 +
src/jiffy/test/cases/empty_string.json | 1 +
src/jiffy/test/cases/escaped_bulgarian.eterm | 6 +
src/jiffy/test/cases/escaped_bulgarian.json | 4 +
src/jiffy/test/cases/escaped_foobar.eterm | 1 +
src/jiffy/test/cases/escaped_foobar.json | 1 +
src/jiffy/test/cases/false.eterm | 1 +
src/jiffy/test/cases/false.json | 1 +
src/jiffy/test/cases/false_then_garbage.eterm | 1 +
src/jiffy/test/cases/false_then_garbage.json | 1 +
src/jiffy/test/cases/four_byte_utf8.eterm | 1 +
src/jiffy/test/cases/four_byte_utf8.json | 2 +
src/jiffy/test/cases/integers.eterm | 13 +
src/jiffy/test/cases/integers.json | 3 +
src/jiffy/test/cases/invalid_utf8.eterm | 1 +
src/jiffy/test/cases/invalid_utf8.json | 1 +
.../test/cases/isolated_surrogate_marker.eterm | 1 +
.../test/cases/isolated_surrogate_marker.json | 1 +
.../test/cases/leading_zero_in_number.eterm | 1 +
.../test/cases/leading_zero_in_number.json | 1 +
src/jiffy/test/cases/lonely_minus_sign.eterm | 1 +
src/jiffy/test/cases/lonely_minus_sign.json | 7 +
src/jiffy/test/cases/lonely_number.eterm | 1 +
src/jiffy/test/cases/lonely_number.json | 1 +
src/jiffy/test/cases/map_close.eterm | 1 +
src/jiffy/test/cases/map_close.json | 1 +
src/jiffy/test/cases/map_open.eterm | 1 +
src/jiffy/test/cases/map_open.json | 1 +
.../missing_integer_after_decimal_point.eterm | 1 +
.../missing_integer_after_decimal_point.json | 1 +
.../cases/missing_integer_after_exponent.eterm | 1 +
.../cases/missing_integer_after_exponent.json | 1 +
.../test/cases/non_utf8_char_in_string.eterm | 1 +
.../test/cases/non_utf8_char_in_string.json | 1 +
src/jiffy/test/cases/null.eterm | 1 +
src/jiffy/test/cases/null.json | 1 +
src/jiffy/test/cases/null_then_garbage.eterm | 1 +
src/jiffy/test/cases/null_then_garbage.json | 1 +
src/jiffy/test/cases/nulls_and_bools.eterm | 5 +
src/jiffy/test/cases/nulls_and_bools.json | 5 +
src/jiffy/test/cases/short-doubles.txt | 100000 ++++++++++++++++
src/jiffy/test/cases/simple.eterm | 5 +
src/jiffy/test/cases/simple.json | 5 +
.../test/cases/string_invalid_escape.eterm | 1 +
src/jiffy/test/cases/string_invalid_escape.json | 1 +
.../test/cases/string_invalid_hex_char.eterm | 1 +
.../test/cases/string_invalid_hex_char.json | 1 +
src/jiffy/test/cases/string_with_escapes.eterm | 5 +
src/jiffy/test/cases/string_with_escapes.json | 3 +
.../cases/string_with_invalid_newline.eterm | 1 +
.../test/cases/string_with_invalid_newline.json | 2 +
src/jiffy/test/cases/three_byte_utf8.eterm | 4 +
src/jiffy/test/cases/three_byte_utf8.json | 1 +
src/jiffy/test/cases/true.eterm | 1 +
src/jiffy/test/cases/true.json | 1 +
src/jiffy/test/cases/true_then_garbage.eterm | 1 +
src/jiffy/test/cases/true_then_garbage.json | 1 +
src/jiffy/test/cases/unescaped_bulgarian.eterm | 5 +
src/jiffy/test/cases/unescaped_bulgarian.json | 1 +
src/jiffy/test/etap.erl | 612 +
src/jiffy/test/jiffy_tests.erl | 135 +
src/jiffy/test/util.erl | 44 +
158 files changed, 113506 insertions(+), 5594 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/rebar.config
----------------------------------------------------------------------
diff --git a/rebar.config b/rebar.config
index 1ae51fd..ad484a2 100644
--- a/rebar.config
+++ b/rebar.config
@@ -21,7 +21,7 @@
"src/chttpd",
"src/couch_replicator",
"src/ddoc_cache",
- "src/ejson",
+ "src/jiffy",
"src/ets_lru",
"src/fabric",
"src/mochiweb",
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/couch/include/couch_db.hrl
----------------------------------------------------------------------
diff --git a/src/couch/include/couch_db.hrl b/src/couch/include/couch_db.hrl
index ffecae0..2c015df 100644
--- a/src/couch/include/couch_db.hrl
+++ b/src/couch/include/couch_db.hrl
@@ -18,8 +18,8 @@
-define(MIN_STR, <<"">>).
-define(MAX_STR, <<255>>). % illegal utf string
--define(JSON_ENCODE(V), ejson:encode(V)).
--define(JSON_DECODE(V), ejson:decode(V)).
+-define(JSON_ENCODE(V), couch_util:json_encode(V)).
+-define(JSON_DECODE(V), couch_util:json_decode(V)).
-define(b2l(V), binary_to_list(V)).
-define(l2b(V), list_to_binary(V)).
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/couch/priv/couch_ejson_compare/couch_ejson_compare.c
----------------------------------------------------------------------
diff --git a/src/couch/priv/couch_ejson_compare/couch_ejson_compare.c b/src/couch/priv/couch_ejson_compare/couch_ejson_compare.c
deleted file mode 100644
index df68c2a..0000000
--- a/src/couch/priv/couch_ejson_compare/couch_ejson_compare.c
+++ /dev/null
@@ -1,457 +0,0 @@
-/**
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-#include <stdio.h>
-#include <assert.h>
-#include "erl_nif_compat.h"
-#include "unicode/ucol.h"
-#include "unicode/ucasemap.h"
-
-#define MAX_DEPTH 10
-
-#if (ERL_NIF_MAJOR_VERSION > 2) || \
- (ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION >= 3)
-/* OTP R15B or higher */
-#define term_is_number(env, t) enif_is_number(env, t)
-#else
-#define term_is_number(env, t) \
- (!enif_is_binary(env, t) && \
- !enif_is_list(env, t) && \
- !enif_is_tuple(env, t))
-#endif
-
-static ERL_NIF_TERM ATOM_TRUE;
-static ERL_NIF_TERM ATOM_FALSE;
-static ERL_NIF_TERM ATOM_NULL;
-
-typedef struct {
- ErlNifEnv* env;
- int error;
- UCollator* coll;
-} ctx_t;
-
-static UCollator** collators = NULL;
-static int collStackTop = 0;
-static int numCollators = 0;
-static ErlNifMutex* collMutex = NULL;
-
-static ERL_NIF_TERM less_json_nif(ErlNifEnv*, int, const ERL_NIF_TERM []);
-static int on_load(ErlNifEnv*, void**, ERL_NIF_TERM);
-static void on_unload(ErlNifEnv*, void*);
-static __inline int less_json(int, ctx_t*, ERL_NIF_TERM, ERL_NIF_TERM);
-static __inline int atom_sort_order(ErlNifEnv*, ERL_NIF_TERM);
-static __inline int compare_strings(ctx_t*, ErlNifBinary, ErlNifBinary);
-static __inline int compare_lists(int, ctx_t*, ERL_NIF_TERM, ERL_NIF_TERM);
-static __inline int compare_props(int, ctx_t*, ERL_NIF_TERM, ERL_NIF_TERM);
-static __inline void reserve_coll(ctx_t*);
-static __inline void release_coll(ctx_t*);
-
-
-void
-reserve_coll(ctx_t *ctx)
-{
- if (ctx->coll == NULL) {
- enif_mutex_lock(collMutex);
- assert(collStackTop < numCollators);
- ctx->coll = collators[collStackTop];
- collStackTop += 1;
- enif_mutex_unlock(collMutex);
- }
-}
-
-
-void
-release_coll(ctx_t *ctx)
-{
- if (ctx->coll != NULL) {
- enif_mutex_lock(collMutex);
- collStackTop -= 1;
- assert(collStackTop >= 0);
- enif_mutex_unlock(collMutex);
- }
-}
-
-
-
-ERL_NIF_TERM
-less_json_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
-{
- ctx_t ctx;
- int result;
-
- ctx.env = env;
- ctx.error = 0;
- ctx.coll = NULL;
-
- result = less_json(1, &ctx, argv[0], argv[1]);
- release_coll(&ctx);
-
- /*
- * There are 2 possible failure reasons:
- *
- * 1) We got an invalid EJSON operand;
- * 2) The EJSON structures are too deep - to avoid allocating too
- * many C stack frames (because less_json is a recursive function),
- * and running out of memory, we throw a badarg exception to Erlang
- * and do the comparison in Erlang land. In practice, views keys are
- * EJSON structures with very little nesting.
- */
- return ctx.error ? enif_make_badarg(env) : enif_make_int(env, result);
-}
-
-
-int
-less_json(int depth, ctx_t* ctx, ERL_NIF_TERM a, ERL_NIF_TERM b)
-{
- int aIsAtom, bIsAtom;
- int aIsBin, bIsBin;
- int aIsNumber, bIsNumber;
- int aIsList, bIsList;
- int aArity, bArity;
- const ERL_NIF_TERM *aProps, *bProps;
-
- /*
- * Avoid too much recursion. Normally there isn't more than a few levels
- * of recursion, as in practice view keys do not go beyond 1 to 3 levels
- * of nesting. In case of too much recursion, signal it to the Erlang land
- * via an exception and do the EJSON comparison in Erlang land.
- */
- if (depth > MAX_DEPTH) {
- ctx->error = 1;
- return 0;
- }
-
- aIsAtom = enif_is_atom(ctx->env, a);
- bIsAtom = enif_is_atom(ctx->env, b);
-
- if (aIsAtom) {
- if (bIsAtom) {
- int aSortOrd, bSortOrd;
-
- if ((aSortOrd = atom_sort_order(ctx->env, a)) == -1) {
- ctx->error = 1;
- return 0;
- }
-
- if ((bSortOrd = atom_sort_order(ctx->env, b)) == -1) {
- ctx->error = 1;
- return 0;
- }
-
- return aSortOrd - bSortOrd;
- }
-
- return -1;
- }
-
- if (bIsAtom) {
- return 1;
- }
-
- aIsNumber = term_is_number(ctx->env, a);
- bIsNumber = term_is_number(ctx->env, b);
-
- if (aIsNumber) {
- if (bIsNumber) {
- return enif_compare_compat(ctx->env, a, b);
- }
-
- return -1;
- }
-
- if (bIsNumber) {
- return 1;
- }
-
- aIsBin = enif_is_binary(ctx->env, a);
- bIsBin = enif_is_binary(ctx->env, b);
-
- if (aIsBin) {
- if (bIsBin) {
- ErlNifBinary binA, binB;
-
- enif_inspect_binary(ctx->env, a, &binA);
- enif_inspect_binary(ctx->env, b, &binB);
-
- return compare_strings(ctx, binA, binB);
- }
-
- return -1;
- }
-
- if (bIsBin) {
- return 1;
- }
-
- aIsList = enif_is_list(ctx->env, a);
- bIsList = enif_is_list(ctx->env, b);
-
- if (aIsList) {
- if (bIsList) {
- return compare_lists(depth, ctx, a, b);
- }
-
- return -1;
- }
-
- if (bIsList) {
- return 1;
- }
-
- if (!enif_get_tuple(ctx->env, a, &aArity, &aProps)) {
- ctx->error = 1;
- return 0;
- }
- if ((aArity != 1) || !enif_is_list(ctx->env, aProps[0])) {
- ctx->error = 1;
- return 0;
- }
-
- if (!enif_get_tuple(ctx->env, b, &bArity, &bProps)) {
- ctx->error = 1;
- return 0;
- }
- if ((bArity != 1) || !enif_is_list(ctx->env, bProps[0])) {
- ctx->error = 1;
- return 0;
- }
-
- return compare_props(depth, ctx, aProps[0], bProps[0]);
-}
-
-
-int
-atom_sort_order(ErlNifEnv* env, ERL_NIF_TERM a)
-{
- if (enif_compare_compat(env, a, ATOM_NULL) == 0) {
- return 1;
- } else if (enif_compare_compat(env, a, ATOM_FALSE) == 0) {
- return 2;
- } else if (enif_compare_compat(env, a, ATOM_TRUE) == 0) {
- return 3;
- }
-
- return -1;
-}
-
-
-int
-compare_lists(int depth, ctx_t* ctx, ERL_NIF_TERM a, ERL_NIF_TERM b)
-{
- ERL_NIF_TERM headA, tailA;
- ERL_NIF_TERM headB, tailB;
- int aIsEmpty, bIsEmpty;
- int result;
-
- while (1) {
- aIsEmpty = !enif_get_list_cell(ctx->env, a, &headA, &tailA);
- bIsEmpty = !enif_get_list_cell(ctx->env, b, &headB, &tailB);
-
- if (aIsEmpty) {
- if (bIsEmpty) {
- return 0;
- }
- return -1;
- }
-
- if (bIsEmpty) {
- return 1;
- }
-
- result = less_json(depth + 1, ctx, headA, headB);
-
- if (ctx->error || result != 0) {
- return result;
- }
-
- a = tailA;
- b = tailB;
- }
-
- return result;
-}
-
-
-int
-compare_props(int depth, ctx_t* ctx, ERL_NIF_TERM a, ERL_NIF_TERM b)
-{
- ERL_NIF_TERM headA, tailA;
- ERL_NIF_TERM headB, tailB;
- int aArity, bArity;
- const ERL_NIF_TERM *aKV, *bKV;
- ErlNifBinary keyA, keyB;
- int aIsEmpty, bIsEmpty;
- int keyCompResult, valueCompResult;
-
- while (1) {
- aIsEmpty = !enif_get_list_cell(ctx->env, a, &headA, &tailA);
- bIsEmpty = !enif_get_list_cell(ctx->env, b, &headB, &tailB);
-
- if (aIsEmpty) {
- if (bIsEmpty) {
- return 0;
- }
- return -1;
- }
-
- if (bIsEmpty) {
- return 1;
- }
-
- if (!enif_get_tuple(ctx->env, headA, &aArity, &aKV)) {
- ctx->error = 1;
- return 0;
- }
- if ((aArity != 2) || !enif_inspect_binary(ctx->env, aKV[0], &keyA)) {
- ctx->error = 1;
- return 0;
- }
-
- if (!enif_get_tuple(ctx->env, headB, &bArity, &bKV)) {
- ctx->error = 1;
- return 0;
- }
- if ((bArity != 2) || !enif_inspect_binary(ctx->env, bKV[0], &keyB)) {
- ctx->error = 1;
- return 0;
- }
-
- keyCompResult = compare_strings(ctx, keyA, keyB);
-
- if (ctx->error || keyCompResult != 0) {
- return keyCompResult;
- }
-
- valueCompResult = less_json(depth + 1, ctx, aKV[1], bKV[1]);
-
- if (ctx->error || valueCompResult != 0) {
- return valueCompResult;
- }
-
- a = tailA;
- b = tailB;
- }
-
- return 0;
-}
-
-
-int
-compare_strings(ctx_t* ctx, ErlNifBinary a, ErlNifBinary b)
-{
- UErrorCode status = U_ZERO_ERROR;
- UCharIterator iterA, iterB;
- int result;
-
- uiter_setUTF8(&iterA, (const char *) a.data, (uint32_t) a.size);
- uiter_setUTF8(&iterB, (const char *) b.data, (uint32_t) b.size);
-
- reserve_coll(ctx);
- result = ucol_strcollIter(ctx->coll, &iterA, &iterB, &status);
-
- if (U_FAILURE(status)) {
- ctx->error = 1;
- return 0;
- }
-
- /* ucol_strcollIter returns 0, -1 or 1
- * (see type UCollationResult in unicode/ucol.h) */
-
- return result;
-}
-
-
-int
-on_load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)
-{
- UErrorCode status = U_ZERO_ERROR;
- int i, j;
-
- if (!enif_get_int(env, info, &numCollators)) {
- return 1;
- }
-
- if (numCollators < 1) {
- return 2;
- }
-
- collMutex = enif_mutex_create("coll_mutex");
-
- if (collMutex == NULL) {
- return 3;
- }
-
- collators = enif_alloc(sizeof(UCollator*) * numCollators);
-
- if (collators == NULL) {
- enif_mutex_destroy(collMutex);
- return 4;
- }
-
- for (i = 0; i < numCollators; i++) {
- collators[i] = ucol_open("", &status);
-
- if (U_FAILURE(status)) {
- for (j = 0; j < i; j++) {
- ucol_close(collators[j]);
- }
-
- enif_free(collators);
- enif_mutex_destroy(collMutex);
-
- return 5;
- }
- }
-
- ATOM_TRUE = enif_make_atom(env, "true");
- ATOM_FALSE = enif_make_atom(env, "false");
- ATOM_NULL = enif_make_atom(env, "null");
-
- return 0;
-}
-
-
-void
-on_unload(ErlNifEnv* env, void* priv_data)
-{
- if (collators != NULL) {
- int i;
-
- for (i = 0; i < numCollators; i++) {
- ucol_close(collators[i]);
- }
-
- enif_free(collators);
- }
-
- if (collMutex != NULL) {
- enif_mutex_destroy(collMutex);
- }
-}
-
-
-static ErlNifFunc nif_functions[] = {
- {"less_nif", 2, less_json_nif}
-};
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-ERL_NIF_INIT(couch_ejson_compare, nif_functions, &on_load, NULL, NULL, &on_unload);
-
-#ifdef __cplusplus
-}
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/couch/src/couch_ejson_compare.erl
----------------------------------------------------------------------
diff --git a/src/couch/src/couch_ejson_compare.erl b/src/couch/src/couch_ejson_compare.erl
deleted file mode 100644
index 7b000fc..0000000
--- a/src/couch/src/couch_ejson_compare.erl
+++ /dev/null
@@ -1,113 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_ejson_compare).
-
--export([less/2, less_json_ids/2, less_json/2]).
-
--on_load(init/0).
-
-
-init() ->
- LibDir = case config:get("couchdb", "util_driver_dir") of
- undefined ->
- filename:join(couch_util:priv_dir(), "lib");
- LibDir0 ->
- LibDir0
- end,
- NumScheds = erlang:system_info(schedulers),
- (catch erlang:load_nif(filename:join([LibDir, ?MODULE]), NumScheds)),
- case erlang:system_info(otp_release) of
- "R13B03" -> true;
- _ -> ok
- end.
-
-
-less(A, B) ->
- try
- less_nif(A, B)
- catch
- error:badarg ->
- % Maybe the EJSON structure is too deep, fallback to Erlang land.
- less_erl(A, B)
- end.
-
-less_json_ids({JsonA, IdA}, {JsonB, IdB}) ->
- case less(JsonA, JsonB) of
- 0 ->
- IdA < IdB;
- Result ->
- Result < 0
- end.
-
-less_json(A,B) ->
- less(A, B) < 0.
-
-
-less_nif(A, B) ->
- less_erl(A, B).
-
-
-less_erl(A,A) -> 0;
-
-less_erl(A,B) when is_atom(A), is_atom(B) -> atom_sort(A) - atom_sort(B);
-less_erl(A,_) when is_atom(A) -> -1;
-less_erl(_,B) when is_atom(B) -> 1;
-
-less_erl(A,B) when is_number(A), is_number(B) -> A - B;
-less_erl(A,_) when is_number(A) -> -1;
-less_erl(_,B) when is_number(B) -> 1;
-
-less_erl(A,B) when is_binary(A), is_binary(B) -> couch_util:collate(A,B);
-less_erl(A,_) when is_binary(A) -> -1;
-less_erl(_,B) when is_binary(B) -> 1;
-
-less_erl(A,B) when is_list(A), is_list(B) -> less_list(A,B);
-less_erl(A,_) when is_list(A) -> -1;
-less_erl(_,B) when is_list(B) -> 1;
-
-less_erl({A},{B}) when is_list(A), is_list(B) -> less_props(A,B);
-less_erl({A},_) when is_list(A) -> -1;
-less_erl(_,{B}) when is_list(B) -> 1.
-
-atom_sort(null) -> 1;
-atom_sort(false) -> 2;
-atom_sort(true) -> 3.
-
-less_props([], [_|_]) ->
- -1;
-less_props(_, []) ->
- 1;
-less_props([{AKey, AValue}|RestA], [{BKey, BValue}|RestB]) ->
- case couch_util:collate(AKey, BKey) of
- 0 ->
- case less_erl(AValue, BValue) of
- 0 ->
- less_props(RestA, RestB);
- Result ->
- Result
- end;
- Result ->
- Result
- end.
-
-less_list([], [_|_]) ->
- -1;
-less_list(_, []) ->
- 1;
-less_list([A|RestA], [B|RestB]) ->
- case less_erl(A,B) of
- 0 ->
- less_list(RestA, RestB);
- Result ->
- Result
- end.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/couch/src/couch_util.erl
----------------------------------------------------------------------
diff --git a/src/couch/src/couch_util.erl b/src/couch/src/couch_util.erl
index d09211a..beb9622 100644
--- a/src/couch/src/couch_util.erl
+++ b/src/couch/src/couch_util.erl
@@ -21,6 +21,7 @@
-export([get_nested_json_value/2, json_user_ctx/1]).
-export([proplist_apply_field/2, json_apply_field/2]).
-export([to_binary/1, to_integer/1, to_list/1, url_encode/1]).
+-export([json_encode/1, json_decode/1]).
-export([verify/2,simple_call/2,shutdown_sync/1]).
-export([get_value/2, get_value/3]).
-export([md5/1, md5_init/0, md5_update/2, md5_final/1]).
@@ -376,6 +377,17 @@ url_encode([H|T]) ->
url_encode([]) ->
[].
+json_encode(V) ->
+ jiffy:encode(V, [force_utf8]).
+
+json_decode(V) ->
+ try
+ jiffy:decode(V)
+ catch
+ throw:Error ->
+ throw({invalid_json, Error})
+ end.
+
verify([X|RestX], [Y|RestY], Result) ->
verify(RestX, RestY, (X bxor Y) bor Result);
verify([], [], Result) ->
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/decode.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/decode.c b/src/ejson/c_src/decode.c
deleted file mode 100644
index 68f1317..0000000
--- a/src/ejson/c_src/decode.c
+++ /dev/null
@@ -1,308 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "erl_nif.h"
-#include "erl_nif_compat.h"
-#include "yajl/yajl_parse.h"
-#include "yajl/yajl_parser.h"
-#include "yajl/yajl_lex.h"
-
-typedef struct {
- ERL_NIF_TERM head;
- ErlNifEnv* env;
-} decode_ctx;
-
-#define ENV(ctxarg) (((decode_ctx*)ctxarg)->env)
-
-#define CONTINUE 1
-#define CANCEL 0
-
-
-static ERL_NIF_TERM
-make_error(yajl_handle handle, ErlNifEnv* env)
-{
- char* yajlError = (char*) yajl_get_error(handle, 0, NULL, 0);
- ERL_NIF_TERM errMsg;
-
- if(yajlError != NULL)
- {
- errMsg = enif_make_string(env, yajlError, ERL_NIF_LATIN1);
- yajl_free_error(handle, (unsigned char*) yajlError);
- }
- else
- {
- errMsg = enif_make_string(env, "unknown parse error", ERL_NIF_LATIN1);
- }
-
- return enif_make_tuple(env, 2,
- enif_make_atom(env, "error"),
- enif_make_tuple(env, 2,
- enif_make_uint(env, handle->bytesConsumed),
- errMsg
- )
- );
-}
-
-
-static void
-add_to_head(void* vctx, ERL_NIF_TERM newhead)
-{
- decode_ctx* ctx = (decode_ctx*)vctx;
- ctx->head = enif_make_list_cell(ctx->env, newhead, ctx->head);
-}
-
-static int
-decode_null(void* ctx)
-{
- add_to_head(ctx, enif_make_atom(ENV(ctx), "null"));
- return CONTINUE;
-}
-
-static int
-decode_boolean(void* ctx, int val)
-{
- add_to_head(ctx, enif_make_atom(ENV(ctx), val ? "true" : "false"));
- return CONTINUE;
-}
-
-static int
-decode_number(void * ctx, const char * numberVal, unsigned int numberLen)
-{
- // scan in the input to see if it's a float or int
-
- int numberType = 0; // 0 means integer, 1 means float
- unsigned int i;
- ErlNifBinary bin;
- int missingDot = 1;
- unsigned int expPos;
-
- for(i=0; i<numberLen; i++) {
- switch (numberVal[i]) {
- case '.':
- missingDot = 0;
- numberType = 1; // it's a float
- goto loopend;
- case 'E':
- case 'e':
- expPos = i;
- numberType = 1; // it's a float
- goto loopend;
- }
- }
-loopend:
- if ((numberType == 1) && missingDot)
- {
- if(!enif_alloc_binary_compat(ENV(ctx), numberLen + 2, &bin))
- {
- return CANCEL;
- }
- memcpy(bin.data, numberVal, expPos);
- bin.data[expPos] = '.';
- bin.data[expPos + 1] = '0';
- memcpy(bin.data + expPos + 2, numberVal + expPos, numberLen - expPos);
- }
- else
- {
- if(!enif_alloc_binary_compat(ENV(ctx), numberLen, &bin))
- {
- return CANCEL;
- }
- memcpy(bin.data, numberVal, numberLen);
- }
- add_to_head(ctx, enif_make_tuple(ENV(ctx), 2,
- enif_make_int(ENV(ctx), numberType),
- enif_make_binary(ENV(ctx), &bin)));
- return CONTINUE;
-}
-
-
-
-static int
-decode_string(void* ctx, const unsigned char* data, unsigned int size)
-{
- ErlNifBinary bin;
- if(!enif_alloc_binary_compat(ENV(ctx), size, &bin))
- {
- return CANCEL;
- }
- memcpy(bin.data, data, size);
- add_to_head(ctx, enif_make_binary(ENV(ctx), &bin));
- return CONTINUE;
-}
-
-static int
-decode_start_array(void* ctx)
-{
- add_to_head(ctx, enif_make_int(ENV(ctx), 0));
- return CONTINUE;
-}
-
-
-static int
-decode_end_array(void* ctx)
-{
- add_to_head(ctx, enif_make_int(ENV(ctx), 1));
- return CONTINUE;
-}
-
-
-static int
-decode_start_map(void* ctx)
-{
- add_to_head(ctx, enif_make_int(ENV(ctx), 2));
- return CONTINUE;
-}
-
-
-static int
-decode_end_map(void* ctx)
-{
- add_to_head(ctx, enif_make_int(ENV(ctx), 3));
- return CONTINUE;
-}
-
-
-static int
-decode_map_key(void* ctx, const unsigned char* data, unsigned int size)
-{
- ErlNifBinary bin;
- if(!enif_alloc_binary_compat(ENV(ctx), size, &bin))
- {
- return CANCEL;
- }
- memcpy(bin.data, data, size);
- add_to_head(ctx, enif_make_tuple(ENV(ctx), 2,
- enif_make_int(ENV(ctx), 3),
- enif_make_binary(ENV(ctx), &bin)));
- return CONTINUE;
-}
-
-static yajl_callbacks
-decoder_callbacks = {
- decode_null,
- decode_boolean,
- NULL,
- NULL,
- decode_number,
- decode_string,
- decode_start_map,
- decode_map_key,
- decode_end_map,
- decode_start_array,
- decode_end_array
-};
-
-static int
-check_rest(unsigned char* data, unsigned int size, unsigned int used)
-{
- unsigned int i = 0;
- for(i = used; i < size; i++)
- {
- switch(data[i])
- {
- case ' ':
- case '\t':
- case '\r':
- case '\n':
- continue;
- default:
- return CANCEL;
- }
- }
-
- return CONTINUE;
-}
-
-ERL_NIF_TERM
-reverse_tokens(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
-{
- decode_ctx ctx;
- yajl_parser_config conf = {0, 1}; // No comments, check utf8
- yajl_handle handle = yajl_alloc(&decoder_callbacks, &conf, NULL, &ctx);
- yajl_status status;
- unsigned int used;
- ErlNifBinary bin;
- ERL_NIF_TERM ret;
-
- ctx.env = env;
- ctx.head = enif_make_list_from_array(env, NULL, 0);
-
- if(!enif_inspect_iolist_as_binary(env, argv[0], &bin))
- {
- ret = enif_make_badarg(env);
- goto done;
- }
-
- status = yajl_parse(handle, bin.data, bin.size);
- used = handle->bytesConsumed;
-
- // Parsing something like "2.0" (without quotes) will
- // cause a spurious semi-error. We add the extra size
- // check so that "2008-20-10" doesn't pass.
- if(status == yajl_status_insufficient_data && used == bin.size)
- {
- status = yajl_parse_complete(handle);
- }
-
- if(status == yajl_status_ok && used != bin.size)
- {
- if(check_rest(bin.data, bin.size, used) == CANCEL)
- {
- ret = enif_make_tuple(env, 2,
- enif_make_atom(env, "error"),
- enif_make_atom(env, "garbage_after_value")
- );
- goto done;
- }
- }
-
- switch(status)
- {
- case yajl_status_ok:
- ret = enif_make_tuple(env, 2, enif_make_atom(env, "ok"), ctx.head);
- goto done;
-
- case yajl_status_error:
- ret = make_error(handle, env);
- goto done;
-
- case yajl_status_insufficient_data:
- ret = enif_make_tuple(env, 2,
- enif_make_atom(env, "error"),
- enif_make_atom(env, "insufficient_data")
- );
- goto done;
-
- case yajl_status_client_canceled:
- /* the only time we do this is when we can't allocate a binary. */
- ret = enif_make_tuple(env, 2,
- enif_make_atom(env, "error"),
- enif_make_atom(env, "insufficient_memory")
- );
- goto done;
-
- default:
- ret = enif_make_tuple(env, 2,
- enif_make_atom(env, "error"),
- enif_make_atom(env, "unknown")
- );
- goto done;
- }
-
-done:
- if(handle != NULL) yajl_free(handle);
- return ret;
-}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/ejson.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/ejson.c b/src/ejson/c_src/ejson.c
deleted file mode 100644
index 390f762..0000000
--- a/src/ejson/c_src/ejson.c
+++ /dev/null
@@ -1,30 +0,0 @@
-#include "erl_nif.h"
-
-ERL_NIF_TERM final_encode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
-ERL_NIF_TERM reverse_tokens(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
-
-int
-on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM info)
-{
- return 0;
-}
-
-int
-on_reload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM info)
-{
- return 0;
-}
-
-int
-on_upgrade(ErlNifEnv* env, void** priv_data, void** old_data, ERL_NIF_TERM info)
-{
- return 0;
-}
-
-static ErlNifFunc nif_funcs[] =
-{
- {"final_encode", 1, final_encode},
- {"reverse_tokens", 1, reverse_tokens}
-};
-
-ERL_NIF_INIT(ejson, nif_funcs, &on_load, &on_reload, &on_upgrade, NULL);
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/encode.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/encode.c b/src/ejson/c_src/encode.c
deleted file mode 100644
index 1dbd1df..0000000
--- a/src/ejson/c_src/encode.c
+++ /dev/null
@@ -1,200 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#include <stdio.h>
-#include <string.h>
-#include <math.h>
-
-#include "erl_nif.h"
-#include "erl_nif_compat.h"
-#include "yajl/yajl_encode.h"
-
-#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
-#include <float.h>
-#define isnan _isnan
-#define isinf !_finite
-#define snprintf _snprintf
-#endif
-
-#define SUCCESS 0
-#define NOMEM 1
-#define BADARG 2
-
-
-typedef struct {
- ErlNifEnv* env;
- ErlNifBinary bin;
- size_t fill_offset;
- int error;
-} encode_ctx;
-
-
-static int
-ensure_buffer(void* vctx, unsigned int len) {
- encode_ctx* ctx = (encode_ctx*)vctx;
- if ((ctx->bin.size - ctx->fill_offset) < len) {
- if(!enif_realloc_binary_compat(ctx->env, &(ctx->bin), (ctx->bin.size * 2) + len)) {
- return NOMEM;
- }
- }
- return SUCCESS;
-}
-
-static void
-fill_buffer(void* vctx, const char* str, unsigned int len)
-{
- encode_ctx* ctx = (encode_ctx*)vctx;
-
- if (ctx->error || (ctx->error = ensure_buffer(vctx, len))) {
- return;
- }
- memcpy(ctx->bin.data + ctx->fill_offset, str, len);
- ctx->fill_offset += len;
-}
-
-/* Json encode the string binary into the ctx.bin,
- with surrounding quotes and all */
-static int
-encode_string(void* vctx, ERL_NIF_TERM binary)
-{
- encode_ctx* ctx = (encode_ctx*)vctx;
- ErlNifBinary bin;
-
- if(!enif_inspect_binary(ctx->env, binary, &bin)) {
- return NOMEM;
- }
- fill_buffer(ctx, "\"", 1);
- if (ctx->error) {
- return ctx->error;
- }
- yajl_string_encode2(fill_buffer, ctx, bin.data, bin.size);
- fill_buffer(ctx, "\"", 1);
-
- return ctx->error;
-}
-
-static ERL_NIF_TERM
-no_mem_error(ErlNifEnv* env)
-{
- return enif_make_tuple(env, 2,
- enif_make_atom(env, "error"),
- enif_make_atom(env, "insufficient_memory"));
-}
-
-ERL_NIF_TERM
-final_encode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
-{
- ERL_NIF_TERM head = argv[0];
- ERL_NIF_TERM term;
- double number;
- encode_ctx ctx;
- char* start;
- size_t len;
- size_t i;
-
- ctx.env = env;
- ctx.fill_offset = 0;
- ctx.error = 0;
-
- if (!enif_alloc_binary_compat(env, 100, &ctx.bin)) {
- return no_mem_error(env);
- }
-
- while(enif_get_list_cell(env, head, &term, &head)) {
- ErlNifBinary termbin;
- const ERL_NIF_TERM* array;
- int arity;
- int code;
-
- // We scan the list, looking for things to write into the binary, or
- // encode and then write into the binary. We encode values that are
- // tuples tagged with a type and a value: {Type, Value} where Type
- // is a an Integer and Value is what is to be encoded
-
- if (enif_get_tuple(env, term, &arity, &array)) {
- // It's a tuple to encode and copy
- if (arity != 2 || !enif_get_int(env, array[0], &code)) {
- // not arity 2 or the first element isn't an int
- ctx.error = BADARG;
- goto done;
- }
- if (code == 0) {
- // {0, String}
- if (encode_string(&ctx, array[1]) != SUCCESS) {
- goto done;
- }
- }
- else {
- // {1, Double}
- if(!enif_get_double(env, array[1], &number)) {
- ctx.error = BADARG;
- goto done;
- }
- // We can't encode these.
- if (isnan(number) || isinf(number)) {
- ctx.error = BADARG;
- goto done;
- }
- if ((ctx.error = ensure_buffer(&ctx, 32)) != SUCCESS) {
- goto done;
- }
- // write the string into the buffer
- start = (char*) (ctx.bin.data + ctx.fill_offset);
- snprintf(start, 32, "%0.20g", number);
- len = strlen(start);
- for(i = 0; i < len; i++) {
- if(start[i] == '.' || start[i] == 'e' || start[i] == 'E') {
- break;
- }
- }
- if(i == len) {
- if(i > 29) {
- ctx.error = BADARG;
- goto done;
- }
- start[len++] = '.';
- start[len++] = '0';
- }
- // increment the length
- ctx.fill_offset += len;
- }
- } else if (enif_inspect_binary(env, term, &termbin)) {
- // this is a regular binary, copy the contents into the buffer
- fill_buffer(&ctx, (char*)termbin.data, termbin.size);
- if (ctx.error) {
- goto done;
- }
- }
- else {
- //not a binary, not a tuple, wtf!
- ctx.error = BADARG;
- goto done;
- }
- }
-done:
- if (ctx.error == NOMEM) {
- enif_release_binary_compat(env, &ctx.bin);
- return no_mem_error(env);
- } else if (ctx.error == BADARG) {
- enif_release_binary_compat(env, &ctx.bin);
- return enif_make_badarg(env);
- }
-
- // Resize the binary to our exact final size
- if(!enif_realloc_binary_compat(env, &(ctx.bin), ctx.fill_offset)) {
- enif_release_binary_compat(env, &ctx.bin);
- return no_mem_error(env);
- }
- // make the binary term which transfers ownership
- return enif_make_binary(env, &ctx.bin);
-}
-
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/erl_nif_compat.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/erl_nif_compat.h b/src/ejson/c_src/erl_nif_compat.h
deleted file mode 100644
index 548ea7a..0000000
--- a/src/ejson/c_src/erl_nif_compat.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/* Copyright (c) 2010-2011 Basho Technologies, Inc.
- * With some minor modifications for Apache CouchDB.
- *
- * This file is provided to you under the Apache License,
- * Version 2.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain
- * a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
-*/
-
-#ifndef ERL_NIF_COMPAT_H_
-#define ERL_NIF_COMPAT_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#include "erl_nif.h"
-
-
-#if ERL_NIF_MAJOR_VERSION == 0 && ERL_NIF_MINOR_VERSION == 1
-#define OTP_R13B03
-#elif ERL_NIF_MAJOR_VERSION == 1 && ERL_NIF_MINOR_VERSION == 0
-#define OTP_R13B04
-#elif ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION == 0
-#define OTP_R14A
-#define OTP_R14B
-#define OTP_R14B01
-#elif ERL_NIF_MAJOR_VERSION == 2 && ERL_NIF_MINOR_VERSION == 1
-#define OTP_R14B02
-#endif
-
-
-#ifdef OTP_R13B03
-
-#define enif_open_resource_type_compat enif_open_resource_type
-#define enif_alloc_resource_compat enif_alloc_resource
-#define enif_release_resource_compat enif_release_resource
-#define enif_alloc_binary_compat enif_alloc_binary
-#define enif_alloc_compat enif_alloc
-#define enif_release_binary_compat enif_release_binary
-#define enif_free_compat enif_free
-#define enif_get_atom_compat enif_get_atom
-#define enif_priv_data_compat enif_get_data
-#define enif_make_uint_compat enif_make_ulong
-
-#define enif_make_string_compat(E, B, Enc) \
- enif_make_string(E, B)
-
-#endif /* R13B03 */
-
-
-#ifdef OTP_R13B04
-
-#define enif_open_resource_type_compat enif_open_resource_type
-#define enif_alloc_resource_compat enif_alloc_resource
-#define enif_release_resource_compat enif_release_resource
-#define enif_alloc_binary_compat enif_alloc_binary
-#define enif_realloc_binary_compat enif_realloc_binary
-#define enif_release_binary_compat enif_release_binary
-#define enif_alloc_compat enif_alloc
-#define enif_free_compat enif_free
-#define enif_get_atom_compat enif_get_atom
-#define enif_priv_data_compat enif_priv_data
-#define enif_make_string_compat enif_make_string
-#define enif_make_uint_compat enif_make_uint
-
-#endif /* R13B04 */
-
-
-/* OTP R14 and future releases */
-#if !defined(OTP_R13B03) && !defined(OTP_R13B04)
-
-#define enif_open_resource_type_compat(E, N, D, F, T) \
- enif_open_resource_type(E, NULL, N, D, F, T)
-
-#define enif_alloc_resource_compat(E, T, S) \
- enif_alloc_resource(T, S)
-
-#define enif_release_resource_compat(E, H) \
- enif_release_resource(H)
-
-#define enif_alloc_binary_compat(E, S, B) \
- enif_alloc_binary(S, B)
-
-#define enif_realloc_binary_compat(E, S, B) \
- enif_realloc_binary(S, B)
-
-#define enif_release_binary_compat(E, B) \
- enif_release_binary(B)
-
-#define enif_alloc_compat(E, S) \
- enif_alloc(S)
-
-#define enif_free_compat(E, P) \
- enif_free(P)
-
-#define enif_get_atom_compat(E, T, B, S) \
- enif_get_atom(E, T, B, S, ERL_NIF_LATIN1)
-
-#define enif_priv_data_compat enif_priv_data
-#define enif_make_string_compat enif_make_string
-#define enif_make_uint_compat enif_make_uint
-
-#endif /* R14 and future releases */
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* ERL_NIF_COMPAT_H_ */
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl.c b/src/ejson/c_src/yajl/yajl.c
deleted file mode 100644
index 39d8b9f..0000000
--- a/src/ejson/c_src/yajl/yajl.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "yajl_parse.h"
-#include "yajl_lex.h"
-#include "yajl_parser.h"
-#include "yajl_alloc.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-
-const char *
-yajl_status_to_string(yajl_status stat)
-{
- const char * statStr = "unknown";
- switch (stat) {
- case yajl_status_ok:
- statStr = "ok, no error";
- break;
- case yajl_status_client_canceled:
- statStr = "client canceled parse";
- break;
- case yajl_status_insufficient_data:
- statStr = "eof was met before the parse could complete";
- break;
- case yajl_status_error:
- statStr = "parse error";
- break;
- }
- return statStr;
-}
-
-yajl_handle
-yajl_alloc(const yajl_callbacks * callbacks,
- const yajl_parser_config * config,
- const yajl_alloc_funcs * afs,
- void * ctx)
-{
- unsigned int allowComments = 0;
- unsigned int validateUTF8 = 0;
- yajl_handle hand = NULL;
- yajl_alloc_funcs afsBuffer;
-
- /* first order of business is to set up memory allocation routines */
- if (afs != NULL) {
- if (afs->malloc == NULL || afs->realloc == NULL || afs->free == NULL)
- {
- return NULL;
- }
- } else {
- yajl_set_default_alloc_funcs(&afsBuffer);
- afs = &afsBuffer;
- }
-
- hand = (yajl_handle) YA_MALLOC(afs, sizeof(struct yajl_handle_t));
-
- /* copy in pointers to allocation routines */
- memcpy((void *) &(hand->alloc), (void *) afs, sizeof(yajl_alloc_funcs));
-
- if (config != NULL) {
- allowComments = config->allowComments;
- validateUTF8 = config->checkUTF8;
- }
-
- hand->callbacks = callbacks;
- hand->ctx = ctx;
- hand->lexer = yajl_lex_alloc(&(hand->alloc), allowComments, validateUTF8);
- hand->bytesConsumed = 0;
- hand->decodeBuf = yajl_buf_alloc(&(hand->alloc));
- yajl_bs_init(hand->stateStack, &(hand->alloc));
-
- yajl_bs_push(hand->stateStack, yajl_state_start);
-
- return hand;
-}
-
-void
-yajl_free(yajl_handle handle)
-{
- yajl_bs_free(handle->stateStack);
- yajl_buf_free(handle->decodeBuf);
- yajl_lex_free(handle->lexer);
- YA_FREE(&(handle->alloc), handle);
-}
-
-yajl_status
-yajl_parse(yajl_handle hand, const unsigned char * jsonText,
- unsigned int jsonTextLen)
-{
- yajl_status status;
- status = yajl_do_parse(hand, jsonText, jsonTextLen);
- return status;
-}
-
-yajl_status
-yajl_parse_complete(yajl_handle hand)
-{
- /* The particular case we want to handle is a trailing number.
- * Further input consisting of digits could cause our interpretation
- * of the number to change (buffered "1" but "2" comes in).
- * A very simple approach to this is to inject whitespace to terminate
- * any number in the lex buffer.
- */
- return yajl_parse(hand, (const unsigned char *)" ", 1);
-}
-
-unsigned char *
-yajl_get_error(yajl_handle hand, int verbose,
- const unsigned char * jsonText, unsigned int jsonTextLen)
-{
- return yajl_render_error_string(hand, jsonText, jsonTextLen, verbose);
-}
-
-unsigned int
-yajl_get_bytes_consumed(yajl_handle hand)
-{
- if (!hand) return 0;
- else return hand->bytesConsumed;
-}
-
-
-void
-yajl_free_error(yajl_handle hand, unsigned char * str)
-{
- /* use memory allocation functions if set */
- YA_FREE(&(hand->alloc), str);
-}
-
-/* XXX: add utility routines to parse from file */
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_alloc.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_alloc.c b/src/ejson/c_src/yajl/yajl_alloc.c
deleted file mode 100644
index ccfb7c3..0000000
--- a/src/ejson/c_src/yajl/yajl_alloc.c
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-/**
- * \file yajl_alloc.h
- * default memory allocation routines for yajl which use malloc/realloc and
- * free
- */
-
-#include "yajl_alloc.h"
-#include <stdlib.h>
-
-static void * yajl_internal_malloc(void *ctx, unsigned int sz)
-{
- return malloc(sz);
-}
-
-static void * yajl_internal_realloc(void *ctx, void * previous,
- unsigned int sz)
-{
- return realloc(previous, sz);
-}
-
-static void yajl_internal_free(void *ctx, void * ptr)
-{
- free(ptr);
-}
-
-void yajl_set_default_alloc_funcs(yajl_alloc_funcs * yaf)
-{
- yaf->malloc = yajl_internal_malloc;
- yaf->free = yajl_internal_free;
- yaf->realloc = yajl_internal_realloc;
- yaf->ctx = NULL;
-}
-
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_alloc.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_alloc.h b/src/ejson/c_src/yajl/yajl_alloc.h
deleted file mode 100644
index cc1e5cf..0000000
--- a/src/ejson/c_src/yajl/yajl_alloc.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-/**
- * \file yajl_alloc.h
- * default memory allocation routines for yajl which use malloc/realloc and
- * free
- */
-
-#ifndef __YAJL_ALLOC_H__
-#define __YAJL_ALLOC_H__
-
-#include "yajl_common.h"
-
-#define YA_MALLOC(afs, sz) (afs)->malloc((afs)->ctx, (sz))
-#define YA_FREE(afs, ptr) (afs)->free((afs)->ctx, (ptr))
-#define YA_REALLOC(afs, ptr, sz) (afs)->realloc((afs)->ctx, (ptr), (sz))
-
-void yajl_set_default_alloc_funcs(yajl_alloc_funcs * yaf);
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_buf.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_buf.c b/src/ejson/c_src/yajl/yajl_buf.c
deleted file mode 100644
index 04e608a..0000000
--- a/src/ejson/c_src/yajl/yajl_buf.c
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "yajl_buf.h"
-
-#include <assert.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define YAJL_BUF_INIT_SIZE 2048
-
-struct yajl_buf_t {
- unsigned int len;
- unsigned int used;
- unsigned char * data;
- yajl_alloc_funcs * alloc;
-};
-
-static
-void yajl_buf_ensure_available(yajl_buf buf, unsigned int want)
-{
- unsigned int need;
-
- assert(buf != NULL);
-
- /* first call */
- if (buf->data == NULL) {
- buf->len = YAJL_BUF_INIT_SIZE;
- buf->data = (unsigned char *) YA_MALLOC(buf->alloc, buf->len);
- buf->data[0] = 0;
- }
-
- need = buf->len;
-
- while (want >= (need - buf->used)) need <<= 1;
-
- if (need != buf->len) {
- buf->data = (unsigned char *) YA_REALLOC(buf->alloc, buf->data, need);
- buf->len = need;
- }
-}
-
-yajl_buf yajl_buf_alloc(yajl_alloc_funcs * alloc)
-{
- yajl_buf b = YA_MALLOC(alloc, sizeof(struct yajl_buf_t));
- memset((void *) b, 0, sizeof(struct yajl_buf_t));
- b->alloc = alloc;
- return b;
-}
-
-void yajl_buf_free(yajl_buf buf)
-{
- assert(buf != NULL);
- if (buf->data) YA_FREE(buf->alloc, buf->data);
- YA_FREE(buf->alloc, buf);
-}
-
-void yajl_buf_append(yajl_buf buf, const void * data, unsigned int len)
-{
- yajl_buf_ensure_available(buf, len);
- if (len > 0) {
- assert(data != NULL);
- memcpy(buf->data + buf->used, data, len);
- buf->used += len;
- buf->data[buf->used] = 0;
- }
-}
-
-void yajl_buf_clear(yajl_buf buf)
-{
- buf->used = 0;
- if (buf->data) buf->data[buf->used] = 0;
-}
-
-const unsigned char * yajl_buf_data(yajl_buf buf)
-{
- return buf->data;
-}
-
-unsigned int yajl_buf_len(yajl_buf buf)
-{
- return buf->used;
-}
-
-void
-yajl_buf_truncate(yajl_buf buf, unsigned int len)
-{
- assert(len <= buf->used);
- buf->used = len;
-}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_buf.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_buf.h b/src/ejson/c_src/yajl/yajl_buf.h
deleted file mode 100644
index a6dcbe9..0000000
--- a/src/ejson/c_src/yajl/yajl_buf.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __YAJL_BUF_H__
-#define __YAJL_BUF_H__
-
-#include "yajl_common.h"
-#include "yajl_alloc.h"
-
-/*
- * Implementation/performance notes. If this were moved to a header
- * only implementation using #define's where possible we might be
- * able to sqeeze a little performance out of the guy by killing function
- * call overhead. YMMV.
- */
-
-/**
- * yajl_buf is a buffer with exponential growth. the buffer ensures that
- * you are always null padded.
- */
-typedef struct yajl_buf_t * yajl_buf;
-
-/* allocate a new buffer */
-yajl_buf yajl_buf_alloc(yajl_alloc_funcs * alloc);
-
-/* free the buffer */
-void yajl_buf_free(yajl_buf buf);
-
-/* append a number of bytes to the buffer */
-void yajl_buf_append(yajl_buf buf, const void * data, unsigned int len);
-
-/* empty the buffer */
-void yajl_buf_clear(yajl_buf buf);
-
-/* get a pointer to the beginning of the buffer */
-const unsigned char * yajl_buf_data(yajl_buf buf);
-
-/* get the length of the buffer */
-unsigned int yajl_buf_len(yajl_buf buf);
-
-/* truncate the buffer */
-void yajl_buf_truncate(yajl_buf buf, unsigned int len);
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_bytestack.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_bytestack.h b/src/ejson/c_src/yajl/yajl_bytestack.h
deleted file mode 100644
index 3b49d17..0000000
--- a/src/ejson/c_src/yajl/yajl_bytestack.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * A header only implementation of a simple stack of bytes, used in YAJL
- * to maintain parse state.
- */
-
-#ifndef __YAJL_BYTESTACK_H__
-#define __YAJL_BYTESTACK_H__
-
-#include "yajl_common.h"
-
-#define YAJL_BS_INC 128
-
-typedef struct yajl_bytestack_t
-{
- unsigned char * stack;
- unsigned int size;
- unsigned int used;
- yajl_alloc_funcs * yaf;
-} yajl_bytestack;
-
-/* initialize a bytestack */
-#define yajl_bs_init(obs, _yaf) { \
- (obs).stack = NULL; \
- (obs).size = 0; \
- (obs).used = 0; \
- (obs).yaf = (_yaf); \
- } \
-
-
-/* initialize a bytestack */
-#define yajl_bs_free(obs) \
- if ((obs).stack) (obs).yaf->free((obs).yaf->ctx, (obs).stack);
-
-#define yajl_bs_current(obs) \
- (assert((obs).used > 0), (obs).stack[(obs).used - 1])
-
-#define yajl_bs_push(obs, byte) { \
- if (((obs).size - (obs).used) == 0) { \
- (obs).size += YAJL_BS_INC; \
- (obs).stack = (obs).yaf->realloc((obs).yaf->ctx,\
- (void *) (obs).stack, (obs).size);\
- } \
- (obs).stack[((obs).used)++] = (byte); \
-}
-
-/* removes the top item of the stack, returns nothing */
-#define yajl_bs_pop(obs) { ((obs).used)--; }
-
-#define yajl_bs_set(obs, byte) \
- (obs).stack[((obs).used) - 1] = (byte);
-
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_common.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_common.h b/src/ejson/c_src/yajl/yajl_common.h
deleted file mode 100644
index a227deb..0000000
--- a/src/ejson/c_src/yajl/yajl_common.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __YAJL_COMMON_H__
-#define __YAJL_COMMON_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define YAJL_MAX_DEPTH 128
-
-/* msft dll export gunk. To build a DLL on windows, you
- * must define WIN32, YAJL_SHARED, and YAJL_BUILD. To use a shared
- * DLL, you must define YAJL_SHARED and WIN32 */
-#if defined(WIN32) && defined(YAJL_SHARED)
-# ifdef YAJL_BUILD
-# define YAJL_API __declspec(dllexport)
-# else
-# define YAJL_API __declspec(dllimport)
-# endif
-#else
-# define YAJL_API
-#endif
-
-/** pointer to a malloc function, supporting client overriding memory
- * allocation routines */
-typedef void * (*yajl_malloc_func)(void *ctx, unsigned int sz);
-
-/** pointer to a free function, supporting client overriding memory
- * allocation routines */
-typedef void (*yajl_free_func)(void *ctx, void * ptr);
-
-/** pointer to a realloc function which can resize an allocation. */
-typedef void * (*yajl_realloc_func)(void *ctx, void * ptr, unsigned int sz);
-
-/** A structure which can be passed to yajl_*_alloc routines to allow the
- * client to specify memory allocation functions to be used. */
-typedef struct
-{
- /** pointer to a function that can allocate uninitialized memory */
- yajl_malloc_func malloc;
- /** pointer to a function that can resize memory allocations */
- yajl_realloc_func realloc;
- /** pointer to a function that can free memory allocated using
- * reallocFunction or mallocFunction */
- yajl_free_func free;
- /** a context pointer that will be passed to above allocation routines */
- void * ctx;
-} yajl_alloc_funcs;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_encode.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_encode.c b/src/ejson/c_src/yajl/yajl_encode.c
deleted file mode 100644
index ad5b1c5..0000000
--- a/src/ejson/c_src/yajl/yajl_encode.c
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "yajl_encode.h"
-
-#include <assert.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-
-static void CharToHex(unsigned char c, char * hexBuf)
-{
- const char * hexchar = "0123456789ABCDEF";
- hexBuf[0] = hexchar[c >> 4];
- hexBuf[1] = hexchar[c & 0x0F];
-}
-
-void
-yajl_string_encode(yajl_buf buf, const unsigned char * str,
- unsigned int len)
-{
- yajl_string_encode2((const yajl_print_t) &yajl_buf_append, buf, str, len);
-}
-
-void
-yajl_string_encode2(const yajl_print_t print,
- void * ctx,
- const unsigned char * str,
- unsigned int len)
-{
- unsigned int beg = 0;
- unsigned int end = 0;
- char hexBuf[7];
- hexBuf[0] = '\\'; hexBuf[1] = 'u'; hexBuf[2] = '0'; hexBuf[3] = '0';
- hexBuf[6] = 0;
-
- while (end < len) {
- const char * escaped = NULL;
- switch (str[end]) {
- case '\r': escaped = "\\r"; break;
- case '\n': escaped = "\\n"; break;
- case '\\': escaped = "\\\\"; break;
- /* case '/': escaped = "\\/"; break; */
- case '"': escaped = "\\\""; break;
- case '\f': escaped = "\\f"; break;
- case '\b': escaped = "\\b"; break;
- case '\t': escaped = "\\t"; break;
- default:
- if ((unsigned char) str[end] < 32) {
- CharToHex(str[end], hexBuf + 4);
- escaped = hexBuf;
- }
- break;
- }
- if (escaped != NULL) {
- print(ctx, (const char *) (str + beg), end - beg);
- print(ctx, escaped, strlen(escaped));
- beg = ++end;
- } else {
- ++end;
- }
- }
- print(ctx, (const char *) (str + beg), end - beg);
-}
-
-static void hexToDigit(unsigned int * val, const unsigned char * hex)
-{
- unsigned int i;
- for (i=0;i<4;i++) {
- unsigned char c = hex[i];
- if (c >= 'A') c = (c & ~0x20) - 7;
- c -= '0';
- assert(!(c & 0xF0));
- *val = (*val << 4) | c;
- }
-}
-
-static void Utf32toUtf8(unsigned int codepoint, char * utf8Buf)
-{
- if (codepoint < 0x80) {
- utf8Buf[0] = (char) codepoint;
- utf8Buf[1] = 0;
- } else if (codepoint < 0x0800) {
- utf8Buf[0] = (char) ((codepoint >> 6) | 0xC0);
- utf8Buf[1] = (char) ((codepoint & 0x3F) | 0x80);
- utf8Buf[2] = 0;
- } else if (codepoint < 0x10000) {
- utf8Buf[0] = (char) ((codepoint >> 12) | 0xE0);
- utf8Buf[1] = (char) (((codepoint >> 6) & 0x3F) | 0x80);
- utf8Buf[2] = (char) ((codepoint & 0x3F) | 0x80);
- utf8Buf[3] = 0;
- } else if (codepoint < 0x200000) {
- utf8Buf[0] =(char)((codepoint >> 18) | 0xF0);
- utf8Buf[1] =(char)(((codepoint >> 12) & 0x3F) | 0x80);
- utf8Buf[2] =(char)(((codepoint >> 6) & 0x3F) | 0x80);
- utf8Buf[3] =(char)((codepoint & 0x3F) | 0x80);
- utf8Buf[4] = 0;
- } else {
- utf8Buf[0] = '?';
- utf8Buf[1] = 0;
- }
-}
-
-void yajl_string_decode(yajl_buf buf, const unsigned char * str,
- unsigned int len)
-{
- unsigned int beg = 0;
- unsigned int end = 0;
-
- while (end < len) {
- if (str[end] == '\\') {
- char utf8Buf[5];
- const char * unescaped = "?";
- yajl_buf_append(buf, str + beg, end - beg);
- switch (str[++end]) {
- case 'r': unescaped = "\r"; break;
- case 'n': unescaped = "\n"; break;
- case '\\': unescaped = "\\"; break;
- case '/': unescaped = "/"; break;
- case '"': unescaped = "\""; break;
- case 'f': unescaped = "\f"; break;
- case 'b': unescaped = "\b"; break;
- case 't': unescaped = "\t"; break;
- case 'u': {
- unsigned int codepoint = 0;
- hexToDigit(&codepoint, str + ++end);
- end+=3;
- /* check if this is a surrogate */
- if ((codepoint & 0xFC00) == 0xD800) {
- end++;
- if (str[end] == '\\' && str[end + 1] == 'u') {
- unsigned int surrogate = 0;
- hexToDigit(&surrogate, str + end + 2);
- codepoint =
- (((codepoint & 0x3F) << 10) |
- ((((codepoint >> 6) & 0xF) + 1) << 16) |
- (surrogate & 0x3FF));
- end += 5;
- } else {
- unescaped = "?";
- break;
- }
- }
-
- Utf32toUtf8(codepoint, utf8Buf);
- unescaped = utf8Buf;
- break;
- }
- default:
- assert("this should never happen" == NULL);
- }
- yajl_buf_append(buf, unescaped, strlen(unescaped));
- beg = ++end;
- } else {
- end++;
- }
- }
- yajl_buf_append(buf, str + beg, end - beg);
-}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_encode.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_encode.h b/src/ejson/c_src/yajl/yajl_encode.h
deleted file mode 100644
index 3e3b092..0000000
--- a/src/ejson/c_src/yajl/yajl_encode.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __YAJL_ENCODE_H__
-#define __YAJL_ENCODE_H__
-
-#include "yajl_buf.h"
-#include "yajl_gen.h"
-
-void yajl_string_encode2(const yajl_print_t printer,
- void * ctx,
- const unsigned char * str,
- unsigned int length);
-
-void yajl_string_encode(yajl_buf buf, const unsigned char * str,
- unsigned int length);
-
-void yajl_string_decode(yajl_buf buf, const unsigned char * str,
- unsigned int length);
-
-#endif
[08/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/double-conversion.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/double-conversion.cc b/src/jiffy/c_src/double-conversion/double-conversion.cc
new file mode 100644
index 0000000..a79fe92
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/double-conversion.cc
@@ -0,0 +1,889 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <limits.h>
+#include <math.h>
+
+#include "double-conversion.h"
+
+#include "bignum-dtoa.h"
+#include "fast-dtoa.h"
+#include "fixed-dtoa.h"
+#include "ieee.h"
+#include "strtod.h"
+#include "utils.h"
+
+namespace double_conversion {
+
+const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
+ int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
+ static DoubleToStringConverter converter(flags,
+ "Infinity",
+ "NaN",
+ 'e',
+ -6, 21,
+ 6, 0);
+ return converter;
+}
+
+
+bool DoubleToStringConverter::HandleSpecialValues(
+ double value,
+ StringBuilder* result_builder) const {
+ Double double_inspect(value);
+ if (double_inspect.IsInfinite()) {
+ if (infinity_symbol_ == NULL) return false;
+ if (value < 0) {
+ result_builder->AddCharacter('-');
+ }
+ result_builder->AddString(infinity_symbol_);
+ return true;
+ }
+ if (double_inspect.IsNan()) {
+ if (nan_symbol_ == NULL) return false;
+ result_builder->AddString(nan_symbol_);
+ return true;
+ }
+ return false;
+}
+
+
+void DoubleToStringConverter::CreateExponentialRepresentation(
+ const char* decimal_digits,
+ int length,
+ int exponent,
+ StringBuilder* result_builder) const {
+ ASSERT(length != 0);
+ result_builder->AddCharacter(decimal_digits[0]);
+ if (length != 1) {
+ result_builder->AddCharacter('.');
+ result_builder->AddSubstring(&decimal_digits[1], length-1);
+ }
+ result_builder->AddCharacter(exponent_character_);
+ if (exponent < 0) {
+ result_builder->AddCharacter('-');
+ exponent = -exponent;
+ } else {
+ if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
+ result_builder->AddCharacter('+');
+ }
+ }
+ if (exponent == 0) {
+ result_builder->AddCharacter('0');
+ return;
+ }
+ ASSERT(exponent < 1e4);
+ const int kMaxExponentLength = 5;
+ char buffer[kMaxExponentLength + 1];
+ buffer[kMaxExponentLength] = '\0';
+ int first_char_pos = kMaxExponentLength;
+ while (exponent > 0) {
+ buffer[--first_char_pos] = '0' + (exponent % 10);
+ exponent /= 10;
+ }
+ result_builder->AddSubstring(&buffer[first_char_pos],
+ kMaxExponentLength - first_char_pos);
+}
+
+
+void DoubleToStringConverter::CreateDecimalRepresentation(
+ const char* decimal_digits,
+ int length,
+ int decimal_point,
+ int digits_after_point,
+ StringBuilder* result_builder) const {
+ // Create a representation that is padded with zeros if needed.
+ if (decimal_point <= 0) {
+ // "0.00000decimal_rep".
+ result_builder->AddCharacter('0');
+ if (digits_after_point > 0) {
+ result_builder->AddCharacter('.');
+ result_builder->AddPadding('0', -decimal_point);
+ ASSERT(length <= digits_after_point - (-decimal_point));
+ result_builder->AddSubstring(decimal_digits, length);
+ int remaining_digits = digits_after_point - (-decimal_point) - length;
+ result_builder->AddPadding('0', remaining_digits);
+ }
+ } else if (decimal_point >= length) {
+ // "decimal_rep0000.00000" or "decimal_rep.0000"
+ result_builder->AddSubstring(decimal_digits, length);
+ result_builder->AddPadding('0', decimal_point - length);
+ if (digits_after_point > 0) {
+ result_builder->AddCharacter('.');
+ result_builder->AddPadding('0', digits_after_point);
+ }
+ } else {
+ // "decima.l_rep000"
+ ASSERT(digits_after_point > 0);
+ result_builder->AddSubstring(decimal_digits, decimal_point);
+ result_builder->AddCharacter('.');
+ ASSERT(length - decimal_point <= digits_after_point);
+ result_builder->AddSubstring(&decimal_digits[decimal_point],
+ length - decimal_point);
+ int remaining_digits = digits_after_point - (length - decimal_point);
+ result_builder->AddPadding('0', remaining_digits);
+ }
+ if (digits_after_point == 0) {
+ if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
+ result_builder->AddCharacter('.');
+ }
+ if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
+ result_builder->AddCharacter('0');
+ }
+ }
+}
+
+
+bool DoubleToStringConverter::ToShortestIeeeNumber(
+ double value,
+ StringBuilder* result_builder,
+ DoubleToStringConverter::DtoaMode mode) const {
+ ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ int decimal_point;
+ bool sign;
+ const int kDecimalRepCapacity = kBase10MaximalLength + 1;
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+
+ DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+
+ bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ int exponent = decimal_point - 1;
+ if ((decimal_in_shortest_low_ <= exponent) &&
+ (exponent < decimal_in_shortest_high_)) {
+ CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
+ decimal_point,
+ Max(0, decimal_rep_length - decimal_point),
+ result_builder);
+ } else {
+ CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
+ result_builder);
+ }
+ return true;
+}
+
+
+bool DoubleToStringConverter::ToFixed(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const {
+ ASSERT(kMaxFixedDigitsBeforePoint == 60);
+ const double kFirstNonFixed = 1e60;
+
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
+ if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
+
+ // Find a sufficiently precise decimal representation of n.
+ int decimal_point;
+ bool sign;
+ // Add space for the '\0' byte.
+ const int kDecimalRepCapacity =
+ kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+ DoubleToAscii(value, FIXED, requested_digits,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+
+ bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
+ requested_digits, result_builder);
+ return true;
+}
+
+
+bool DoubleToStringConverter::ToExponential(
+ double value,
+ int requested_digits,
+ StringBuilder* result_builder) const {
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ if (requested_digits < -1) return false;
+ if (requested_digits > kMaxExponentialDigits) return false;
+
+ int decimal_point;
+ bool sign;
+ // Add space for digit before the decimal point and the '\0' character.
+ const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
+ ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+
+ if (requested_digits == -1) {
+ DoubleToAscii(value, SHORTEST, 0,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+ } else {
+ DoubleToAscii(value, PRECISION, requested_digits + 1,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+ ASSERT(decimal_rep_length <= requested_digits + 1);
+
+ for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
+ decimal_rep[i] = '0';
+ }
+ decimal_rep_length = requested_digits + 1;
+ }
+
+ bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ int exponent = decimal_point - 1;
+ CreateExponentialRepresentation(decimal_rep,
+ decimal_rep_length,
+ exponent,
+ result_builder);
+ return true;
+}
+
+
+bool DoubleToStringConverter::ToPrecision(double value,
+ int precision,
+ StringBuilder* result_builder) const {
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
+ return false;
+ }
+
+ // Find a sufficiently precise decimal representation of n.
+ int decimal_point;
+ bool sign;
+ // Add one for the terminating null character.
+ const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+
+ DoubleToAscii(value, PRECISION, precision,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+ ASSERT(decimal_rep_length <= precision);
+
+ bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ // The exponent if we print the number as x.xxeyyy. That is with the
+ // decimal point after the first digit.
+ int exponent = decimal_point - 1;
+
+ int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
+ if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
+ (decimal_point - precision + extra_zero >
+ max_trailing_padding_zeroes_in_precision_mode_)) {
+ // Fill buffer to contain 'precision' digits.
+ // Usually the buffer is already at the correct length, but 'DoubleToAscii'
+ // is allowed to return less characters.
+ for (int i = decimal_rep_length; i < precision; ++i) {
+ decimal_rep[i] = '0';
+ }
+
+ CreateExponentialRepresentation(decimal_rep,
+ precision,
+ exponent,
+ result_builder);
+ } else {
+ CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
+ Max(0, precision - decimal_point),
+ result_builder);
+ }
+ return true;
+}
+
+
+static BignumDtoaMode DtoaToBignumDtoaMode(
+ DoubleToStringConverter::DtoaMode dtoa_mode) {
+ switch (dtoa_mode) {
+ case DoubleToStringConverter::SHORTEST: return BIGNUM_DTOA_SHORTEST;
+ case DoubleToStringConverter::SHORTEST_SINGLE:
+ return BIGNUM_DTOA_SHORTEST_SINGLE;
+ case DoubleToStringConverter::FIXED: return BIGNUM_DTOA_FIXED;
+ case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
+ default:
+ UNREACHABLE();
+ return BIGNUM_DTOA_SHORTEST; // To silence compiler.
+ }
+}
+
+
+void DoubleToStringConverter::DoubleToAscii(double v,
+ DtoaMode mode,
+ int requested_digits,
+ char* buffer,
+ int buffer_length,
+ bool* sign,
+ int* length,
+ int* point) {
+ Vector<char> vector(buffer, buffer_length);
+ ASSERT(!Double(v).IsSpecial());
+ ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
+
+ if (Double(v).Sign() < 0) {
+ *sign = true;
+ v = -v;
+ } else {
+ *sign = false;
+ }
+
+ if (mode == PRECISION && requested_digits == 0) {
+ vector[0] = '\0';
+ *length = 0;
+ return;
+ }
+
+ if (v == 0) {
+ vector[0] = '0';
+ vector[1] = '\0';
+ *length = 1;
+ *point = 1;
+ return;
+ }
+
+ bool fast_worked;
+ switch (mode) {
+ case SHORTEST:
+ fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
+ break;
+ case SHORTEST_SINGLE:
+ fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
+ vector, length, point);
+ break;
+ case FIXED:
+ fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
+ break;
+ case PRECISION:
+ fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
+ vector, length, point);
+ break;
+ default:
+ UNREACHABLE();
+ fast_worked = false;
+ }
+ if (fast_worked) return;
+
+ // If the fast dtoa didn't succeed use the slower bignum version.
+ BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
+ BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
+ vector[*length] = '\0';
+}
+
+
+// Consumes the given substring from the iterator.
+// Returns false, if the substring does not match.
+static bool ConsumeSubString(const char** current,
+ const char* end,
+ const char* substring) {
+ ASSERT(**current == *substring);
+ for (substring++; *substring != '\0'; substring++) {
+ ++*current;
+ if (*current == end || **current != *substring) return false;
+ }
+ ++*current;
+ return true;
+}
+
+
+// Maximum number of significant digits in decimal representation.
+// The longest possible double in decimal representation is
+// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
+// (768 digits). If we parse a number whose first digits are equal to a
+// mean of 2 adjacent doubles (that could have up to 769 digits) the result
+// must be rounded to the bigger one unless the tail consists of zeros, so
+// we don't need to preserve all the digits.
+const int kMaxSignificantDigits = 772;
+
+
+// Returns true if a nonspace found and false if the end has reached.
+static inline bool AdvanceToNonspace(const char** current, const char* end) {
+ while (*current != end) {
+ if (**current != ' ') return true;
+ ++*current;
+ }
+ return false;
+}
+
+
+static bool isDigit(int x, int radix) {
+ return (x >= '0' && x <= '9' && x < '0' + radix)
+ || (radix > 10 && x >= 'a' && x < 'a' + radix - 10)
+ || (radix > 10 && x >= 'A' && x < 'A' + radix - 10);
+}
+
+
+static double SignedZero(bool sign) {
+ return sign ? -0.0 : 0.0;
+}
+
+
+// Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
+template <int radix_log_2>
+static double RadixStringToIeee(const char* current,
+ const char* end,
+ bool sign,
+ bool allow_trailing_junk,
+ double junk_string_value,
+ bool read_as_double,
+ const char** trailing_pointer) {
+ ASSERT(current != end);
+
+ const int kDoubleSize = Double::kSignificandSize;
+ const int kSingleSize = Single::kSignificandSize;
+ const int kSignificandSize = read_as_double? kDoubleSize: kSingleSize;
+
+ // Skip leading 0s.
+ while (*current == '0') {
+ ++current;
+ if (current == end) {
+ *trailing_pointer = end;
+ return SignedZero(sign);
+ }
+ }
+
+ int64_t number = 0;
+ int exponent = 0;
+ const int radix = (1 << radix_log_2);
+
+ do {
+ int digit;
+ if (*current >= '0' && *current <= '9' && *current < '0' + radix) {
+ digit = static_cast<char>(*current) - '0';
+ } else if (radix > 10 && *current >= 'a' && *current < 'a' + radix - 10) {
+ digit = static_cast<char>(*current) - 'a' + 10;
+ } else if (radix > 10 && *current >= 'A' && *current < 'A' + radix - 10) {
+ digit = static_cast<char>(*current) - 'A' + 10;
+ } else {
+ if (allow_trailing_junk || !AdvanceToNonspace(¤t, end)) {
+ break;
+ } else {
+ return junk_string_value;
+ }
+ }
+
+ number = number * radix + digit;
+ int overflow = static_cast<int>(number >> kSignificandSize);
+ if (overflow != 0) {
+ // Overflow occurred. Need to determine which direction to round the
+ // result.
+ int overflow_bits_count = 1;
+ while (overflow > 1) {
+ overflow_bits_count++;
+ overflow >>= 1;
+ }
+
+ int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
+ int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
+ number >>= overflow_bits_count;
+ exponent = overflow_bits_count;
+
+ bool zero_tail = true;
+ while (true) {
+ ++current;
+ if (current == end || !isDigit(*current, radix)) break;
+ zero_tail = zero_tail && *current == '0';
+ exponent += radix_log_2;
+ }
+
+ if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
+ return junk_string_value;
+ }
+
+ int middle_value = (1 << (overflow_bits_count - 1));
+ if (dropped_bits > middle_value) {
+ number++; // Rounding up.
+ } else if (dropped_bits == middle_value) {
+ // Rounding to even to consistency with decimals: half-way case rounds
+ // up if significant part is odd and down otherwise.
+ if ((number & 1) != 0 || !zero_tail) {
+ number++; // Rounding up.
+ }
+ }
+
+ // Rounding up may cause overflow.
+ if ((number & ((int64_t)1 << kSignificandSize)) != 0) {
+ exponent++;
+ number >>= 1;
+ }
+ break;
+ }
+ ++current;
+ } while (current != end);
+
+ ASSERT(number < ((int64_t)1 << kSignificandSize));
+ ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number);
+
+ *trailing_pointer = current;
+
+ if (exponent == 0) {
+ if (sign) {
+ if (number == 0) return -0.0;
+ number = -number;
+ }
+ return static_cast<double>(number);
+ }
+
+ ASSERT(number != 0);
+ return Double(DiyFp(number, exponent)).value();
+}
+
+
+double StringToDoubleConverter::StringToIeee(
+ const char* input,
+ int length,
+ int* processed_characters_count,
+ bool read_as_double) {
+ const char* current = input;
+ const char* end = input + length;
+
+ *processed_characters_count = 0;
+
+ const bool allow_trailing_junk = (flags_ & ALLOW_TRAILING_JUNK) != 0;
+ const bool allow_leading_spaces = (flags_ & ALLOW_LEADING_SPACES) != 0;
+ const bool allow_trailing_spaces = (flags_ & ALLOW_TRAILING_SPACES) != 0;
+ const bool allow_spaces_after_sign = (flags_ & ALLOW_SPACES_AFTER_SIGN) != 0;
+
+ // To make sure that iterator dereferencing is valid the following
+ // convention is used:
+ // 1. Each '++current' statement is followed by check for equality to 'end'.
+ // 2. If AdvanceToNonspace returned false then current == end.
+ // 3. If 'current' becomes equal to 'end' the function returns or goes to
+ // 'parsing_done'.
+ // 4. 'current' is not dereferenced after the 'parsing_done' label.
+ // 5. Code before 'parsing_done' may rely on 'current != end'.
+ if (current == end) return empty_string_value_;
+
+ if (allow_leading_spaces || allow_trailing_spaces) {
+ if (!AdvanceToNonspace(¤t, end)) {
+ *processed_characters_count = current - input;
+ return empty_string_value_;
+ }
+ if (!allow_leading_spaces && (input != current)) {
+ // No leading spaces allowed, but AdvanceToNonspace moved forward.
+ return junk_string_value_;
+ }
+ }
+
+ // The longest form of simplified number is: "-<significant digits>.1eXXX\0".
+ const int kBufferSize = kMaxSignificantDigits + 10;
+ char buffer[kBufferSize]; // NOLINT: size is known at compile time.
+ int buffer_pos = 0;
+
+ // Exponent will be adjusted if insignificant digits of the integer part
+ // or insignificant leading zeros of the fractional part are dropped.
+ int exponent = 0;
+ int significant_digits = 0;
+ int insignificant_digits = 0;
+ bool nonzero_digit_dropped = false;
+
+ bool sign = false;
+
+ if (*current == '+' || *current == '-') {
+ sign = (*current == '-');
+ ++current;
+ const char* next_non_space = current;
+ // Skip following spaces (if allowed).
+ if (!AdvanceToNonspace(&next_non_space, end)) return junk_string_value_;
+ if (!allow_spaces_after_sign && (current != next_non_space)) {
+ return junk_string_value_;
+ }
+ current = next_non_space;
+ }
+
+ if (infinity_symbol_ != NULL) {
+ if (*current == infinity_symbol_[0]) {
+ if (!ConsumeSubString(¤t, end, infinity_symbol_)) {
+ return junk_string_value_;
+ }
+
+ if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
+ return junk_string_value_;
+ }
+ if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
+ return junk_string_value_;
+ }
+
+ ASSERT(buffer_pos == 0);
+ *processed_characters_count = current - input;
+ return sign ? -Double::Infinity() : Double::Infinity();
+ }
+ }
+
+ if (nan_symbol_ != NULL) {
+ if (*current == nan_symbol_[0]) {
+ if (!ConsumeSubString(¤t, end, nan_symbol_)) {
+ return junk_string_value_;
+ }
+
+ if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
+ return junk_string_value_;
+ }
+ if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
+ return junk_string_value_;
+ }
+
+ ASSERT(buffer_pos == 0);
+ *processed_characters_count = current - input;
+ return sign ? -Double::NaN() : Double::NaN();
+ }
+ }
+
+ bool leading_zero = false;
+ if (*current == '0') {
+ ++current;
+ if (current == end) {
+ *processed_characters_count = current - input;
+ return SignedZero(sign);
+ }
+
+ leading_zero = true;
+
+ // It could be hexadecimal value.
+ if ((flags_ & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
+ ++current;
+ if (current == end || !isDigit(*current, 16)) {
+ return junk_string_value_; // "0x".
+ }
+
+ const char* tail_pointer = NULL;
+ double result = RadixStringToIeee<4>(current,
+ end,
+ sign,
+ allow_trailing_junk,
+ junk_string_value_,
+ read_as_double,
+ &tail_pointer);
+ if (tail_pointer != NULL) {
+ if (allow_trailing_spaces) AdvanceToNonspace(&tail_pointer, end);
+ *processed_characters_count = tail_pointer - input;
+ }
+ return result;
+ }
+
+ // Ignore leading zeros in the integer part.
+ while (*current == '0') {
+ ++current;
+ if (current == end) {
+ *processed_characters_count = current - input;
+ return SignedZero(sign);
+ }
+ }
+ }
+
+ bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
+
+ // Copy significant digits of the integer part (if any) to the buffer.
+ while (*current >= '0' && *current <= '9') {
+ if (significant_digits < kMaxSignificantDigits) {
+ ASSERT(buffer_pos < kBufferSize);
+ buffer[buffer_pos++] = static_cast<char>(*current);
+ significant_digits++;
+ // Will later check if it's an octal in the buffer.
+ } else {
+ insignificant_digits++; // Move the digit into the exponential part.
+ nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
+ }
+ octal = octal && *current < '8';
+ ++current;
+ if (current == end) goto parsing_done;
+ }
+
+ if (significant_digits == 0) {
+ octal = false;
+ }
+
+ if (*current == '.') {
+ if (octal && !allow_trailing_junk) return junk_string_value_;
+ if (octal) goto parsing_done;
+
+ ++current;
+ if (current == end) {
+ if (significant_digits == 0 && !leading_zero) {
+ return junk_string_value_;
+ } else {
+ goto parsing_done;
+ }
+ }
+
+ if (significant_digits == 0) {
+ // octal = false;
+ // Integer part consists of 0 or is absent. Significant digits start after
+ // leading zeros (if any).
+ while (*current == '0') {
+ ++current;
+ if (current == end) {
+ *processed_characters_count = current - input;
+ return SignedZero(sign);
+ }
+ exponent--; // Move this 0 into the exponent.
+ }
+ }
+
+ // There is a fractional part.
+ // We don't emit a '.', but adjust the exponent instead.
+ while (*current >= '0' && *current <= '9') {
+ if (significant_digits < kMaxSignificantDigits) {
+ ASSERT(buffer_pos < kBufferSize);
+ buffer[buffer_pos++] = static_cast<char>(*current);
+ significant_digits++;
+ exponent--;
+ } else {
+ // Ignore insignificant digits in the fractional part.
+ nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
+ }
+ ++current;
+ if (current == end) goto parsing_done;
+ }
+ }
+
+ if (!leading_zero && exponent == 0 && significant_digits == 0) {
+ // If leading_zeros is true then the string contains zeros.
+ // If exponent < 0 then string was [+-]\.0*...
+ // If significant_digits != 0 the string is not equal to 0.
+ // Otherwise there are no digits in the string.
+ return junk_string_value_;
+ }
+
+ // Parse exponential part.
+ if (*current == 'e' || *current == 'E') {
+ if (octal && !allow_trailing_junk) return junk_string_value_;
+ if (octal) goto parsing_done;
+ ++current;
+ if (current == end) {
+ if (allow_trailing_junk) {
+ goto parsing_done;
+ } else {
+ return junk_string_value_;
+ }
+ }
+ char sign = '+';
+ if (*current == '+' || *current == '-') {
+ sign = static_cast<char>(*current);
+ ++current;
+ if (current == end) {
+ if (allow_trailing_junk) {
+ goto parsing_done;
+ } else {
+ return junk_string_value_;
+ }
+ }
+ }
+
+ if (current == end || *current < '0' || *current > '9') {
+ if (allow_trailing_junk) {
+ goto parsing_done;
+ } else {
+ return junk_string_value_;
+ }
+ }
+
+ const int max_exponent = INT_MAX / 2;
+ ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
+ int num = 0;
+ do {
+ // Check overflow.
+ int digit = *current - '0';
+ if (num >= max_exponent / 10
+ && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
+ num = max_exponent;
+ } else {
+ num = num * 10 + digit;
+ }
+ ++current;
+ } while (current != end && *current >= '0' && *current <= '9');
+
+ exponent += (sign == '-' ? -num : num);
+ }
+
+ if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
+ return junk_string_value_;
+ }
+ if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
+ return junk_string_value_;
+ }
+ if (allow_trailing_spaces) {
+ AdvanceToNonspace(¤t, end);
+ }
+
+ parsing_done:
+ exponent += insignificant_digits;
+
+ if (octal) {
+ double result;
+ const char* tail_pointer = NULL;
+ result = RadixStringToIeee<3>(buffer,
+ buffer + buffer_pos,
+ sign,
+ allow_trailing_junk,
+ junk_string_value_,
+ read_as_double,
+ &tail_pointer);
+ ASSERT(tail_pointer != NULL);
+ *processed_characters_count = current - input;
+ return result;
+ }
+
+ if (nonzero_digit_dropped) {
+ buffer[buffer_pos++] = '1';
+ exponent--;
+ }
+
+ ASSERT(buffer_pos < kBufferSize);
+ buffer[buffer_pos] = '\0';
+
+ double converted;
+ if (read_as_double) {
+ converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
+ } else {
+ converted = Strtof(Vector<const char>(buffer, buffer_pos), exponent);
+ }
+ *processed_characters_count = current - input;
+ return sign? -converted: converted;
+}
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/double-conversion.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/double-conversion.h b/src/jiffy/c_src/double-conversion/double-conversion.h
new file mode 100644
index 0000000..f98edae
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/double-conversion.h
@@ -0,0 +1,536 @@
+// Copyright 2012 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
+#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+class DoubleToStringConverter {
+ public:
+ // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
+ // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
+ // function returns false.
+ static const int kMaxFixedDigitsBeforePoint = 60;
+ static const int kMaxFixedDigitsAfterPoint = 60;
+
+ // When calling ToExponential with a requested_digits
+ // parameter > kMaxExponentialDigits then the function returns false.
+ static const int kMaxExponentialDigits = 120;
+
+ // When calling ToPrecision with a requested_digits
+ // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
+ // then the function returns false.
+ static const int kMinPrecisionDigits = 1;
+ static const int kMaxPrecisionDigits = 120;
+
+ enum Flags {
+ NO_FLAGS = 0,
+ EMIT_POSITIVE_EXPONENT_SIGN = 1,
+ EMIT_TRAILING_DECIMAL_POINT = 2,
+ EMIT_TRAILING_ZERO_AFTER_POINT = 4,
+ UNIQUE_ZERO = 8
+ };
+
+ // Flags should be a bit-or combination of the possible Flags-enum.
+ // - NO_FLAGS: no special flags.
+ // - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
+ // form, emits a '+' for positive exponents. Example: 1.2e+2.
+ // - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
+ // converted into decimal format then a trailing decimal point is appended.
+ // Example: 2345.0 is converted to "2345.".
+ // - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
+ // emits a trailing '0'-character. This flag requires the
+ // EXMIT_TRAILING_DECIMAL_POINT flag.
+ // Example: 2345.0 is converted to "2345.0".
+ // - UNIQUE_ZERO: "-0.0" is converted to "0.0".
+ //
+ // Infinity symbol and nan_symbol provide the string representation for these
+ // special values. If the string is NULL and the special value is encountered
+ // then the conversion functions return false.
+ //
+ // The exponent_character is used in exponential representations. It is
+ // usually 'e' or 'E'.
+ //
+ // When converting to the shortest representation the converter will
+ // represent input numbers in decimal format if they are in the interval
+ // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
+ // (lower boundary included, greater boundary excluded).
+ // Example: with decimal_in_shortest_low = -6 and
+ // decimal_in_shortest_high = 21:
+ // ToShortest(0.000001) -> "0.000001"
+ // ToShortest(0.0000001) -> "1e-7"
+ // ToShortest(111111111111111111111.0) -> "111111111111111110000"
+ // ToShortest(100000000000000000000.0) -> "100000000000000000000"
+ // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
+ //
+ // When converting to precision mode the converter may add
+ // max_leading_padding_zeroes before returning the number in exponential
+ // format.
+ // Example with max_leading_padding_zeroes_in_precision_mode = 6.
+ // ToPrecision(0.0000012345, 2) -> "0.0000012"
+ // ToPrecision(0.00000012345, 2) -> "1.2e-7"
+ // Similarily the converter may add up to
+ // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
+ // returning an exponential representation. A zero added by the
+ // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
+ // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
+ // ToPrecision(230.0, 2) -> "230"
+ // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
+ // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
+ DoubleToStringConverter(int flags,
+ const char* infinity_symbol,
+ const char* nan_symbol,
+ char exponent_character,
+ int decimal_in_shortest_low,
+ int decimal_in_shortest_high,
+ int max_leading_padding_zeroes_in_precision_mode,
+ int max_trailing_padding_zeroes_in_precision_mode)
+ : flags_(flags),
+ infinity_symbol_(infinity_symbol),
+ nan_symbol_(nan_symbol),
+ exponent_character_(exponent_character),
+ decimal_in_shortest_low_(decimal_in_shortest_low),
+ decimal_in_shortest_high_(decimal_in_shortest_high),
+ max_leading_padding_zeroes_in_precision_mode_(
+ max_leading_padding_zeroes_in_precision_mode),
+ max_trailing_padding_zeroes_in_precision_mode_(
+ max_trailing_padding_zeroes_in_precision_mode) {
+ // When 'trailing zero after the point' is set, then 'trailing point'
+ // must be set too.
+ ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
+ !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
+ }
+
+ // Returns a converter following the EcmaScript specification.
+ static const DoubleToStringConverter& EcmaScriptConverter();
+
+ // Computes the shortest string of digits that correctly represent the input
+ // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
+ // (see constructor) it then either returns a decimal representation, or an
+ // exponential representation.
+ // Example with decimal_in_shortest_low = -6,
+ // decimal_in_shortest_high = 21,
+ // EMIT_POSITIVE_EXPONENT_SIGN activated, and
+ // EMIT_TRAILING_DECIMAL_POINT deactived:
+ // ToShortest(0.000001) -> "0.000001"
+ // ToShortest(0.0000001) -> "1e-7"
+ // ToShortest(111111111111111111111.0) -> "111111111111111110000"
+ // ToShortest(100000000000000000000.0) -> "100000000000000000000"
+ // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
+ //
+ // Note: the conversion may round the output if the returned string
+ // is accurate enough to uniquely identify the input-number.
+ // For example the most precise representation of the double 9e59 equals
+ // "899999999999999918767229449717619953810131273674690656206848", but
+ // the converter will return the shorter (but still correct) "9e59".
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except when the input value is special and no infinity_symbol or
+ // nan_symbol has been given to the constructor.
+ bool ToShortest(double value, StringBuilder* result_builder) const {
+ return ToShortestIeeeNumber(value, result_builder, SHORTEST);
+ }
+
+ // Same as ToShortest, but for single-precision floats.
+ bool ToShortestSingle(float value, StringBuilder* result_builder) const {
+ return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
+ }
+
+
+ // Computes a decimal representation with a fixed number of digits after the
+ // decimal point. The last emitted digit is rounded.
+ //
+ // Examples:
+ // ToFixed(3.12, 1) -> "3.1"
+ // ToFixed(3.1415, 3) -> "3.142"
+ // ToFixed(1234.56789, 4) -> "1234.5679"
+ // ToFixed(1.23, 5) -> "1.23000"
+ // ToFixed(0.1, 4) -> "0.1000"
+ // ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
+ // ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
+ // ToFixed(0.1, 17) -> "0.10000000000000001"
+ //
+ // If requested_digits equals 0, then the tail of the result depends on
+ // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
+ // Examples, for requested_digits == 0,
+ // let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
+ // - false and false: then 123.45 -> 123
+ // 0.678 -> 1
+ // - true and false: then 123.45 -> 123.
+ // 0.678 -> 1.
+ // - true and true: then 123.45 -> 123.0
+ // 0.678 -> 1.0
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except for the following cases:
+ // - the input value is special and no infinity_symbol or nan_symbol has
+ // been provided to the constructor,
+ // - 'value' > 10^kMaxFixedDigitsBeforePoint, or
+ // - 'requested_digits' > kMaxFixedDigitsAfterPoint.
+ // The last two conditions imply that the result will never contain more than
+ // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
+ // (one additional character for the sign, and one for the decimal point).
+ bool ToFixed(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const;
+
+ // Computes a representation in exponential format with requested_digits
+ // after the decimal point. The last emitted digit is rounded.
+ // If requested_digits equals -1, then the shortest exponential representation
+ // is computed.
+ //
+ // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
+ // exponent_character set to 'e'.
+ // ToExponential(3.12, 1) -> "3.1e0"
+ // ToExponential(5.0, 3) -> "5.000e0"
+ // ToExponential(0.001, 2) -> "1.00e-3"
+ // ToExponential(3.1415, -1) -> "3.1415e0"
+ // ToExponential(3.1415, 4) -> "3.1415e0"
+ // ToExponential(3.1415, 3) -> "3.142e0"
+ // ToExponential(123456789000000, 3) -> "1.235e14"
+ // ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
+ // ToExponential(1000000000000000019884624838656.0, 32) ->
+ // "1.00000000000000001988462483865600e30"
+ // ToExponential(1234, 0) -> "1e3"
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except for the following cases:
+ // - the input value is special and no infinity_symbol or nan_symbol has
+ // been provided to the constructor,
+ // - 'requested_digits' > kMaxExponentialDigits.
+ // The last condition implies that the result will never contain more than
+ // kMaxExponentialDigits + 8 characters (the sign, the digit before the
+ // decimal point, the decimal point, the exponent character, the
+ // exponent's sign, and at most 3 exponent digits).
+ bool ToExponential(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const;
+
+ // Computes 'precision' leading digits of the given 'value' and returns them
+ // either in exponential or decimal format, depending on
+ // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
+ // constructor).
+ // The last computed digit is rounded.
+ //
+ // Example with max_leading_padding_zeroes_in_precision_mode = 6.
+ // ToPrecision(0.0000012345, 2) -> "0.0000012"
+ // ToPrecision(0.00000012345, 2) -> "1.2e-7"
+ // Similarily the converter may add up to
+ // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
+ // returning an exponential representation. A zero added by the
+ // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
+ // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
+ // ToPrecision(230.0, 2) -> "230"
+ // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
+ // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
+ // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
+ // EMIT_TRAILING_ZERO_AFTER_POINT:
+ // ToPrecision(123450.0, 6) -> "123450"
+ // ToPrecision(123450.0, 5) -> "123450"
+ // ToPrecision(123450.0, 4) -> "123500"
+ // ToPrecision(123450.0, 3) -> "123000"
+ // ToPrecision(123450.0, 2) -> "1.2e5"
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except for the following cases:
+ // - the input value is special and no infinity_symbol or nan_symbol has
+ // been provided to the constructor,
+ // - precision < kMinPericisionDigits
+ // - precision > kMaxPrecisionDigits
+ // The last condition implies that the result will never contain more than
+ // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
+ // exponent character, the exponent's sign, and at most 3 exponent digits).
+ bool ToPrecision(double value,
+ int precision,
+ StringBuilder* result_builder) const;
+
+ enum DtoaMode {
+ // Produce the shortest correct representation.
+ // For example the output of 0.299999999999999988897 is (the less accurate
+ // but correct) 0.3.
+ SHORTEST,
+ // Same as SHORTEST, but for single-precision floats.
+ SHORTEST_SINGLE,
+ // Produce a fixed number of digits after the decimal point.
+ // For instance fixed(0.1, 4) becomes 0.1000
+ // If the input number is big, the output will be big.
+ FIXED,
+ // Fixed number of digits (independent of the decimal point).
+ PRECISION
+ };
+
+ // The maximal number of digits that are needed to emit a double in base 10.
+ // A higher precision can be achieved by using more digits, but the shortest
+ // accurate representation of any double will never use more digits than
+ // kBase10MaximalLength.
+ // Note that DoubleToAscii null-terminates its input. So the given buffer
+ // should be at least kBase10MaximalLength + 1 characters long.
+ static const int kBase10MaximalLength = 17;
+
+ // Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or
+ // -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v'
+ // after it has been casted to a single-precision float. That is, in this
+ // mode static_cast<float>(v) must not be NaN, +Infinity or -Infinity.
+ //
+ // The result should be interpreted as buffer * 10^(point-length).
+ //
+ // The output depends on the given mode:
+ // - SHORTEST: produce the least amount of digits for which the internal
+ // identity requirement is still satisfied. If the digits are printed
+ // (together with the correct exponent) then reading this number will give
+ // 'v' again. The buffer will choose the representation that is closest to
+ // 'v'. If there are two at the same distance, than the one farther away
+ // from 0 is chosen (halfway cases - ending with 5 - are rounded up).
+ // In this mode the 'requested_digits' parameter is ignored.
+ // - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
+ // - FIXED: produces digits necessary to print a given number with
+ // 'requested_digits' digits after the decimal point. The produced digits
+ // might be too short in which case the caller has to fill the remainder
+ // with '0's.
+ // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
+ // Halfway cases are rounded towards +/-Infinity (away from 0). The call
+ // toFixed(0.15, 2) thus returns buffer="2", point=0.
+ // The returned buffer may contain digits that would be truncated from the
+ // shortest representation of the input.
+ // - PRECISION: produces 'requested_digits' where the first digit is not '0'.
+ // Even though the length of produced digits usually equals
+ // 'requested_digits', the function is allowed to return fewer digits, in
+ // which case the caller has to fill the missing digits with '0's.
+ // Halfway cases are again rounded away from 0.
+ // DoubleToAscii expects the given buffer to be big enough to hold all
+ // digits and a terminating null-character. In SHORTEST-mode it expects a
+ // buffer of at least kBase10MaximalLength + 1. In all other modes the
+ // requested_digits parameter and the padding-zeroes limit the size of the
+ // output. Don't forget the decimal point, the exponent character and the
+ // terminating null-character when computing the maximal output size.
+ // The given length is only used in debug mode to ensure the buffer is big
+ // enough.
+ static void DoubleToAscii(double v,
+ DtoaMode mode,
+ int requested_digits,
+ char* buffer,
+ int buffer_length,
+ bool* sign,
+ int* length,
+ int* point);
+
+ private:
+ // Implementation for ToShortest and ToShortestSingle.
+ bool ToShortestIeeeNumber(double value,
+ StringBuilder* result_builder,
+ DtoaMode mode) const;
+
+ // If the value is a special value (NaN or Infinity) constructs the
+ // corresponding string using the configured infinity/nan-symbol.
+ // If either of them is NULL or the value is not special then the
+ // function returns false.
+ bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
+ // Constructs an exponential representation (i.e. 1.234e56).
+ // The given exponent assumes a decimal point after the first decimal digit.
+ void CreateExponentialRepresentation(const char* decimal_digits,
+ int length,
+ int exponent,
+ StringBuilder* result_builder) const;
+ // Creates a decimal representation (i.e 1234.5678).
+ void CreateDecimalRepresentation(const char* decimal_digits,
+ int length,
+ int decimal_point,
+ int digits_after_point,
+ StringBuilder* result_builder) const;
+
+ const int flags_;
+ const char* const infinity_symbol_;
+ const char* const nan_symbol_;
+ const char exponent_character_;
+ const int decimal_in_shortest_low_;
+ const int decimal_in_shortest_high_;
+ const int max_leading_padding_zeroes_in_precision_mode_;
+ const int max_trailing_padding_zeroes_in_precision_mode_;
+
+ DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
+};
+
+
+class StringToDoubleConverter {
+ public:
+ // Enumeration for allowing octals and ignoring junk when converting
+ // strings to numbers.
+ enum Flags {
+ NO_FLAGS = 0,
+ ALLOW_HEX = 1,
+ ALLOW_OCTALS = 2,
+ ALLOW_TRAILING_JUNK = 4,
+ ALLOW_LEADING_SPACES = 8,
+ ALLOW_TRAILING_SPACES = 16,
+ ALLOW_SPACES_AFTER_SIGN = 32
+ };
+
+ // Flags should be a bit-or combination of the possible Flags-enum.
+ // - NO_FLAGS: no special flags.
+ // - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers.
+ // Ex: StringToDouble("0x1234") -> 4660.0
+ // In StringToDouble("0x1234.56") the characters ".56" are trailing
+ // junk. The result of the call is hence dependent on
+ // the ALLOW_TRAILING_JUNK flag and/or the junk value.
+ // With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK,
+ // the string will not be parsed as "0" followed by junk.
+ //
+ // - ALLOW_OCTALS: recognizes the prefix "0" for octals:
+ // If a sequence of octal digits starts with '0', then the number is
+ // read as octal integer. Octal numbers may only be integers.
+ // Ex: StringToDouble("01234") -> 668.0
+ // StringToDouble("012349") -> 12349.0 // Not a sequence of octal
+ // // digits.
+ // In StringToDouble("01234.56") the characters ".56" are trailing
+ // junk. The result of the call is hence dependent on
+ // the ALLOW_TRAILING_JUNK flag and/or the junk value.
+ // In StringToDouble("01234e56") the characters "e56" are trailing
+ // junk, too.
+ // - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of
+ // a double literal.
+ // - ALLOW_LEADING_SPACES: skip over leading spaces.
+ // - ALLOW_TRAILING_SPACES: ignore trailing spaces.
+ // - ALLOW_SPACES_AFTER_SIGN: ignore spaces after the sign.
+ // Ex: StringToDouble("- 123.2") -> -123.2.
+ // StringToDouble("+ 123.2") -> 123.2
+ //
+ // empty_string_value is returned when an empty string is given as input.
+ // If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string
+ // containing only spaces is converted to the 'empty_string_value', too.
+ //
+ // junk_string_value is returned when
+ // a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not
+ // part of a double-literal) is found.
+ // b) ALLOW_TRAILING_JUNK is set, but the string does not start with a
+ // double literal.
+ //
+ // infinity_symbol and nan_symbol are strings that are used to detect
+ // inputs that represent infinity and NaN. They can be null, in which case
+ // they are ignored.
+ // The conversion routine first reads any possible signs. Then it compares the
+ // following character of the input-string with the first character of
+ // the infinity, and nan-symbol. If either matches, the function assumes, that
+ // a match has been found, and expects the following input characters to match
+ // the remaining characters of the special-value symbol.
+ // This means that the following restrictions apply to special-value symbols:
+ // - they must not start with signs ('+', or '-'),
+ // - they must not have the same first character.
+ // - they must not start with digits.
+ //
+ // Examples:
+ // flags = ALLOW_HEX | ALLOW_TRAILING_JUNK,
+ // empty_string_value = 0.0,
+ // junk_string_value = NaN,
+ // infinity_symbol = "infinity",
+ // nan_symbol = "nan":
+ // StringToDouble("0x1234") -> 4660.0.
+ // StringToDouble("0x1234K") -> 4660.0.
+ // StringToDouble("") -> 0.0 // empty_string_value.
+ // StringToDouble(" ") -> NaN // junk_string_value.
+ // StringToDouble(" 1") -> NaN // junk_string_value.
+ // StringToDouble("0x") -> NaN // junk_string_value.
+ // StringToDouble("-123.45") -> -123.45.
+ // StringToDouble("--123.45") -> NaN // junk_string_value.
+ // StringToDouble("123e45") -> 123e45.
+ // StringToDouble("123E45") -> 123e45.
+ // StringToDouble("123e+45") -> 123e45.
+ // StringToDouble("123E-45") -> 123e-45.
+ // StringToDouble("123e") -> 123.0 // trailing junk ignored.
+ // StringToDouble("123e-") -> 123.0 // trailing junk ignored.
+ // StringToDouble("+NaN") -> NaN // NaN string literal.
+ // StringToDouble("-infinity") -> -inf. // infinity literal.
+ // StringToDouble("Infinity") -> NaN // junk_string_value.
+ //
+ // flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES,
+ // empty_string_value = 0.0,
+ // junk_string_value = NaN,
+ // infinity_symbol = NULL,
+ // nan_symbol = NULL:
+ // StringToDouble("0x1234") -> NaN // junk_string_value.
+ // StringToDouble("01234") -> 668.0.
+ // StringToDouble("") -> 0.0 // empty_string_value.
+ // StringToDouble(" ") -> 0.0 // empty_string_value.
+ // StringToDouble(" 1") -> 1.0
+ // StringToDouble("0x") -> NaN // junk_string_value.
+ // StringToDouble("0123e45") -> NaN // junk_string_value.
+ // StringToDouble("01239E45") -> 1239e45.
+ // StringToDouble("-infinity") -> NaN // junk_string_value.
+ // StringToDouble("NaN") -> NaN // junk_string_value.
+ StringToDoubleConverter(int flags,
+ double empty_string_value,
+ double junk_string_value,
+ const char* infinity_symbol,
+ const char* nan_symbol)
+ : flags_(flags),
+ empty_string_value_(empty_string_value),
+ junk_string_value_(junk_string_value),
+ infinity_symbol_(infinity_symbol),
+ nan_symbol_(nan_symbol) {
+ }
+
+ // Performs the conversion.
+ // The output parameter 'processed_characters_count' is set to the number
+ // of characters that have been processed to read the number.
+ // Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included
+ // in the 'processed_characters_count'. Trailing junk is never included.
+ double StringToDouble(const char* buffer,
+ int length,
+ int* processed_characters_count) {
+ return StringToIeee(buffer, length, processed_characters_count, true);
+ }
+
+ // Same as StringToDouble but reads a float.
+ // Note that this is not equivalent to static_cast<float>(StringToDouble(...))
+ // due to potential double-rounding.
+ float StringToFloat(const char* buffer,
+ int length,
+ int* processed_characters_count) {
+ return static_cast<float>(StringToIeee(buffer, length,
+ processed_characters_count, false));
+ }
+
+ private:
+ const int flags_;
+ const double empty_string_value_;
+ const double junk_string_value_;
+ const char* const infinity_symbol_;
+ const char* const nan_symbol_;
+
+ double StringToIeee(const char* buffer,
+ int length,
+ int* processed_characters_count,
+ bool read_as_double);
+
+ DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
[09/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/bignum-dtoa.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/bignum-dtoa.cc b/src/jiffy/c_src/double-conversion/bignum-dtoa.cc
new file mode 100644
index 0000000..b6c2e85
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/bignum-dtoa.cc
@@ -0,0 +1,640 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <math.h>
+
+#include "bignum-dtoa.h"
+
+#include "bignum.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+static int NormalizedExponent(uint64_t significand, int exponent) {
+ ASSERT(significand != 0);
+ while ((significand & Double::kHiddenBit) == 0) {
+ significand = significand << 1;
+ exponent = exponent - 1;
+ }
+ return exponent;
+}
+
+
+// Forward declarations:
+// Returns an estimation of k such that 10^(k-1) <= v < 10^k.
+static int EstimatePower(int exponent);
+// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
+// and denominator.
+static void InitialScaledStartValues(uint64_t significand,
+ int exponent,
+ bool lower_boundary_is_closer,
+ int estimated_power,
+ bool need_boundary_deltas,
+ Bignum* numerator,
+ Bignum* denominator,
+ Bignum* delta_minus,
+ Bignum* delta_plus);
+// Multiplies numerator/denominator so that its values lies in the range 1-10.
+// Returns decimal_point s.t.
+// v = numerator'/denominator' * 10^(decimal_point-1)
+// where numerator' and denominator' are the values of numerator and
+// denominator after the call to this function.
+static void FixupMultiply10(int estimated_power, bool is_even,
+ int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus);
+// Generates digits from the left to the right and stops when the generated
+// digits yield the shortest decimal representation of v.
+static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus,
+ bool is_even,
+ Vector<char> buffer, int* length);
+// Generates 'requested_digits' after the decimal point.
+static void BignumToFixed(int requested_digits, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length);
+// Generates 'count' digits of numerator/denominator.
+// Once 'count' digits have been produced rounds the result depending on the
+// remainder (remainders of exactly .5 round upwards). Might update the
+// decimal_point when rounding up (for example for 0.9999).
+static void GenerateCountedDigits(int count, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length);
+
+
+void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
+ Vector<char> buffer, int* length, int* decimal_point) {
+ ASSERT(v > 0);
+ ASSERT(!Double(v).IsSpecial());
+ uint64_t significand;
+ int exponent;
+ bool lower_boundary_is_closer;
+ if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
+ float f = static_cast<float>(v);
+ ASSERT(f == v);
+ significand = Single(f).Significand();
+ exponent = Single(f).Exponent();
+ lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
+ } else {
+ significand = Double(v).Significand();
+ exponent = Double(v).Exponent();
+ lower_boundary_is_closer = Double(v).LowerBoundaryIsCloser();
+ }
+ bool need_boundary_deltas =
+ (mode == BIGNUM_DTOA_SHORTEST || mode == BIGNUM_DTOA_SHORTEST_SINGLE);
+
+ bool is_even = (significand & 1) == 0;
+ int normalized_exponent = NormalizedExponent(significand, exponent);
+ // estimated_power might be too low by 1.
+ int estimated_power = EstimatePower(normalized_exponent);
+
+ // Shortcut for Fixed.
+ // The requested digits correspond to the digits after the point. If the
+ // number is much too small, then there is no need in trying to get any
+ // digits.
+ if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
+ buffer[0] = '\0';
+ *length = 0;
+ // Set decimal-point to -requested_digits. This is what Gay does.
+ // Note that it should not have any effect anyways since the string is
+ // empty.
+ *decimal_point = -requested_digits;
+ return;
+ }
+
+ Bignum numerator;
+ Bignum denominator;
+ Bignum delta_minus;
+ Bignum delta_plus;
+ // Make sure the bignum can grow large enough. The smallest double equals
+ // 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
+ // The maximum double is 1.7976931348623157e308 which needs fewer than
+ // 308*4 binary digits.
+ ASSERT(Bignum::kMaxSignificantBits >= 324*4);
+ InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
+ estimated_power, need_boundary_deltas,
+ &numerator, &denominator,
+ &delta_minus, &delta_plus);
+ // We now have v = (numerator / denominator) * 10^estimated_power.
+ FixupMultiply10(estimated_power, is_even, decimal_point,
+ &numerator, &denominator,
+ &delta_minus, &delta_plus);
+ // We now have v = (numerator / denominator) * 10^(decimal_point-1), and
+ // 1 <= (numerator + delta_plus) / denominator < 10
+ switch (mode) {
+ case BIGNUM_DTOA_SHORTEST:
+ case BIGNUM_DTOA_SHORTEST_SINGLE:
+ GenerateShortestDigits(&numerator, &denominator,
+ &delta_minus, &delta_plus,
+ is_even, buffer, length);
+ break;
+ case BIGNUM_DTOA_FIXED:
+ BignumToFixed(requested_digits, decimal_point,
+ &numerator, &denominator,
+ buffer, length);
+ break;
+ case BIGNUM_DTOA_PRECISION:
+ GenerateCountedDigits(requested_digits, decimal_point,
+ &numerator, &denominator,
+ buffer, length);
+ break;
+ default:
+ UNREACHABLE();
+ }
+ buffer[*length] = '\0';
+}
+
+
+// The procedure starts generating digits from the left to the right and stops
+// when the generated digits yield the shortest decimal representation of v. A
+// decimal representation of v is a number lying closer to v than to any other
+// double, so it converts to v when read.
+//
+// This is true if d, the decimal representation, is between m- and m+, the
+// upper and lower boundaries. d must be strictly between them if !is_even.
+// m- := (numerator - delta_minus) / denominator
+// m+ := (numerator + delta_plus) / denominator
+//
+// Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
+// If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
+// will be produced. This should be the standard precondition.
+static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus,
+ bool is_even,
+ Vector<char> buffer, int* length) {
+ // Small optimization: if delta_minus and delta_plus are the same just reuse
+ // one of the two bignums.
+ if (Bignum::Equal(*delta_minus, *delta_plus)) {
+ delta_plus = delta_minus;
+ }
+ *length = 0;
+ while (true) {
+ uint16_t digit;
+ digit = numerator->DivideModuloIntBignum(*denominator);
+ ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
+ // digit = numerator / denominator (integer division).
+ // numerator = numerator % denominator.
+ buffer[(*length)++] = digit + '0';
+
+ // Can we stop already?
+ // If the remainder of the division is less than the distance to the lower
+ // boundary we can stop. In this case we simply round down (discarding the
+ // remainder).
+ // Similarly we test if we can round up (using the upper boundary).
+ bool in_delta_room_minus;
+ bool in_delta_room_plus;
+ if (is_even) {
+ in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
+ } else {
+ in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
+ }
+ if (is_even) {
+ in_delta_room_plus =
+ Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
+ } else {
+ in_delta_room_plus =
+ Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
+ }
+ if (!in_delta_room_minus && !in_delta_room_plus) {
+ // Prepare for next iteration.
+ numerator->Times10();
+ delta_minus->Times10();
+ // We optimized delta_plus to be equal to delta_minus (if they share the
+ // same value). So don't multiply delta_plus if they point to the same
+ // object.
+ if (delta_minus != delta_plus) {
+ delta_plus->Times10();
+ }
+ } else if (in_delta_room_minus && in_delta_room_plus) {
+ // Let's see if 2*numerator < denominator.
+ // If yes, then the next digit would be < 5 and we can round down.
+ int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
+ if (compare < 0) {
+ // Remaining digits are less than .5. -> Round down (== do nothing).
+ } else if (compare > 0) {
+ // Remaining digits are more than .5 of denominator. -> Round up.
+ // Note that the last digit could not be a '9' as otherwise the whole
+ // loop would have stopped earlier.
+ // We still have an assert here in case the preconditions were not
+ // satisfied.
+ ASSERT(buffer[(*length) - 1] != '9');
+ buffer[(*length) - 1]++;
+ } else {
+ // Halfway case.
+ // TODO(floitsch): need a way to solve half-way cases.
+ // For now let's round towards even (since this is what Gay seems to
+ // do).
+
+ if ((buffer[(*length) - 1] - '0') % 2 == 0) {
+ // Round down => Do nothing.
+ } else {
+ ASSERT(buffer[(*length) - 1] != '9');
+ buffer[(*length) - 1]++;
+ }
+ }
+ return;
+ } else if (in_delta_room_minus) {
+ // Round down (== do nothing).
+ return;
+ } else { // in_delta_room_plus
+ // Round up.
+ // Note again that the last digit could not be '9' since this would have
+ // stopped the loop earlier.
+ // We still have an ASSERT here, in case the preconditions were not
+ // satisfied.
+ ASSERT(buffer[(*length) -1] != '9');
+ buffer[(*length) - 1]++;
+ return;
+ }
+ }
+}
+
+
+// Let v = numerator / denominator < 10.
+// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
+// from left to right. Once 'count' digits have been produced we decide wether
+// to round up or down. Remainders of exactly .5 round upwards. Numbers such
+// as 9.999999 propagate a carry all the way, and change the
+// exponent (decimal_point), when rounding upwards.
+static void GenerateCountedDigits(int count, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length) {
+ ASSERT(count >= 0);
+ for (int i = 0; i < count - 1; ++i) {
+ uint16_t digit;
+ digit = numerator->DivideModuloIntBignum(*denominator);
+ ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
+ // digit = numerator / denominator (integer division).
+ // numerator = numerator % denominator.
+ buffer[i] = digit + '0';
+ // Prepare for next iteration.
+ numerator->Times10();
+ }
+ // Generate the last digit.
+ uint16_t digit;
+ digit = numerator->DivideModuloIntBignum(*denominator);
+ if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
+ digit++;
+ }
+ buffer[count - 1] = digit + '0';
+ // Correct bad digits (in case we had a sequence of '9's). Propagate the
+ // carry until we hat a non-'9' or til we reach the first digit.
+ for (int i = count - 1; i > 0; --i) {
+ if (buffer[i] != '0' + 10) break;
+ buffer[i] = '0';
+ buffer[i - 1]++;
+ }
+ if (buffer[0] == '0' + 10) {
+ // Propagate a carry past the top place.
+ buffer[0] = '1';
+ (*decimal_point)++;
+ }
+ *length = count;
+}
+
+
+// Generates 'requested_digits' after the decimal point. It might omit
+// trailing '0's. If the input number is too small then no digits at all are
+// generated (ex.: 2 fixed digits for 0.00001).
+//
+// Input verifies: 1 <= (numerator + delta) / denominator < 10.
+static void BignumToFixed(int requested_digits, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length) {
+ // Note that we have to look at more than just the requested_digits, since
+ // a number could be rounded up. Example: v=0.5 with requested_digits=0.
+ // Even though the power of v equals 0 we can't just stop here.
+ if (-(*decimal_point) > requested_digits) {
+ // The number is definitively too small.
+ // Ex: 0.001 with requested_digits == 1.
+ // Set decimal-point to -requested_digits. This is what Gay does.
+ // Note that it should not have any effect anyways since the string is
+ // empty.
+ *decimal_point = -requested_digits;
+ *length = 0;
+ return;
+ } else if (-(*decimal_point) == requested_digits) {
+ // We only need to verify if the number rounds down or up.
+ // Ex: 0.04 and 0.06 with requested_digits == 1.
+ ASSERT(*decimal_point == -requested_digits);
+ // Initially the fraction lies in range (1, 10]. Multiply the denominator
+ // by 10 so that we can compare more easily.
+ denominator->Times10();
+ if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
+ // If the fraction is >= 0.5 then we have to include the rounded
+ // digit.
+ buffer[0] = '1';
+ *length = 1;
+ (*decimal_point)++;
+ } else {
+ // Note that we caught most of similar cases earlier.
+ *length = 0;
+ }
+ return;
+ } else {
+ // The requested digits correspond to the digits after the point.
+ // The variable 'needed_digits' includes the digits before the point.
+ int needed_digits = (*decimal_point) + requested_digits;
+ GenerateCountedDigits(needed_digits, decimal_point,
+ numerator, denominator,
+ buffer, length);
+ }
+}
+
+
+// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
+// v = f * 2^exponent and 2^52 <= f < 2^53.
+// v is hence a normalized double with the given exponent. The output is an
+// approximation for the exponent of the decimal approimation .digits * 10^k.
+//
+// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
+// Note: this property holds for v's upper boundary m+ too.
+// 10^k <= m+ < 10^k+1.
+// (see explanation below).
+//
+// Examples:
+// EstimatePower(0) => 16
+// EstimatePower(-52) => 0
+//
+// Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
+static int EstimatePower(int exponent) {
+ // This function estimates log10 of v where v = f*2^e (with e == exponent).
+ // Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
+ // Note that f is bounded by its container size. Let p = 53 (the double's
+ // significand size). Then 2^(p-1) <= f < 2^p.
+ //
+ // Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
+ // to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
+ // The computed number undershoots by less than 0.631 (when we compute log3
+ // and not log10).
+ //
+ // Optimization: since we only need an approximated result this computation
+ // can be performed on 64 bit integers. On x86/x64 architecture the speedup is
+ // not really measurable, though.
+ //
+ // Since we want to avoid overshooting we decrement by 1e10 so that
+ // floating-point imprecisions don't affect us.
+ //
+ // Explanation for v's boundary m+: the computation takes advantage of
+ // the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
+ // (even for denormals where the delta can be much more important).
+
+ const double k1Log10 = 0.30102999566398114; // 1/lg(10)
+
+ // For doubles len(f) == 53 (don't forget the hidden bit).
+ const int kSignificandSize = Double::kSignificandSize;
+ double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
+ return static_cast<int>(estimate);
+}
+
+
+// See comments for InitialScaledStartValues.
+static void InitialScaledStartValuesPositiveExponent(
+ uint64_t significand, int exponent,
+ int estimated_power, bool need_boundary_deltas,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ // A positive exponent implies a positive power.
+ ASSERT(estimated_power >= 0);
+ // Since the estimated_power is positive we simply multiply the denominator
+ // by 10^estimated_power.
+
+ // numerator = v.
+ numerator->AssignUInt64(significand);
+ numerator->ShiftLeft(exponent);
+ // denominator = 10^estimated_power.
+ denominator->AssignPowerUInt16(10, estimated_power);
+
+ if (need_boundary_deltas) {
+ // Introduce a common denominator so that the deltas to the boundaries are
+ // integers.
+ denominator->ShiftLeft(1);
+ numerator->ShiftLeft(1);
+ // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
+ // denominator (of 2) delta_plus equals 2^e.
+ delta_plus->AssignUInt16(1);
+ delta_plus->ShiftLeft(exponent);
+ // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
+ delta_minus->AssignUInt16(1);
+ delta_minus->ShiftLeft(exponent);
+ }
+}
+
+
+// See comments for InitialScaledStartValues
+static void InitialScaledStartValuesNegativeExponentPositivePower(
+ uint64_t significand, int exponent,
+ int estimated_power, bool need_boundary_deltas,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ // v = f * 2^e with e < 0, and with estimated_power >= 0.
+ // This means that e is close to 0 (have a look at how estimated_power is
+ // computed).
+
+ // numerator = significand
+ // since v = significand * 2^exponent this is equivalent to
+ // numerator = v * / 2^-exponent
+ numerator->AssignUInt64(significand);
+ // denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
+ denominator->AssignPowerUInt16(10, estimated_power);
+ denominator->ShiftLeft(-exponent);
+
+ if (need_boundary_deltas) {
+ // Introduce a common denominator so that the deltas to the boundaries are
+ // integers.
+ denominator->ShiftLeft(1);
+ numerator->ShiftLeft(1);
+ // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
+ // denominator (of 2) delta_plus equals 2^e.
+ // Given that the denominator already includes v's exponent the distance
+ // to the boundaries is simply 1.
+ delta_plus->AssignUInt16(1);
+ // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
+ delta_minus->AssignUInt16(1);
+ }
+}
+
+
+// See comments for InitialScaledStartValues
+static void InitialScaledStartValuesNegativeExponentNegativePower(
+ uint64_t significand, int exponent,
+ int estimated_power, bool need_boundary_deltas,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ // Instead of multiplying the denominator with 10^estimated_power we
+ // multiply all values (numerator and deltas) by 10^-estimated_power.
+
+ // Use numerator as temporary container for power_ten.
+ Bignum* power_ten = numerator;
+ power_ten->AssignPowerUInt16(10, -estimated_power);
+
+ if (need_boundary_deltas) {
+ // Since power_ten == numerator we must make a copy of 10^estimated_power
+ // before we complete the computation of the numerator.
+ // delta_plus = delta_minus = 10^estimated_power
+ delta_plus->AssignBignum(*power_ten);
+ delta_minus->AssignBignum(*power_ten);
+ }
+
+ // numerator = significand * 2 * 10^-estimated_power
+ // since v = significand * 2^exponent this is equivalent to
+ // numerator = v * 10^-estimated_power * 2 * 2^-exponent.
+ // Remember: numerator has been abused as power_ten. So no need to assign it
+ // to itself.
+ ASSERT(numerator == power_ten);
+ numerator->MultiplyByUInt64(significand);
+
+ // denominator = 2 * 2^-exponent with exponent < 0.
+ denominator->AssignUInt16(1);
+ denominator->ShiftLeft(-exponent);
+
+ if (need_boundary_deltas) {
+ // Introduce a common denominator so that the deltas to the boundaries are
+ // integers.
+ numerator->ShiftLeft(1);
+ denominator->ShiftLeft(1);
+ // With this shift the boundaries have their correct value, since
+ // delta_plus = 10^-estimated_power, and
+ // delta_minus = 10^-estimated_power.
+ // These assignments have been done earlier.
+ // The adjustments if f == 2^p-1 (lower boundary is closer) are done later.
+ }
+}
+
+
+// Let v = significand * 2^exponent.
+// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
+// and denominator. The functions GenerateShortestDigits and
+// GenerateCountedDigits will then convert this ratio to its decimal
+// representation d, with the required accuracy.
+// Then d * 10^estimated_power is the representation of v.
+// (Note: the fraction and the estimated_power might get adjusted before
+// generating the decimal representation.)
+//
+// The initial start values consist of:
+// - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
+// - a scaled (common) denominator.
+// optionally (used by GenerateShortestDigits to decide if it has the shortest
+// decimal converting back to v):
+// - v - m-: the distance to the lower boundary.
+// - m+ - v: the distance to the upper boundary.
+//
+// v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
+//
+// Let ep == estimated_power, then the returned values will satisfy:
+// v / 10^ep = numerator / denominator.
+// v's boundarys m- and m+:
+// m- / 10^ep == v / 10^ep - delta_minus / denominator
+// m+ / 10^ep == v / 10^ep + delta_plus / denominator
+// Or in other words:
+// m- == v - delta_minus * 10^ep / denominator;
+// m+ == v + delta_plus * 10^ep / denominator;
+//
+// Since 10^(k-1) <= v < 10^k (with k == estimated_power)
+// or 10^k <= v < 10^(k+1)
+// we then have 0.1 <= numerator/denominator < 1
+// or 1 <= numerator/denominator < 10
+//
+// It is then easy to kickstart the digit-generation routine.
+//
+// The boundary-deltas are only filled if the mode equals BIGNUM_DTOA_SHORTEST
+// or BIGNUM_DTOA_SHORTEST_SINGLE.
+
+static void InitialScaledStartValues(uint64_t significand,
+ int exponent,
+ bool lower_boundary_is_closer,
+ int estimated_power,
+ bool need_boundary_deltas,
+ Bignum* numerator,
+ Bignum* denominator,
+ Bignum* delta_minus,
+ Bignum* delta_plus) {
+ if (exponent >= 0) {
+ InitialScaledStartValuesPositiveExponent(
+ significand, exponent, estimated_power, need_boundary_deltas,
+ numerator, denominator, delta_minus, delta_plus);
+ } else if (estimated_power >= 0) {
+ InitialScaledStartValuesNegativeExponentPositivePower(
+ significand, exponent, estimated_power, need_boundary_deltas,
+ numerator, denominator, delta_minus, delta_plus);
+ } else {
+ InitialScaledStartValuesNegativeExponentNegativePower(
+ significand, exponent, estimated_power, need_boundary_deltas,
+ numerator, denominator, delta_minus, delta_plus);
+ }
+
+ if (need_boundary_deltas && lower_boundary_is_closer) {
+ // The lower boundary is closer at half the distance of "normal" numbers.
+ // Increase the common denominator and adapt all but the delta_minus.
+ denominator->ShiftLeft(1); // *2
+ numerator->ShiftLeft(1); // *2
+ delta_plus->ShiftLeft(1); // *2
+ }
+}
+
+
+// This routine multiplies numerator/denominator so that its values lies in the
+// range 1-10. That is after a call to this function we have:
+// 1 <= (numerator + delta_plus) /denominator < 10.
+// Let numerator the input before modification and numerator' the argument
+// after modification, then the output-parameter decimal_point is such that
+// numerator / denominator * 10^estimated_power ==
+// numerator' / denominator' * 10^(decimal_point - 1)
+// In some cases estimated_power was too low, and this is already the case. We
+// then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
+// estimated_power) but do not touch the numerator or denominator.
+// Otherwise the routine multiplies the numerator and the deltas by 10.
+static void FixupMultiply10(int estimated_power, bool is_even,
+ int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ bool in_range;
+ if (is_even) {
+ // For IEEE doubles half-way cases (in decimal system numbers ending with 5)
+ // are rounded to the closest floating-point number with even significand.
+ in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
+ } else {
+ in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
+ }
+ if (in_range) {
+ // Since numerator + delta_plus >= denominator we already have
+ // 1 <= numerator/denominator < 10. Simply update the estimated_power.
+ *decimal_point = estimated_power + 1;
+ } else {
+ *decimal_point = estimated_power;
+ numerator->Times10();
+ if (Bignum::Equal(*delta_minus, *delta_plus)) {
+ delta_minus->Times10();
+ delta_plus->AssignBignum(*delta_minus);
+ } else {
+ delta_minus->Times10();
+ delta_plus->Times10();
+ }
+ }
+}
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/bignum-dtoa.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/bignum-dtoa.h b/src/jiffy/c_src/double-conversion/bignum-dtoa.h
new file mode 100644
index 0000000..34b9619
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/bignum-dtoa.h
@@ -0,0 +1,84 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_BIGNUM_DTOA_H_
+#define DOUBLE_CONVERSION_BIGNUM_DTOA_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+enum BignumDtoaMode {
+ // Return the shortest correct representation.
+ // For example the output of 0.299999999999999988897 is (the less accurate but
+ // correct) 0.3.
+ BIGNUM_DTOA_SHORTEST,
+ // Same as BIGNUM_DTOA_SHORTEST but for single-precision floats.
+ BIGNUM_DTOA_SHORTEST_SINGLE,
+ // Return a fixed number of digits after the decimal point.
+ // For instance fixed(0.1, 4) becomes 0.1000
+ // If the input number is big, the output will be big.
+ BIGNUM_DTOA_FIXED,
+ // Return a fixed number of digits, no matter what the exponent is.
+ BIGNUM_DTOA_PRECISION
+};
+
+// Converts the given double 'v' to ascii.
+// The result should be interpreted as buffer * 10^(point-length).
+// The buffer will be null-terminated.
+//
+// The input v must be > 0 and different from NaN, and Infinity.
+//
+// The output depends on the given mode:
+// - SHORTEST: produce the least amount of digits for which the internal
+// identity requirement is still satisfied. If the digits are printed
+// (together with the correct exponent) then reading this number will give
+// 'v' again. The buffer will choose the representation that is closest to
+// 'v'. If there are two at the same distance, than the number is round up.
+// In this mode the 'requested_digits' parameter is ignored.
+// - FIXED: produces digits necessary to print a given number with
+// 'requested_digits' digits after the decimal point. The produced digits
+// might be too short in which case the caller has to fill the gaps with '0's.
+// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
+// Halfway cases are rounded up. The call toFixed(0.15, 2) thus returns
+// buffer="2", point=0.
+// Note: the length of the returned buffer has no meaning wrt the significance
+// of its digits. That is, just because it contains '0's does not mean that
+// any other digit would not satisfy the internal identity requirement.
+// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
+// Even though the length of produced digits usually equals
+// 'requested_digits', the function is allowed to return fewer digits, in
+// which case the caller has to fill the missing digits with '0's.
+// Halfway cases are again rounded up.
+// 'BignumDtoa' expects the given buffer to be big enough to hold all digits
+// and a terminating null-character.
+void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
+ Vector<char> buffer, int* length, int* point);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_BIGNUM_DTOA_H_
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/bignum.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/bignum.cc b/src/jiffy/c_src/double-conversion/bignum.cc
new file mode 100644
index 0000000..747491a
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/bignum.cc
@@ -0,0 +1,764 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "bignum.h"
+#include "utils.h"
+
+namespace double_conversion {
+
+Bignum::Bignum()
+ : bigits_(bigits_buffer_, kBigitCapacity), used_digits_(0), exponent_(0) {
+ for (int i = 0; i < kBigitCapacity; ++i) {
+ bigits_[i] = 0;
+ }
+}
+
+
+template<typename S>
+static int BitSize(S value) {
+ return 8 * sizeof(value);
+}
+
+// Guaranteed to lie in one Bigit.
+void Bignum::AssignUInt16(uint16_t value) {
+ ASSERT(kBigitSize >= BitSize(value));
+ Zero();
+ if (value == 0) return;
+
+ EnsureCapacity(1);
+ bigits_[0] = value;
+ used_digits_ = 1;
+}
+
+
+void Bignum::AssignUInt64(uint64_t value) {
+ const int kUInt64Size = 64;
+
+ Zero();
+ if (value == 0) return;
+
+ int needed_bigits = kUInt64Size / kBigitSize + 1;
+ EnsureCapacity(needed_bigits);
+ for (int i = 0; i < needed_bigits; ++i) {
+ bigits_[i] = value & kBigitMask;
+ value = value >> kBigitSize;
+ }
+ used_digits_ = needed_bigits;
+ Clamp();
+}
+
+
+void Bignum::AssignBignum(const Bignum& other) {
+ exponent_ = other.exponent_;
+ for (int i = 0; i < other.used_digits_; ++i) {
+ bigits_[i] = other.bigits_[i];
+ }
+ // Clear the excess digits (if there were any).
+ for (int i = other.used_digits_; i < used_digits_; ++i) {
+ bigits_[i] = 0;
+ }
+ used_digits_ = other.used_digits_;
+}
+
+
+static uint64_t ReadUInt64(Vector<const char> buffer,
+ int from,
+ int digits_to_read) {
+ uint64_t result = 0;
+ for (int i = from; i < from + digits_to_read; ++i) {
+ int digit = buffer[i] - '0';
+ ASSERT(0 <= digit && digit <= 9);
+ result = result * 10 + digit;
+ }
+ return result;
+}
+
+
+void Bignum::AssignDecimalString(Vector<const char> value) {
+ // 2^64 = 18446744073709551616 > 10^19
+ const int kMaxUint64DecimalDigits = 19;
+ Zero();
+ int length = value.length();
+ int pos = 0;
+ // Let's just say that each digit needs 4 bits.
+ while (length >= kMaxUint64DecimalDigits) {
+ uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
+ pos += kMaxUint64DecimalDigits;
+ length -= kMaxUint64DecimalDigits;
+ MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
+ AddUInt64(digits);
+ }
+ uint64_t digits = ReadUInt64(value, pos, length);
+ MultiplyByPowerOfTen(length);
+ AddUInt64(digits);
+ Clamp();
+}
+
+
+static int HexCharValue(char c) {
+ if ('0' <= c && c <= '9') return c - '0';
+ if ('a' <= c && c <= 'f') return 10 + c - 'a';
+ if ('A' <= c && c <= 'F') return 10 + c - 'A';
+ UNREACHABLE();
+ return 0; // To make compiler happy.
+}
+
+
+void Bignum::AssignHexString(Vector<const char> value) {
+ Zero();
+ int length = value.length();
+
+ int needed_bigits = length * 4 / kBigitSize + 1;
+ EnsureCapacity(needed_bigits);
+ int string_index = length - 1;
+ for (int i = 0; i < needed_bigits - 1; ++i) {
+ // These bigits are guaranteed to be "full".
+ Chunk current_bigit = 0;
+ for (int j = 0; j < kBigitSize / 4; j++) {
+ current_bigit += HexCharValue(value[string_index--]) << (j * 4);
+ }
+ bigits_[i] = current_bigit;
+ }
+ used_digits_ = needed_bigits - 1;
+
+ Chunk most_significant_bigit = 0; // Could be = 0;
+ for (int j = 0; j <= string_index; ++j) {
+ most_significant_bigit <<= 4;
+ most_significant_bigit += HexCharValue(value[j]);
+ }
+ if (most_significant_bigit != 0) {
+ bigits_[used_digits_] = most_significant_bigit;
+ used_digits_++;
+ }
+ Clamp();
+}
+
+
+void Bignum::AddUInt64(uint64_t operand) {
+ if (operand == 0) return;
+ Bignum other;
+ other.AssignUInt64(operand);
+ AddBignum(other);
+}
+
+
+void Bignum::AddBignum(const Bignum& other) {
+ ASSERT(IsClamped());
+ ASSERT(other.IsClamped());
+
+ // If this has a greater exponent than other append zero-bigits to this.
+ // After this call exponent_ <= other.exponent_.
+ Align(other);
+
+ // There are two possibilities:
+ // aaaaaaaaaaa 0000 (where the 0s represent a's exponent)
+ // bbbbb 00000000
+ // ----------------
+ // ccccccccccc 0000
+ // or
+ // aaaaaaaaaa 0000
+ // bbbbbbbbb 0000000
+ // -----------------
+ // cccccccccccc 0000
+ // In both cases we might need a carry bigit.
+
+ EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_);
+ Chunk carry = 0;
+ int bigit_pos = other.exponent_ - exponent_;
+ ASSERT(bigit_pos >= 0);
+ for (int i = 0; i < other.used_digits_; ++i) {
+ Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry;
+ bigits_[bigit_pos] = sum & kBigitMask;
+ carry = sum >> kBigitSize;
+ bigit_pos++;
+ }
+
+ while (carry != 0) {
+ Chunk sum = bigits_[bigit_pos] + carry;
+ bigits_[bigit_pos] = sum & kBigitMask;
+ carry = sum >> kBigitSize;
+ bigit_pos++;
+ }
+ used_digits_ = Max(bigit_pos, used_digits_);
+ ASSERT(IsClamped());
+}
+
+
+void Bignum::SubtractBignum(const Bignum& other) {
+ ASSERT(IsClamped());
+ ASSERT(other.IsClamped());
+ // We require this to be bigger than other.
+ ASSERT(LessEqual(other, *this));
+
+ Align(other);
+
+ int offset = other.exponent_ - exponent_;
+ Chunk borrow = 0;
+ int i;
+ for (i = 0; i < other.used_digits_; ++i) {
+ ASSERT((borrow == 0) || (borrow == 1));
+ Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow;
+ bigits_[i + offset] = difference & kBigitMask;
+ borrow = difference >> (kChunkSize - 1);
+ }
+ while (borrow != 0) {
+ Chunk difference = bigits_[i + offset] - borrow;
+ bigits_[i + offset] = difference & kBigitMask;
+ borrow = difference >> (kChunkSize - 1);
+ ++i;
+ }
+ Clamp();
+}
+
+
+void Bignum::ShiftLeft(int shift_amount) {
+ if (used_digits_ == 0) return;
+ exponent_ += shift_amount / kBigitSize;
+ int local_shift = shift_amount % kBigitSize;
+ EnsureCapacity(used_digits_ + 1);
+ BigitsShiftLeft(local_shift);
+}
+
+
+void Bignum::MultiplyByUInt32(uint32_t factor) {
+ if (factor == 1) return;
+ if (factor == 0) {
+ Zero();
+ return;
+ }
+ if (used_digits_ == 0) return;
+
+ // The product of a bigit with the factor is of size kBigitSize + 32.
+ // Assert that this number + 1 (for the carry) fits into double chunk.
+ ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
+ DoubleChunk carry = 0;
+ for (int i = 0; i < used_digits_; ++i) {
+ DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry;
+ bigits_[i] = static_cast<Chunk>(product & kBigitMask);
+ carry = (product >> kBigitSize);
+ }
+ while (carry != 0) {
+ EnsureCapacity(used_digits_ + 1);
+ bigits_[used_digits_] = carry & kBigitMask;
+ used_digits_++;
+ carry >>= kBigitSize;
+ }
+}
+
+
+void Bignum::MultiplyByUInt64(uint64_t factor) {
+ if (factor == 1) return;
+ if (factor == 0) {
+ Zero();
+ return;
+ }
+ ASSERT(kBigitSize < 32);
+ uint64_t carry = 0;
+ uint64_t low = factor & 0xFFFFFFFF;
+ uint64_t high = factor >> 32;
+ for (int i = 0; i < used_digits_; ++i) {
+ uint64_t product_low = low * bigits_[i];
+ uint64_t product_high = high * bigits_[i];
+ uint64_t tmp = (carry & kBigitMask) + product_low;
+ bigits_[i] = tmp & kBigitMask;
+ carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
+ (product_high << (32 - kBigitSize));
+ }
+ while (carry != 0) {
+ EnsureCapacity(used_digits_ + 1);
+ bigits_[used_digits_] = carry & kBigitMask;
+ used_digits_++;
+ carry >>= kBigitSize;
+ }
+}
+
+
+void Bignum::MultiplyByPowerOfTen(int exponent) {
+ const uint64_t kFive27 = UINT64_2PART_C(0x6765c793, fa10079d);
+ const uint16_t kFive1 = 5;
+ const uint16_t kFive2 = kFive1 * 5;
+ const uint16_t kFive3 = kFive2 * 5;
+ const uint16_t kFive4 = kFive3 * 5;
+ const uint16_t kFive5 = kFive4 * 5;
+ const uint16_t kFive6 = kFive5 * 5;
+ const uint32_t kFive7 = kFive6 * 5;
+ const uint32_t kFive8 = kFive7 * 5;
+ const uint32_t kFive9 = kFive8 * 5;
+ const uint32_t kFive10 = kFive9 * 5;
+ const uint32_t kFive11 = kFive10 * 5;
+ const uint32_t kFive12 = kFive11 * 5;
+ const uint32_t kFive13 = kFive12 * 5;
+ const uint32_t kFive1_to_12[] =
+ { kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
+ kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
+
+ ASSERT(exponent >= 0);
+ if (exponent == 0) return;
+ if (used_digits_ == 0) return;
+
+ // We shift by exponent at the end just before returning.
+ int remaining_exponent = exponent;
+ while (remaining_exponent >= 27) {
+ MultiplyByUInt64(kFive27);
+ remaining_exponent -= 27;
+ }
+ while (remaining_exponent >= 13) {
+ MultiplyByUInt32(kFive13);
+ remaining_exponent -= 13;
+ }
+ if (remaining_exponent > 0) {
+ MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
+ }
+ ShiftLeft(exponent);
+}
+
+
+void Bignum::Square() {
+ ASSERT(IsClamped());
+ int product_length = 2 * used_digits_;
+ EnsureCapacity(product_length);
+
+ // Comba multiplication: compute each column separately.
+ // Example: r = a2a1a0 * b2b1b0.
+ // r = 1 * a0b0 +
+ // 10 * (a1b0 + a0b1) +
+ // 100 * (a2b0 + a1b1 + a0b2) +
+ // 1000 * (a2b1 + a1b2) +
+ // 10000 * a2b2
+ //
+ // In the worst case we have to accumulate nb-digits products of digit*digit.
+ //
+ // Assert that the additional number of bits in a DoubleChunk are enough to
+ // sum up used_digits of Bigit*Bigit.
+ if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_) {
+ UNIMPLEMENTED();
+ }
+ DoubleChunk accumulator = 0;
+ // First shift the digits so we don't overwrite them.
+ int copy_offset = used_digits_;
+ for (int i = 0; i < used_digits_; ++i) {
+ bigits_[copy_offset + i] = bigits_[i];
+ }
+ // We have two loops to avoid some 'if's in the loop.
+ for (int i = 0; i < used_digits_; ++i) {
+ // Process temporary digit i with power i.
+ // The sum of the two indices must be equal to i.
+ int bigit_index1 = i;
+ int bigit_index2 = 0;
+ // Sum all of the sub-products.
+ while (bigit_index1 >= 0) {
+ Chunk chunk1 = bigits_[copy_offset + bigit_index1];
+ Chunk chunk2 = bigits_[copy_offset + bigit_index2];
+ accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
+ bigit_index1--;
+ bigit_index2++;
+ }
+ bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
+ accumulator >>= kBigitSize;
+ }
+ for (int i = used_digits_; i < product_length; ++i) {
+ int bigit_index1 = used_digits_ - 1;
+ int bigit_index2 = i - bigit_index1;
+ // Invariant: sum of both indices is again equal to i.
+ // Inner loop runs 0 times on last iteration, emptying accumulator.
+ while (bigit_index2 < used_digits_) {
+ Chunk chunk1 = bigits_[copy_offset + bigit_index1];
+ Chunk chunk2 = bigits_[copy_offset + bigit_index2];
+ accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
+ bigit_index1--;
+ bigit_index2++;
+ }
+ // The overwritten bigits_[i] will never be read in further loop iterations,
+ // because bigit_index1 and bigit_index2 are always greater
+ // than i - used_digits_.
+ bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
+ accumulator >>= kBigitSize;
+ }
+ // Since the result was guaranteed to lie inside the number the
+ // accumulator must be 0 now.
+ ASSERT(accumulator == 0);
+
+ // Don't forget to update the used_digits and the exponent.
+ used_digits_ = product_length;
+ exponent_ *= 2;
+ Clamp();
+}
+
+
+void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
+ ASSERT(base != 0);
+ ASSERT(power_exponent >= 0);
+ if (power_exponent == 0) {
+ AssignUInt16(1);
+ return;
+ }
+ Zero();
+ int shifts = 0;
+ // We expect base to be in range 2-32, and most often to be 10.
+ // It does not make much sense to implement different algorithms for counting
+ // the bits.
+ while ((base & 1) == 0) {
+ base >>= 1;
+ shifts++;
+ }
+ int bit_size = 0;
+ int tmp_base = base;
+ while (tmp_base != 0) {
+ tmp_base >>= 1;
+ bit_size++;
+ }
+ int final_size = bit_size * power_exponent;
+ // 1 extra bigit for the shifting, and one for rounded final_size.
+ EnsureCapacity(final_size / kBigitSize + 2);
+
+ // Left to Right exponentiation.
+ int mask = 1;
+ while (power_exponent >= mask) mask <<= 1;
+
+ // The mask is now pointing to the bit above the most significant 1-bit of
+ // power_exponent.
+ // Get rid of first 1-bit;
+ mask >>= 2;
+ uint64_t this_value = base;
+
+ bool delayed_multipliciation = false;
+ const uint64_t max_32bits = 0xFFFFFFFF;
+ while (mask != 0 && this_value <= max_32bits) {
+ this_value = this_value * this_value;
+ // Verify that there is enough space in this_value to perform the
+ // multiplication. The first bit_size bits must be 0.
+ if ((power_exponent & mask) != 0) {
+ uint64_t base_bits_mask =
+ ~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
+ bool high_bits_zero = (this_value & base_bits_mask) == 0;
+ if (high_bits_zero) {
+ this_value *= base;
+ } else {
+ delayed_multipliciation = true;
+ }
+ }
+ mask >>= 1;
+ }
+ AssignUInt64(this_value);
+ if (delayed_multipliciation) {
+ MultiplyByUInt32(base);
+ }
+
+ // Now do the same thing as a bignum.
+ while (mask != 0) {
+ Square();
+ if ((power_exponent & mask) != 0) {
+ MultiplyByUInt32(base);
+ }
+ mask >>= 1;
+ }
+
+ // And finally add the saved shifts.
+ ShiftLeft(shifts * power_exponent);
+}
+
+
+// Precondition: this/other < 16bit.
+uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
+ ASSERT(IsClamped());
+ ASSERT(other.IsClamped());
+ ASSERT(other.used_digits_ > 0);
+
+ // Easy case: if we have less digits than the divisor than the result is 0.
+ // Note: this handles the case where this == 0, too.
+ if (BigitLength() < other.BigitLength()) {
+ return 0;
+ }
+
+ Align(other);
+
+ uint16_t result = 0;
+
+ // Start by removing multiples of 'other' until both numbers have the same
+ // number of digits.
+ while (BigitLength() > other.BigitLength()) {
+ // This naive approach is extremely inefficient if the this divided other
+ // might be big. This function is implemented for doubleToString where
+ // the result should be small (less than 10).
+ ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
+ // Remove the multiples of the first digit.
+ // Example this = 23 and other equals 9. -> Remove 2 multiples.
+ result += bigits_[used_digits_ - 1];
+ SubtractTimes(other, bigits_[used_digits_ - 1]);
+ }
+
+ ASSERT(BigitLength() == other.BigitLength());
+
+ // Both bignums are at the same length now.
+ // Since other has more than 0 digits we know that the access to
+ // bigits_[used_digits_ - 1] is safe.
+ Chunk this_bigit = bigits_[used_digits_ - 1];
+ Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
+
+ if (other.used_digits_ == 1) {
+ // Shortcut for easy (and common) case.
+ int quotient = this_bigit / other_bigit;
+ bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
+ result += quotient;
+ Clamp();
+ return result;
+ }
+
+ int division_estimate = this_bigit / (other_bigit + 1);
+ result += division_estimate;
+ SubtractTimes(other, division_estimate);
+
+ if (other_bigit * (division_estimate + 1) > this_bigit) {
+ // No need to even try to subtract. Even if other's remaining digits were 0
+ // another subtraction would be too much.
+ return result;
+ }
+
+ while (LessEqual(other, *this)) {
+ SubtractBignum(other);
+ result++;
+ }
+ return result;
+}
+
+
+template<typename S>
+static int SizeInHexChars(S number) {
+ ASSERT(number > 0);
+ int result = 0;
+ while (number != 0) {
+ number >>= 4;
+ result++;
+ }
+ return result;
+}
+
+
+static char HexCharOfValue(int value) {
+ ASSERT(0 <= value && value <= 16);
+ if (value < 10) return value + '0';
+ return value - 10 + 'A';
+}
+
+
+bool Bignum::ToHexString(char* buffer, int buffer_size) const {
+ ASSERT(IsClamped());
+ // Each bigit must be printable as separate hex-character.
+ ASSERT(kBigitSize % 4 == 0);
+ const int kHexCharsPerBigit = kBigitSize / 4;
+
+ if (used_digits_ == 0) {
+ if (buffer_size < 2) return false;
+ buffer[0] = '0';
+ buffer[1] = '\0';
+ return true;
+ }
+ // We add 1 for the terminating '\0' character.
+ int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
+ SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
+ if (needed_chars > buffer_size) return false;
+ int string_index = needed_chars - 1;
+ buffer[string_index--] = '\0';
+ for (int i = 0; i < exponent_; ++i) {
+ for (int j = 0; j < kHexCharsPerBigit; ++j) {
+ buffer[string_index--] = '0';
+ }
+ }
+ for (int i = 0; i < used_digits_ - 1; ++i) {
+ Chunk current_bigit = bigits_[i];
+ for (int j = 0; j < kHexCharsPerBigit; ++j) {
+ buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
+ current_bigit >>= 4;
+ }
+ }
+ // And finally the last bigit.
+ Chunk most_significant_bigit = bigits_[used_digits_ - 1];
+ while (most_significant_bigit != 0) {
+ buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
+ most_significant_bigit >>= 4;
+ }
+ return true;
+}
+
+
+Bignum::Chunk Bignum::BigitAt(int index) const {
+ if (index >= BigitLength()) return 0;
+ if (index < exponent_) return 0;
+ return bigits_[index - exponent_];
+}
+
+
+int Bignum::Compare(const Bignum& a, const Bignum& b) {
+ ASSERT(a.IsClamped());
+ ASSERT(b.IsClamped());
+ int bigit_length_a = a.BigitLength();
+ int bigit_length_b = b.BigitLength();
+ if (bigit_length_a < bigit_length_b) return -1;
+ if (bigit_length_a > bigit_length_b) return +1;
+ for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
+ Chunk bigit_a = a.BigitAt(i);
+ Chunk bigit_b = b.BigitAt(i);
+ if (bigit_a < bigit_b) return -1;
+ if (bigit_a > bigit_b) return +1;
+ // Otherwise they are equal up to this digit. Try the next digit.
+ }
+ return 0;
+}
+
+
+int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
+ ASSERT(a.IsClamped());
+ ASSERT(b.IsClamped());
+ ASSERT(c.IsClamped());
+ if (a.BigitLength() < b.BigitLength()) {
+ return PlusCompare(b, a, c);
+ }
+ if (a.BigitLength() + 1 < c.BigitLength()) return -1;
+ if (a.BigitLength() > c.BigitLength()) return +1;
+ // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
+ // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
+ // of 'a'.
+ if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
+ return -1;
+ }
+
+ Chunk borrow = 0;
+ // Starting at min_exponent all digits are == 0. So no need to compare them.
+ int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
+ for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
+ Chunk chunk_a = a.BigitAt(i);
+ Chunk chunk_b = b.BigitAt(i);
+ Chunk chunk_c = c.BigitAt(i);
+ Chunk sum = chunk_a + chunk_b;
+ if (sum > chunk_c + borrow) {
+ return +1;
+ } else {
+ borrow = chunk_c + borrow - sum;
+ if (borrow > 1) return -1;
+ borrow <<= kBigitSize;
+ }
+ }
+ if (borrow == 0) return 0;
+ return -1;
+}
+
+
+void Bignum::Clamp() {
+ while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
+ used_digits_--;
+ }
+ if (used_digits_ == 0) {
+ // Zero.
+ exponent_ = 0;
+ }
+}
+
+
+bool Bignum::IsClamped() const {
+ return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
+}
+
+
+void Bignum::Zero() {
+ for (int i = 0; i < used_digits_; ++i) {
+ bigits_[i] = 0;
+ }
+ used_digits_ = 0;
+ exponent_ = 0;
+}
+
+
+void Bignum::Align(const Bignum& other) {
+ if (exponent_ > other.exponent_) {
+ // If "X" represents a "hidden" digit (by the exponent) then we are in the
+ // following case (a == this, b == other):
+ // a: aaaaaaXXXX or a: aaaaaXXX
+ // b: bbbbbbX b: bbbbbbbbXX
+ // We replace some of the hidden digits (X) of a with 0 digits.
+ // a: aaaaaa000X or a: aaaaa0XX
+ int zero_digits = exponent_ - other.exponent_;
+ EnsureCapacity(used_digits_ + zero_digits);
+ for (int i = used_digits_ - 1; i >= 0; --i) {
+ bigits_[i + zero_digits] = bigits_[i];
+ }
+ for (int i = 0; i < zero_digits; ++i) {
+ bigits_[i] = 0;
+ }
+ used_digits_ += zero_digits;
+ exponent_ -= zero_digits;
+ ASSERT(used_digits_ >= 0);
+ ASSERT(exponent_ >= 0);
+ }
+}
+
+
+void Bignum::BigitsShiftLeft(int shift_amount) {
+ ASSERT(shift_amount < kBigitSize);
+ ASSERT(shift_amount >= 0);
+ Chunk carry = 0;
+ for (int i = 0; i < used_digits_; ++i) {
+ Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
+ bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
+ carry = new_carry;
+ }
+ if (carry != 0) {
+ bigits_[used_digits_] = carry;
+ used_digits_++;
+ }
+}
+
+
+void Bignum::SubtractTimes(const Bignum& other, int factor) {
+ ASSERT(exponent_ <= other.exponent_);
+ if (factor < 3) {
+ for (int i = 0; i < factor; ++i) {
+ SubtractBignum(other);
+ }
+ return;
+ }
+ Chunk borrow = 0;
+ int exponent_diff = other.exponent_ - exponent_;
+ for (int i = 0; i < other.used_digits_; ++i) {
+ DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
+ DoubleChunk remove = borrow + product;
+ Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
+ bigits_[i + exponent_diff] = difference & kBigitMask;
+ borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
+ (remove >> kBigitSize));
+ }
+ for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
+ if (borrow == 0) return;
+ Chunk difference = bigits_[i] - borrow;
+ bigits_[i] = difference & kBigitMask;
+ borrow = difference >> (kChunkSize - 1);
+ ++i;
+ }
+ Clamp();
+}
+
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/bignum.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/bignum.h b/src/jiffy/c_src/double-conversion/bignum.h
new file mode 100644
index 0000000..5ec3544
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/bignum.h
@@ -0,0 +1,145 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_BIGNUM_H_
+#define DOUBLE_CONVERSION_BIGNUM_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+class Bignum {
+ public:
+ // 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
+ // This bignum can encode much bigger numbers, since it contains an
+ // exponent.
+ static const int kMaxSignificantBits = 3584;
+
+ Bignum();
+ void AssignUInt16(uint16_t value);
+ void AssignUInt64(uint64_t value);
+ void AssignBignum(const Bignum& other);
+
+ void AssignDecimalString(Vector<const char> value);
+ void AssignHexString(Vector<const char> value);
+
+ void AssignPowerUInt16(uint16_t base, int exponent);
+
+ void AddUInt16(uint16_t operand);
+ void AddUInt64(uint64_t operand);
+ void AddBignum(const Bignum& other);
+ // Precondition: this >= other.
+ void SubtractBignum(const Bignum& other);
+
+ void Square();
+ void ShiftLeft(int shift_amount);
+ void MultiplyByUInt32(uint32_t factor);
+ void MultiplyByUInt64(uint64_t factor);
+ void MultiplyByPowerOfTen(int exponent);
+ void Times10() { return MultiplyByUInt32(10); }
+ // Pseudocode:
+ // int result = this / other;
+ // this = this % other;
+ // In the worst case this function is in O(this/other).
+ uint16_t DivideModuloIntBignum(const Bignum& other);
+
+ bool ToHexString(char* buffer, int buffer_size) const;
+
+ // Returns
+ // -1 if a < b,
+ // 0 if a == b, and
+ // +1 if a > b.
+ static int Compare(const Bignum& a, const Bignum& b);
+ static bool Equal(const Bignum& a, const Bignum& b) {
+ return Compare(a, b) == 0;
+ }
+ static bool LessEqual(const Bignum& a, const Bignum& b) {
+ return Compare(a, b) <= 0;
+ }
+ static bool Less(const Bignum& a, const Bignum& b) {
+ return Compare(a, b) < 0;
+ }
+ // Returns Compare(a + b, c);
+ static int PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c);
+ // Returns a + b == c
+ static bool PlusEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
+ return PlusCompare(a, b, c) == 0;
+ }
+ // Returns a + b <= c
+ static bool PlusLessEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
+ return PlusCompare(a, b, c) <= 0;
+ }
+ // Returns a + b < c
+ static bool PlusLess(const Bignum& a, const Bignum& b, const Bignum& c) {
+ return PlusCompare(a, b, c) < 0;
+ }
+ private:
+ typedef uint32_t Chunk;
+ typedef uint64_t DoubleChunk;
+
+ static const int kChunkSize = sizeof(Chunk) * 8;
+ static const int kDoubleChunkSize = sizeof(DoubleChunk) * 8;
+ // With bigit size of 28 we loose some bits, but a double still fits easily
+ // into two chunks, and more importantly we can use the Comba multiplication.
+ static const int kBigitSize = 28;
+ static const Chunk kBigitMask = (1 << kBigitSize) - 1;
+ // Every instance allocates kBigitLength chunks on the stack. Bignums cannot
+ // grow. There are no checks if the stack-allocated space is sufficient.
+ static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
+
+ void EnsureCapacity(int size) {
+ if (size > kBigitCapacity) {
+ UNREACHABLE();
+ }
+ }
+ void Align(const Bignum& other);
+ void Clamp();
+ bool IsClamped() const;
+ void Zero();
+ // Requires this to have enough capacity (no tests done).
+ // Updates used_digits_ if necessary.
+ // shift_amount must be < kBigitSize.
+ void BigitsShiftLeft(int shift_amount);
+ // BigitLength includes the "hidden" digits encoded in the exponent.
+ int BigitLength() const { return used_digits_ + exponent_; }
+ Chunk BigitAt(int index) const;
+ void SubtractTimes(const Bignum& other, int factor);
+
+ Chunk bigits_buffer_[kBigitCapacity];
+ // A vector backed by bigits_buffer_. This way accesses to the array are
+ // checked for out-of-bounds errors.
+ Vector<Chunk> bigits_;
+ int used_digits_;
+ // The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
+ int exponent_;
+
+ DISALLOW_COPY_AND_ASSIGN(Bignum);
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_BIGNUM_H_
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/cached-powers.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/cached-powers.cc b/src/jiffy/c_src/double-conversion/cached-powers.cc
new file mode 100644
index 0000000..c676429
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/cached-powers.cc
@@ -0,0 +1,175 @@
+// Copyright 2006-2008 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <stdarg.h>
+#include <limits.h>
+#include <math.h>
+
+#include "utils.h"
+
+#include "cached-powers.h"
+
+namespace double_conversion {
+
+struct CachedPower {
+ uint64_t significand;
+ int16_t binary_exponent;
+ int16_t decimal_exponent;
+};
+
+static const CachedPower kCachedPowers[] = {
+ {UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
+ {UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
+ {UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
+ {UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
+ {UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
+ {UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
+ {UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
+ {UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
+ {UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
+ {UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
+ {UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
+ {UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
+ {UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
+ {UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
+ {UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
+ {UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
+ {UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
+ {UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
+ {UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
+ {UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
+ {UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
+ {UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
+ {UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
+ {UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
+ {UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
+ {UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
+ {UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
+ {UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
+ {UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
+ {UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
+ {UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
+ {UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
+ {UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
+ {UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
+ {UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
+ {UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
+ {UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
+ {UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
+ {UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
+ {UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
+ {UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
+ {UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
+ {UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
+ {UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
+ {UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
+ {UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
+ {UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
+ {UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
+ {UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
+ {UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
+ {UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
+ {UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
+ {UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
+ {UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
+ {UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
+ {UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
+ {UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
+ {UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
+ {UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
+ {UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
+ {UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
+ {UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
+ {UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
+ {UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
+ {UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
+ {UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
+ {UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
+ {UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
+ {UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
+ {UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
+ {UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
+ {UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
+ {UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
+ {UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
+ {UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
+ {UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
+ {UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
+ {UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
+ {UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
+ {UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
+ {UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
+ {UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
+ {UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
+ {UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
+ {UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
+ {UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
+ {UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
+};
+
+static const int kCachedPowersLength = ARRAY_SIZE(kCachedPowers);
+static const int kCachedPowersOffset = 348; // -1 * the first decimal_exponent.
+static const double kD_1_LOG2_10 = 0.30102999566398114; // 1 / lg(10)
+// Difference between the decimal exponents in the table above.
+const int PowersOfTenCache::kDecimalExponentDistance = 8;
+const int PowersOfTenCache::kMinDecimalExponent = -348;
+const int PowersOfTenCache::kMaxDecimalExponent = 340;
+
+void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
+ int min_exponent,
+ int max_exponent,
+ DiyFp* power,
+ int* decimal_exponent) {
+ int kQ = DiyFp::kSignificandSize;
+ double k = ceil((min_exponent + kQ - 1) * kD_1_LOG2_10);
+ int foo = kCachedPowersOffset;
+ int index =
+ (foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
+ ASSERT(0 <= index && index < kCachedPowersLength);
+ CachedPower cached_power = kCachedPowers[index];
+ ASSERT(min_exponent <= cached_power.binary_exponent);
+ ASSERT(cached_power.binary_exponent <= max_exponent);
+ *decimal_exponent = cached_power.decimal_exponent;
+ *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
+}
+
+
+void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent,
+ DiyFp* power,
+ int* found_exponent) {
+ ASSERT(kMinDecimalExponent <= requested_exponent);
+ ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
+ int index =
+ (requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
+ CachedPower cached_power = kCachedPowers[index];
+ *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
+ *found_exponent = cached_power.decimal_exponent;
+ ASSERT(*found_exponent <= requested_exponent);
+ ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
+}
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/cached-powers.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/cached-powers.h b/src/jiffy/c_src/double-conversion/cached-powers.h
new file mode 100644
index 0000000..61a5061
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/cached-powers.h
@@ -0,0 +1,64 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_CACHED_POWERS_H_
+#define DOUBLE_CONVERSION_CACHED_POWERS_H_
+
+#include "diy-fp.h"
+
+namespace double_conversion {
+
+class PowersOfTenCache {
+ public:
+
+ // Not all powers of ten are cached. The decimal exponent of two neighboring
+ // cached numbers will differ by kDecimalExponentDistance.
+ static const int kDecimalExponentDistance;
+
+ static const int kMinDecimalExponent;
+ static const int kMaxDecimalExponent;
+
+ // Returns a cached power-of-ten with a binary exponent in the range
+ // [min_exponent; max_exponent] (boundaries included).
+ static void GetCachedPowerForBinaryExponentRange(int min_exponent,
+ int max_exponent,
+ DiyFp* power,
+ int* decimal_exponent);
+
+ // Returns a cached power of ten x ~= 10^k such that
+ // k <= decimal_exponent < k + kCachedPowersDecimalDistance.
+ // The given decimal_exponent must satisfy
+ // kMinDecimalExponent <= requested_exponent, and
+ // requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
+ static void GetCachedPowerForDecimalExponent(int requested_exponent,
+ DiyFp* power,
+ int* found_exponent);
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_CACHED_POWERS_H_
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/diy-fp.cc
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/diy-fp.cc b/src/jiffy/c_src/double-conversion/diy-fp.cc
new file mode 100644
index 0000000..ddd1891
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/diy-fp.cc
@@ -0,0 +1,57 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+#include "diy-fp.h"
+#include "utils.h"
+
+namespace double_conversion {
+
+void DiyFp::Multiply(const DiyFp& other) {
+ // Simply "emulates" a 128 bit multiplication.
+ // However: the resulting number only contains 64 bits. The least
+ // significant 64 bits are only used for rounding the most significant 64
+ // bits.
+ const uint64_t kM32 = 0xFFFFFFFFU;
+ uint64_t a = f_ >> 32;
+ uint64_t b = f_ & kM32;
+ uint64_t c = other.f_ >> 32;
+ uint64_t d = other.f_ & kM32;
+ uint64_t ac = a * c;
+ uint64_t bc = b * c;
+ uint64_t ad = a * d;
+ uint64_t bd = b * d;
+ uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32);
+ // By adding 1U << 31 to tmp we round the final result.
+ // Halfway cases will be round up.
+ tmp += 1U << 31;
+ uint64_t result_f = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
+ e_ += other.e_ + 64;
+ f_ = result_f;
+}
+
+} // namespace double_conversion
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/diy-fp.h
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/diy-fp.h b/src/jiffy/c_src/double-conversion/diy-fp.h
new file mode 100644
index 0000000..9dcf8fb
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/diy-fp.h
@@ -0,0 +1,118 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided
+// with the distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef DOUBLE_CONVERSION_DIY_FP_H_
+#define DOUBLE_CONVERSION_DIY_FP_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+// This "Do It Yourself Floating Point" class implements a floating-point number
+// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
+// have the most significant bit of the significand set.
+// Multiplication and Subtraction do not normalize their results.
+// DiyFp are not designed to contain special doubles (NaN and Infinity).
+class DiyFp {
+ public:
+ static const int kSignificandSize = 64;
+
+ DiyFp() : f_(0), e_(0) {}
+ DiyFp(uint64_t f, int e) : f_(f), e_(e) {}
+
+ // this = this - other.
+ // The exponents of both numbers must be the same and the significand of this
+ // must be bigger than the significand of other.
+ // The result will not be normalized.
+ void Subtract(const DiyFp& other) {
+ ASSERT(e_ == other.e_);
+ ASSERT(f_ >= other.f_);
+ f_ -= other.f_;
+ }
+
+ // Returns a - b.
+ // The exponents of both numbers must be the same and this must be bigger
+ // than other. The result will not be normalized.
+ static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
+ DiyFp result = a;
+ result.Subtract(b);
+ return result;
+ }
+
+
+ // this = this * other.
+ void Multiply(const DiyFp& other);
+
+ // returns a * b;
+ static DiyFp Times(const DiyFp& a, const DiyFp& b) {
+ DiyFp result = a;
+ result.Multiply(b);
+ return result;
+ }
+
+ void Normalize() {
+ ASSERT(f_ != 0);
+ uint64_t f = f_;
+ int e = e_;
+
+ // This method is mainly called for normalizing boundaries. In general
+ // boundaries need to be shifted by 10 bits. We thus optimize for this case.
+ const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000);
+ while ((f & k10MSBits) == 0) {
+ f <<= 10;
+ e -= 10;
+ }
+ while ((f & kUint64MSB) == 0) {
+ f <<= 1;
+ e--;
+ }
+ f_ = f;
+ e_ = e;
+ }
+
+ static DiyFp Normalize(const DiyFp& a) {
+ DiyFp result = a;
+ result.Normalize();
+ return result;
+ }
+
+ uint64_t f() const { return f_; }
+ int e() const { return e_; }
+
+ void set_f(uint64_t new_value) { f_ = new_value; }
+ void set_e(int new_value) { e_ = new_value; }
+
+ private:
+ static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000);
+
+ uint64_t f_;
+ int e_;
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_DIY_FP_H_
[04/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/009-reg-issue-24.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/009-reg-issue-24.t b/src/jiffy/test/009-reg-issue-24.t
new file mode 100755
index 0000000..8c50247
--- /dev/null
+++ b/src/jiffy/test/009-reg-issue-24.t
@@ -0,0 +1,3459 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(1),
+ jiffy:encode(big_doc(), [uescape]),
+ etap:is(1, 1, "No segfault encoding large doc with uescapes."),
+ etap:end_tests().
+
+
+big_doc() ->
+ {[{<<"_id">>,<<"_design/bookmarks">>},
+ {<<"_rev">>,<<"1-1794a8236590d2fc6c288115dc539a3d">>},
+ {<<"lib">>,
+ {[{<<"app">>,
+ <<"\nmodule.exports = {\n\n views: require('./views'),\n shows : require('./shows'),\n rewrites: require('./rewrites'),\n updates: require('./updates')\n};\n\n// Bind event handlers\n// require('./events')\n">>},
+ {<<"rewrites">>,
+ <<"/**\n * Rewrite settings to be exported from the design doc\n */\n\nmodule.exports = [\n {from: '/static/*', to: 'static/*'},\n {from: '/bootstrap/*', to: 'bootstrap/*'},\n {from: '/modules.js', to: 'modules.js' },\n {\"from\": \"/_db/*\", \"to\": \"../../*\" },\n {\"from\": \"/_db\", \"to\": \"../..\" },\n {\"from\": \"/bookmark_lite\", \"to\" : \"_show/bookmark_lite\"},\n {\"from\": \"/bookmark\", \"to\" : \"_show/bookmark\"},\n {\"from\": \"/save\", \"to\" : \"_update/bookmark\"},\n {\"from\": \"/click/*\", \"to\" : \"_update/click/*\"},\n {\"from\": \"/archive/*\", \"to\" : \"_update/archive/*\"},\n {from: '/', to: 'index.html'}\n];">>},
+ {<<"shows">>,
+ <<"var templates = require('handlebars').templates;\n\nexports.bookmark_lite = function(doc, req) {\n\n return {\n code: 200,\n headers: {'content-type' : 'text/html'},\n body: templates['newBookmark.html']({\n title : req.query.title,\n url : req.query.url\n })\n };\n\n}\n\nexports.bookmark = function(doc, req) {\n return {\n code: 200,\n headers: {'content-type' : 'text/html'},\n body: '<h2>Hellp</h2>'\n };\n}\n\n">>},
+ {<<"updates">>,
+ <<"\nvar md5 = require('md5');\nvar querystring = require('querystring');\n\nexports.bookmark = function(doc, req) {\n\n var details = {};\n if (req.body && req.body.length > 0) {\n details = querystring.parse(req.body);\n }\n if (req.query.title) details.title = req.query.title;\n if (req.query.url) details.url = req.query.url;\n\n if (!doc) {\n var id = md5.hex(details.url);\n var doc = {\n _id : id,\n type: 'com.eckoit.bookmark',\n title : decodeURIComponent(details.title),\n url : decodeURIComponent(details.url),\n timestamp: new Date().getTime()\n };\n if (details.short_text) doc.short_text = details.short_text;\n log(doc);\n return [doc, 'SUCCESS']\n\n } else {\n\n }\n}\n\nexports.click = function(doc, req) {\n if (!doc.clicks) doc.clicks = 0;\n doc.clicks++;\n return [doc, 'SUCCESS'];\n}\n\nexports.archive = function(doc, req) {\
n doc.archive = true;\n return [doc, 'SUCCESS'];\n}">>},
+ {<<"views">>,
+ <<"\n\nexports.by_date = {\n map : function(doc) {\n\n if (doc.archive) return;\n\n if (doc.type && doc.type === 'com.eckoit.bookmark' ) {\n var timestamp = doc.timestamp;\n if (!timestamp) timestamp = new Date(0);\n emit(timestamp, null);\n }\n }\n}\n\nexports.by_views = {\n map : function(doc) {\n\n if (doc.archive) return;\n\n if (doc.type && doc.type === 'com.eckoit.bookmark' ) {\n var clicks = doc.clicks;\n if (!clicks) clicks = 0;\n\n var timestamp = doc.timestamp;\n if (!timestamp) timestamp = new Date(0);\n\n emit([clicks, timestamp], null);\n }\n }\n}\n\nexports.all_tags = {\n map : function(doc) {\n if (doc.type && doc.type == 'garden.tag') {\n emit(doc.hash, null);\n }\n }\n}\n">>}]}},
+ {<<"underscore">>,
+ <<"// Underscore.js 1.3.1\n// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.\n// Underscore is freely distributable under the MIT license.\n// Portions of Underscore are inspired or borrowed from Prototype,\n// Oliver Steele's Functional, and John Resig's Micro-Templating.\n// For all details and documentation:\n// http://documentcloud.github.com/underscore\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `global` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Establish the object that gets returned to break out of a loop iteration.\n var breaker = {};\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n
var slice = ArrayProto.slice,\n unshift = ArrayProto.unshift,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeForEach = ArrayProto.forEach,\n nativeMap = ArrayProto.map,\n nativeReduce = ArrayProto.reduce,\n nativeReduceRight = ArrayProto.reduceRight,\n nativeFilter = ArrayProto.filter,\n nativeEvery = ArrayProto.every,\n nativeSome = ArrayProto.some,\n nativeIndexOf = ArrayProto.indexOf,\n nativeLastIndexOf = ArrayProto.lastIndexOf,\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind;\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) { return new wrapper(obj); };\n\n // Export the Underscore object fo
r **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object via a string identifier,\n // for Closure Compiler \"advanced\" mode.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root['_'] = _;\n }\n\n // Current version.\n _.VERSION = '1.3.1';\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles objects with the built-in `forEach`, arrays, and raw objects.\n // Delegates to **ECMAScript 5**'s native `forEach` if available.\n var each = _.each = _.forEach = function(obj, iterator, context) {\n if (obj == null) return;\n if (nativeForEach && obj.forEach === nativeForEach) {\n obj.forEach(iterator, context);\n } else if (obj.length === +obj.length) {\n for (var i = 0, l =
obj.length; i < l; i++) {\n if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;\n }\n } else {\n for (var key in obj) {\n if (_.has(obj, key)) {\n if (iterator.call(context, obj[key], key, obj) === breaker) return;\n }\n }\n }\n };\n\n // Return the results of applying the iterator to each element.\n // Delegates to **ECMAScript 5**'s native `map` if available.\n _.map = _.collect = function(obj, iterator, context) {\n var results = [];\n if (obj == null) return results;\n if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);\n each(obj, function(value, index, list) {\n results[results.length] = iterator.call(context, value, index, list);\n });\n if (obj.length === +obj.length) results.length = obj.length;\n return results;\n };\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`. Delegates to **ECMAScript 5**'s
native `reduce` if available.\n _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {\n var initial = arguments.length > 2;\n if (obj == null) obj = [];\n if (nativeReduce && obj.reduce === nativeReduce) {\n if (context) iterator = _.bind(iterator, context);\n return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);\n }\n each(obj, function(value, index, list) {\n if (!initial) {\n memo = value;\n initial = true;\n } else {\n memo = iterator.call(context, memo, value, index, list);\n }\n });\n if (!initial) throw new TypeError('Reduce of empty array with no initial value');\n return memo;\n };\n\n // The right-associative version of reduce, also known as `foldr`.\n // Delegates to **ECMAScript 5**'s native `reduceRight` if available.\n _.reduceRight = _.foldr = function(obj, iterator, memo, context) {\n var initial = arguments.length > 2;\n if (obj == null) obj = [];\n
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {\n if (context) iterator = _.bind(iterator, context);\n return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);\n }\n var reversed = _.toArray(obj).reverse();\n if (context && !initial) iterator = _.bind(iterator, context);\n return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);\n };\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, iterator, context) {\n var result;\n any(obj, function(value, index, list) {\n if (iterator.call(context, value, index, list)) {\n result = value;\n return true;\n }\n });\n return result;\n };\n\n // Return all the elements that pass a truth test.\n // Delegates to **ECMAScript 5**'s native `filter` if available.\n // Aliased as `select`.\n _.filter = _.select = function(obj, iterator, context) {\n
var results = [];\n if (obj == null) return results;\n if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);\n each(obj, function(value, index, list) {\n if (iterator.call(context, value, index, list)) results[results.length] = value;\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, iterator, context) {\n var results = [];\n if (obj == null) return results;\n each(obj, function(value, index, list) {\n if (!iterator.call(context, value, index, list)) results[results.length] = value;\n });\n return results;\n };\n\n // Determine whether all of the elements match a truth test.\n // Delegates to **ECMAScript 5**'s native `every` if available.\n // Aliased as `all`.\n _.every = _.all = function(obj, iterator, context) {\n var result = true;\n if (obj == null) return result;\n if (nativeEvery && obj.every === nativeEvery) return obj.
every(iterator, context);\n each(obj, function(value, index, list) {\n if (!(result = result && iterator.call(context, value, index, list))) return breaker;\n });\n return result;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Delegates to **ECMAScript 5**'s native `some` if available.\n // Aliased as `any`.\n var any = _.some = _.any = function(obj, iterator, context) {\n iterator || (iterator = _.identity);\n var result = false;\n if (obj == null) return result;\n if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);\n each(obj, function(value, index, list) {\n if (result || (result = iterator.call(context, value, index, list))) return breaker;\n });\n return !!result;\n };\n\n // Determine if a given value is included in the array or object using `===`.\n // Aliased as `contains`.\n _.include = _.contains = function(obj, target) {\n var found = false;\n if (obj
== null) return found;\n if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;\n found = any(obj, function(value) {\n return value === target;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (_.isFunction(method) ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return -Infinity;\n var result = {computed : -Infinity};\n each(ob
j, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return Infinity;\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n if (index == 0) {\n shuffled[0] = value;\n } else {\n
rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n }\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator.\n _.sortBy = function(obj, iterator, context) {\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value : value,\n criteria : iterator.call(context, value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria, b = right.criteria;\n return a < b ? -1 : a > b ? 1 : 0;\n }), 'value');\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = function(obj, val) {\n var result = {};\n var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };\n each(obj, function(value, index) {\n var key = iterator(value, index);\n (re
sult[key] || (result[key] = [])).push(value);\n });\n return result;\n };\n\n // Use a comparator function to figure out at what index an object should\n // be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iterator) {\n iterator || (iterator = _.identity);\n var low = 0, high = array.length;\n while (low < high) {\n var mid = (low + high) >> 1;\n iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;\n }\n return low;\n };\n\n // Safely convert anything iterable into a real, live array.\n _.toArray = function(iterable) {\n if (!iterable) return [];\n if (iterable.toArray) return iterable.toArray();\n if (_.isArray(iterable)) return slice.call(iterable);\n if (_.isArguments(iterable)) return slice.call(iterable);\n return _.values(iterable);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n return _.toArr
ay(obj).length;\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head`. The **guard** check allows it to work\n // with `_.map`.\n _.first = _.head = function(array, n, guard) {\n return (n != null) && !guard ? slice.call(array, 0, n) : array[0];\n };\n\n // Returns everything but the last entry of the array. Especcialy useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N. The **guard** check allows it to work with\n // `_.map`.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array. The **guard** check allows it to work with `_.map`.\n _.last = function(array, n, guard) {\n if ((n != null) && !guard) {\n
return slice.call(array, Math.max(array.length - n, 0));\n } else {\n return array[array.length - 1];\n }\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail`.\n // Especially useful on the arguments object. Passing an **index** will return\n // the rest of the values in the array from that index onward. The **guard**\n // check allows it to work with `_.map`.\n _.rest = _.tail = function(array, index, guard) {\n return slice.call(array, (index == null) || guard ? 1 : index);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, function(value){ return !!value; });\n };\n\n // Return a completely flattened version of an array.\n _.flatten = function(array, shallow) {\n return _.reduce(array, function(memo, value) {\n if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));\n memo[memo.length] = value;\n return memo;\n }, []);
\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iterator) {\n var initial = iterator ? _.map(array, iterator) : array;\n var result = [];\n _.reduce(initial, function(memo, el, i) {\n if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {\n memo[memo.length] = el;\n result[result.length] = array[i];\n }\n return memo;\n }, []);\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(_.flatten(arguments, true));\n };\n\n // Produce a
n array that contains every item shared between all the\n // passed-in arrays. (Aliased as \"intersect\" for back-compat.)\n _.intersection = _.intersect = function(array) {\n var rest = slice.call(arguments, 1);\n return _.filter(_.uniq(array), function(item) {\n return _.every(rest, function(other) {\n return _.indexOf(other, item) >= 0;\n });\n });\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = _.flatten(slice.call(arguments, 1));\n return _.filter(array, function(value){ return !_.include(rest, value); });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function() {\n var args = slice.call(arguments);\n var length = _.max(_.pluck(args, 'length'));\n var results = new Array(length);\n for (var i = 0; i < lengt
h; i++) results[i] = _.pluck(args, \"\" + i);\n return results;\n };\n\n // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),\n // we need this function. Return the position of the first occurrence of an\n // item in an array, or -1 if the item is not included in the array.\n // Delegates to **ECMAScript 5**'s native `indexOf` if available.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = function(array, item, isSorted) {\n if (array == null) return -1;\n var i, l;\n if (isSorted) {\n i = _.sortedIndex(array, item);\n return array[i] === item ? i : -1;\n }\n if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);\n for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;\n return -1;\n };\n\n // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.\n _.lastIndexOf = f
unction(array, item) {\n if (array == null) return -1;\n if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);\n var i = array.length;\n while (i--) if (i in array && array[i] === item) return i;\n return -1;\n };\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (arguments.length <= 1) {\n stop = start || 0;\n start = 0;\n }\n step = arguments[2] || 1;\n\n var len = Math.max(Math.ceil((stop - start) / step), 0);\n var idx = 0;\n var range = new Array(len);\n\n while(idx < len) {\n range[idx++] = start;\n start += step;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Reusable constructor function for prototype setting.\n
var ctor = function(){};\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Binding with arguments is also known as `curry`.\n // Delegates to **ECMAScript 5**'s native `Function.bind` if available.\n // We check for `func.bind` first, to fail fast when `func` is undefined.\n _.bind = function bind(func, context) {\n var bound, args;\n if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError;\n args = slice.call(arguments, 2);\n return bound = function() {\n if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));\n ctor.prototype = func.prototype;\n var self = new ctor;\n var result = func.apply(self, args.concat(slice.call(arguments)));\n if (Object(result) === result) return result;\n return self;\n };\n };\n\n // Bind all of an object's methods to
that object. Useful for ensuring that\n // all callbacks defined on an object belong to it.\n _.bindAll = function(obj) {\n var funcs = slice.call(arguments, 1);\n if (funcs.length == 0) funcs = _.functions(obj);\n each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memo = {};\n hasher || (hasher = _.identity);\n return function() {\n var key = hasher.apply(this, arguments);\n return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));\n };\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){ return func.apply(func, args); }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack
has\n // cleared.\n _.defer = function(func) {\n return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));\n };\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time.\n _.throttle = function(func, wait) {\n var context, args, timeout, throttling, more;\n var whenDone = _.debounce(function(){ more = throttling = false; }, wait);\n return function() {\n context = this; args = arguments;\n var later = function() {\n timeout = null;\n if (more) func.apply(context, args);\n whenDone();\n };\n if (!timeout) timeout = setTimeout(later, wait);\n if (throttling) {\n more = true;\n } else {\n func.apply(context, args);\n }\n whenDone();\n throttling = true;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being ca
lled for\n // N milliseconds.\n _.debounce = function(func, wait) {\n var timeout;\n return function() {\n var context = this, args = arguments;\n var later = function() {\n timeout = null;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = function(func) {\n var ran = false, memo;\n return function() {\n if (ran) return memo;\n ran = true;\n return memo = func.apply(this, arguments);\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return function() {\n var args = [func].concat(slice.call(arguments, 0));\n
return wrapper.apply(this, args);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var funcs = arguments;\n return function() {\n var args = arguments;\n for (var i = funcs.length - 1; i >= 0; i--) {\n args = [funcs[i].apply(this, args)];\n }\n return args[0];\n };\n };\n\n // Returns a function that will only be executed after being called N times.\n _.after = function(times, func) {\n if (times <= 0) return func();\n return function() {\n if (--times < 1) { return func.apply(this, arguments); }\n };\n };\n\n // Object Functions\n // ----------------\n\n // Retrieve the names of an object's properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = nativeKeys || function(obj) {\n if (obj !== Object(obj)) throw new TypeError('Invalid object');\n var keys =
[];\n for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n return _.map(obj, _.identity);\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = function(obj) {\n each(slice.call(arguments, 1), function(source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n });\n return obj;\n };\n\n // Fill in a given object with default properties.\n _.defaults = function(obj) {\n each(slice.call(arguments, 1), function(source) {\n for (var prop in source) {\n if (obj[prop] == null)
obj[prop] = source[prop];\n }\n });\n return obj;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Internal recursive comparison function.\n function eq(a, b, stack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.\n if (a === b) return a !== 0 || 1 / a == 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwr
ap any wrapped objects.\n if (a._chain) a = a._wrapped;\n if (b._chain) b = b._wrapped;\n // Invoke a custom `isEqual` method if one is provided.\n if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);\n if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className != toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, dates, and booleans are compared by value.\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return a == String(b);\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for\n // other numeric values.\n return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);\n case '[object Date]':\n case '[ob
ject Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a == +b;\n // RegExps are compared by their source patterns and flags.\n case '[object RegExp]':\n return a.source == b.source &&\n a.global == b.global &&\n a.multiline == b.multiline &&\n a.ignoreCase == b.ignoreCase;\n }\n if (typeof a != 'object' || typeof b != 'object') return false;\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n var length = stack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (stack[length] == a) return
true;\n }\n // Add the first object to the stack of traversed objects.\n stack.push(a);\n var size = 0, result = true;\n // Recursively compare objects and arrays.\n if (className == '[object Array]') {\n // Compare array lengths to determine if a deep comparison is necessary.\n size = a.length;\n result = size == b.length;\n if (result) {\n // Deep compare the contents, ignoring non-numeric properties.\n while (size--) {\n // Ensure commutative equality for sparse arrays.\n if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;\n }\n }\n } else {\n // Objects with different constructors are not equivalent.\n if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;\n // Deep compare objects.\n for (var key in a) {\n if (_.has(a, key)) {\n // Count the expected number of properties.\n size++;\n
// Deep compare each member.\n if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;\n }\n }\n // Ensure that both objects contain the same number of properties.\n if (result) {\n for (key in b) {\n if (_.has(b, key) && !(size--)) break;\n }\n result = !size;\n }\n }\n // Remove the first object from the stack of traversed objects.\n stack.pop();\n return result;\n }\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b, []);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;\n for (var key in obj) if (_.has(obj, key)) return false;\n return true;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj
.nodeType == 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) == '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n return obj === Object(obj);\n };\n\n // Is a given variable an arguments object?\n _.isArguments = function(obj) {\n return toString.call(obj) == '[object Arguments]';\n };\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return !!(obj && _.has(obj, 'callee'));\n };\n }\n\n // Is a given value a function?\n _.isFunction = function(obj) {\n return toString.call(obj) == '[object Function]';\n };\n\n // Is a given value a string?\n _.isString = function(obj) {\n return toString.call(obj) == '[object String]';\n };\n\n // Is a given value a number?\n _.isNumber = function(obj) {\n return toString.call(obj) == '[object Number]';\n };\n\n // Is t
he given value `NaN`?\n _.isNaN = function(obj) {\n // `NaN` is the only value for which `===` is not reflexive.\n return obj !== obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) == '[object Boolean]';\n };\n\n // Is a given value a date?\n _.isDate = function(obj) {\n return toString.call(obj) == '[object Date]';\n };\n\n // Is the given value a regular expression?\n _.isRegExp = function(obj) {\n return toString.call(obj) == '[object RegExp]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Has own property?\n _.has = function(obj, key) {\n return hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning th
e `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iterators.\n _.identity = function(value) {\n return value;\n };\n\n // Run a function **n** times.\n _.times = function (n, iterator, context) {\n for (var i = 0; i < n; i++) iterator.call(context, i);\n };\n\n // Escape a string for HTML interpolation.\n _.escape = function(string) {\n return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/'/g, ''').replace(/\\//g,'/');\n };\n\n // Add your own custom functions to the Underscore object, ensuring that\n // they're correctly added to the OOP wrapper as well.\n _.mixin = function(obj) {\n each(_.functions(obj), function(name){\n addToWrapper(name, _[name] = obj[name]);\n });\n };\n\n // Generate a u
nique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = idCounter++;\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /.^/;\n\n // Within an interpolation, evaluation, or escaping, remove HTML escaping\n // that had been previously added.\n var unescape = function(code) {\n return code.replace(/\\\\\\\\/g, '\\\\').replace(/\\\\'/g, \"'\");\n };\n\n // JavaScript micro-templating, similar
to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n _.template = function(str, data) {\n var c = _.templateSettings;\n var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +\n 'with(obj||{}){__p.push(\\'' +\n str.replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(c.escape || noMatch, function(match, code) {\n return \"',_.escape(\" + unescape(code) + \"),'\";\n })\n .replace(c.interpolate || noMatch, function(match, code) {\n return \"',\" + unescape(code) + \",'\";\n })\n .replace(c.evaluate || noMatch, function(match, code) {\n return \"');\" + unescape(code).replace(/[\\r\\n\\t]/g, ' ') + \";__p.push('\";\n })\n .replace(/\\r/g, '\\\\r')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\t/g, '\\\\t')\n
+ \"');}return __p.join('');\";\n var func = new Function('obj', '_', tmpl);\n if (data) return func(data, _);\n return function(data) {\n return func.call(this, data, _);\n };\n };\n\n // Add a \"chain\" function, which will delegate to the wrapper.\n _.chain = function(obj) {\n return _(obj).chain();\n };\n\n // The OOP Wrapper\n // ---------------\n\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n var wrapper = function(obj) { this._wrapped = obj; };\n\n // Expose `wrapper.prototype` as `_.prototype`\n _.prototype = wrapper.prototype;\n\n // Helper function to continue chaining intermediate results.\n var result = function(obj, chain) {\n return chain ? _(obj).chain() : obj;\n };\n\n // A method to easily add functions to the OOP wrapper.\n var addToWrapper = function(name,
func) {\n wrapper.prototype[name] = function() {\n var args = slice.call(arguments);\n unshift.call(args, this._wrapped);\n return result(func.apply(_, args), this._chain);\n };\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n wrapper.prototype[name] = function() {\n var wrapped = this._wrapped;\n method.apply(wrapped, arguments);\n var length = wrapped.length;\n if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];\n return result(wrapped, this._chain);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n wrapper.prototype[name] = function() {\n return result(method.apply(
this._wrapped, arguments), this._chain);\n };\n });\n\n // Start chaining a wrapped Underscore object.\n wrapper.prototype.chain = function() {\n this._chain = true;\n return this;\n };\n\n // Extracts the result from a wrapped and chained object.\n wrapper.prototype.value = function() {\n return this._wrapped;\n };\n\n}).call(this);\n">>},
+ {<<"async">>,
+ <<"/*global setTimeout: false, console: false */\n(function () {\n\n var async = {};\n\n // global on the server, window in the browser\n var root = this,\n previous_async = root.async;\n\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = async;\n }\n else {\n root.async = async;\n }\n\n async.noConflict = function () {\n root.async = previous_async;\n return async;\n };\n\n //// cross-browser compatiblity functions ////\n\n var _forEach = function (arr, iterator) {\n if (arr.forEach) {\n return arr.forEach(iterator);\n }\n for (var i = 0; i < arr.length; i += 1) {\n iterator(arr[i], i, arr);\n }\n };\n\n var _map = function (arr, iterator) {\n if (arr.map) {\n return arr.map(iterator);\n }\n var results = [];\n _forEach(arr, function (x, i, a) {\n results.push(iterator(x, i, a));
\n });\n return results;\n };\n\n var _reduce = function (arr, iterator, memo) {\n if (arr.reduce) {\n return arr.reduce(iterator, memo);\n }\n _forEach(arr, function (x, i, a) {\n memo = iterator(memo, x, i, a);\n });\n return memo;\n };\n\n var _keys = function (obj) {\n if (Object.keys) {\n return Object.keys(obj);\n }\n var keys = [];\n for (var k in obj) {\n if (obj.hasOwnProperty(k)) {\n keys.push(k);\n }\n }\n return keys;\n };\n\n var _indexOf = function (arr, item) {\n if (arr.indexOf) {\n return arr.indexOf(item);\n }\n for (var i = 0; i < arr.length; i += 1) {\n if (arr[i] === item) {\n return i;\n }\n }\n return -1;\n };\n\n //// exported async module functions ////\n\n //// nextTick implementation with b
rowser-compatible fallback ////\n if (typeof process === 'undefined' || !(process.nextTick)) {\n async.nextTick = function (fn) {\n setTimeout(fn, 0);\n };\n }\n else {\n async.nextTick = process.nextTick;\n }\n\n async.forEach = function (arr, iterator, callback) {\n if (!arr.length) {\n return callback();\n }\n var completed = 0;\n _forEach(arr, function (x) {\n iterator(x, function (err) {\n if (err) {\n callback(err);\n callback = function () {};\n }\n else {\n completed += 1;\n if (completed === arr.length) {\n callback();\n }\n }\n });\n });\n };\n\n async.forEachSeries = function (arr, iterator, callback) {\n if (!arr.length) {\n return callback();\n }\n
var completed = 0;\n var iterate = function () {\n iterator(arr[completed], function (err) {\n if (err) {\n callback(err);\n callback = function () {};\n }\n else {\n completed += 1;\n if (completed === arr.length) {\n callback();\n }\n else {\n iterate();\n }\n }\n });\n };\n iterate();\n };\n \n async.forEachLimit = function (arr, limit, iterator, callback) {\n if (!arr.length || limit <= 0) {\n return callback(); \n }\n var completed = 0;\n var started = 0;\n var running = 0;\n \n (function replenish () {\n if (completed === arr.length) {\n return callback();\n }\n \n while (running
< limit && started < arr.length) {\n iterator(arr[started], function (err) {\n if (err) {\n callback(err);\n callback = function () {};\n }\n else {\n completed += 1;\n running -= 1;\n if (completed === arr.length) {\n callback();\n }\n else {\n replenish();\n }\n }\n });\n started += 1;\n running += 1;\n }\n })();\n };\n\n\n var doParallel = function (fn) {\n return function () {\n var args = Array.prototype.slice.call(arguments);\n return fn.apply(null, [async.forEach].concat(args));\n };\n };\n var doSeries = function (fn) {\n return function () {\n var args = Array.prototype.slice.call(arguments);\n return fn.apply(nul
l, [async.forEachSeries].concat(args));\n };\n };\n\n\n var _asyncMap = function (eachfn, arr, iterator, callback) {\n var results = [];\n arr = _map(arr, function (x, i) {\n return {index: i, value: x};\n });\n eachfn(arr, function (x, callback) {\n iterator(x.value, function (err, v) {\n results[x.index] = v;\n callback(err);\n });\n }, function (err) {\n callback(err, results);\n });\n };\n async.map = doParallel(_asyncMap);\n async.mapSeries = doSeries(_asyncMap);\n\n\n // reduce only has a series version, as doing reduce in parallel won't\n // work in many situations.\n async.reduce = function (arr, memo, iterator, callback) {\n async.forEachSeries(arr, function (x, callback) {\n iterator(memo, x, function (err, v) {\n memo = v;\n callback(err);\n });\n }, function (er
r) {\n callback(err, memo);\n });\n };\n // inject alias\n async.inject = async.reduce;\n // foldl alias\n async.foldl = async.reduce;\n\n async.reduceRight = function (arr, memo, iterator, callback) {\n var reversed = _map(arr, function (x) {\n return x;\n }).reverse();\n async.reduce(reversed, memo, iterator, callback);\n };\n // foldr alias\n async.foldr = async.reduceRight;\n\n var _filter = function (eachfn, arr, iterator, callback) {\n var results = [];\n arr = _map(arr, function (x, i) {\n return {index: i, value: x};\n });\n eachfn(arr, function (x, callback) {\n iterator(x.value, function (v) {\n if (v) {\n results.push(x);\n }\n callback();\n });\n }, function (err) {\n callback(_map(results.sort(function (a, b) {\n return a.index - b.inde
x;\n }), function (x) {\n return x.value;\n }));\n });\n };\n async.filter = doParallel(_filter);\n async.filterSeries = doSeries(_filter);\n // select alias\n async.select = async.filter;\n async.selectSeries = async.filterSeries;\n\n var _reject = function (eachfn, arr, iterator, callback) {\n var results = [];\n arr = _map(arr, function (x, i) {\n return {index: i, value: x};\n });\n eachfn(arr, function (x, callback) {\n iterator(x.value, function (v) {\n if (!v) {\n results.push(x);\n }\n callback();\n });\n }, function (err) {\n callback(_map(results.sort(function (a, b) {\n return a.index - b.index;\n }), function (x) {\n return x.value;\n }));\n });\n };\n async.reject = doParallel(_reject);\n async.reje
ctSeries = doSeries(_reject);\n\n var _detect = function (eachfn, arr, iterator, main_callback) {\n eachfn(arr, function (x, callback) {\n iterator(x, function (result) {\n if (result) {\n main_callback(x);\n main_callback = function () {};\n }\n else {\n callback();\n }\n });\n }, function (err) {\n main_callback();\n });\n };\n async.detect = doParallel(_detect);\n async.detectSeries = doSeries(_detect);\n\n async.some = function (arr, iterator, main_callback) {\n async.forEach(arr, function (x, callback) {\n iterator(x, function (v) {\n if (v) {\n main_callback(true);\n main_callback = function () {};\n }\n callback();\n });\n }, function (err) {\n main_callback(false);
\n });\n };\n // any alias\n async.any = async.some;\n\n async.every = function (arr, iterator, main_callback) {\n async.forEach(arr, function (x, callback) {\n iterator(x, function (v) {\n if (!v) {\n main_callback(false);\n main_callback = function () {};\n }\n callback();\n });\n }, function (err) {\n main_callback(true);\n });\n };\n // all alias\n async.all = async.every;\n\n async.sortBy = function (arr, iterator, callback) {\n async.map(arr, function (x, callback) {\n iterator(x, function (err, criteria) {\n if (err) {\n callback(err);\n }\n else {\n callback(null, {value: x, criteria: criteria});\n }\n });\n }, function (err, results) {\n if (err) {\n r
eturn callback(err);\n }\n else {\n var fn = function (left, right) {\n var a = left.criteria, b = right.criteria;\n return a < b ? -1 : a > b ? 1 : 0;\n };\n callback(null, _map(results.sort(fn), function (x) {\n return x.value;\n }));\n }\n });\n };\n\n async.auto = function (tasks, callback) {\n callback = callback || function () {};\n var keys = _keys(tasks);\n if (!keys.length) {\n return callback(null);\n }\n\n var results = {};\n\n var listeners = [];\n var addListener = function (fn) {\n listeners.unshift(fn);\n };\n var removeListener = function (fn) {\n for (var i = 0; i < listeners.length; i += 1) {\n if (listeners[i] === fn) {\n listeners.splice(i, 1);\n return;\n
}\n }\n };\n var taskComplete = function () {\n _forEach(listeners, function (fn) {\n fn();\n });\n };\n\n addListener(function () {\n if (_keys(results).length === keys.length) {\n callback(null, results);\n }\n });\n\n _forEach(keys, function (k) {\n var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k];\n var taskCallback = function (err) {\n if (err) {\n callback(err);\n // stop subsequent errors hitting callback multiple times\n callback = function () {};\n }\n else {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n results[k] = args;\n
taskComplete();\n }\n };\n var requires = task.slice(0, Math.abs(task.length - 1)) || [];\n var ready = function () {\n return _reduce(requires, function (a, x) {\n return (a && results.hasOwnProperty(x));\n }, true);\n };\n if (ready()) {\n task[task.length - 1](taskCallback, results);\n }\n else {\n var listener = function () {\n if (ready()) {\n removeListener(listener);\n task[task.length - 1](taskCallback, results);\n }\n };\n addListener(listener);\n }\n });\n };\n\n async.waterfall = function (tasks, callback) {\n if (!tasks.length) {\n return callback();\n }\n callback = callback || function () {};\n var wrapIterator = function (it
erator) {\n return function (err) {\n if (err) {\n callback(err);\n callback = function () {};\n }\n else {\n var args = Array.prototype.slice.call(arguments, 1);\n var next = iterator.next();\n if (next) {\n args.push(wrapIterator(next));\n }\n else {\n args.push(callback);\n }\n async.nextTick(function () {\n iterator.apply(null, args);\n });\n }\n };\n };\n wrapIterator(async.iterator(tasks))();\n };\n\n async.parallel = function (tasks, callback) {\n callback = callback || function () {};\n if (tasks.constructor === Array) {\n async.map(tasks, function (fn, callback) {\n if (fn) {\n
fn(function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n callback.call(null, err, args);\n });\n }\n }, callback);\n }\n else {\n var results = {};\n async.forEach(_keys(tasks), function (k, callback) {\n tasks[k](function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n results[k] = args;\n callback(err);\n });\n }, function (err) {\n callback(err, results);\n });\n }\n };\n\n async.series = function (tasks, callback) {\n callback = callb
ack || function () {};\n if (tasks.constructor === Array) {\n async.mapSeries(tasks, function (fn, callback) {\n if (fn) {\n fn(function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n callback.call(null, err, args);\n });\n }\n }, callback);\n }\n else {\n var results = {};\n async.forEachSeries(_keys(tasks), function (k, callback) {\n tasks[k](function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n results[k] = args;\n callback(err);\n });\n }, func
tion (err) {\n callback(err, results);\n });\n }\n };\n\n async.iterator = function (tasks) {\n var makeCallback = function (index) {\n var fn = function () {\n if (tasks.length) {\n tasks[index].apply(null, arguments);\n }\n return fn.next();\n };\n fn.next = function () {\n return (index < tasks.length - 1) ? makeCallback(index + 1): null;\n };\n return fn;\n };\n return makeCallback(0);\n };\n\n async.apply = function (fn) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function () {\n return fn.apply(\n null, args.concat(Array.prototype.slice.call(arguments))\n );\n };\n };\n\n var _concat = function (eachfn, arr, fn, callback) {\n var r = [];\n eachfn(arr, function (x, cb) {\n
fn(x, function (err, y) {\n r = r.concat(y || []);\n cb(err);\n });\n }, function (err) {\n callback(err, r);\n });\n };\n async.concat = doParallel(_concat);\n async.concatSeries = doSeries(_concat);\n\n async.whilst = function (test, iterator, callback) {\n if (test()) {\n iterator(function (err) {\n if (err) {\n return callback(err);\n }\n async.whilst(test, iterator, callback);\n });\n }\n else {\n callback();\n }\n };\n\n async.until = function (test, iterator, callback) {\n if (!test()) {\n iterator(function (err) {\n if (err) {\n return callback(err);\n }\n async.until(test, iterator, callback);\n });\n }\n else {\n callback();\n }\n };\n\n
async.queue = function (worker, concurrency) {\n var workers = 0;\n var q = {\n tasks: [],\n concurrency: concurrency,\n saturated: null,\n empty: null,\n drain: null,\n push: function (data, callback) {\n q.tasks.push({data: data, callback: callback});\n if(q.saturated && q.tasks.length == concurrency) q.saturated();\n async.nextTick(q.process);\n },\n process: function () {\n if (workers < q.concurrency && q.tasks.length) {\n var task = q.tasks.shift();\n if(q.empty && q.tasks.length == 0) q.empty();\n workers += 1;\n worker(task.data, function () {\n workers -= 1;\n if (task.callback) {\n task.callback.apply(task, arguments);\n }\n
if(q.drain && q.tasks.length + workers == 0) q.drain();\n q.process();\n });\n }\n },\n length: function () {\n return q.tasks.length;\n },\n running: function () {\n return workers;\n }\n };\n return q;\n };\n\n var _console_fn = function (name) {\n return function (fn) {\n var args = Array.prototype.slice.call(arguments, 1);\n fn.apply(null, args.concat([function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (typeof console !== 'undefined') {\n if (err) {\n if (console.error) {\n console.error(err);\n }\n }\n else if (console[name]) {\n _forEach(args, function (x) {\n
console[name](x);\n });\n }\n }\n }]));\n };\n };\n async.log = _console_fn('log');\n async.dir = _console_fn('dir');\n /*async.info = _console_fn('info');\n async.warn = _console_fn('warn');\n async.error = _console_fn('error');*/\n\n async.memoize = function (fn, hasher) {\n var memo = {};\n var queues = {};\n hasher = hasher || function (x) {\n return x;\n };\n var memoized = function () {\n var args = Array.prototype.slice.call(arguments);\n var callback = args.pop();\n var key = hasher.apply(null, args);\n if (key in memo) {\n callback.apply(null, memo[key]);\n }\n else if (key in queues) {\n queues[key].push(callback);\n }\n else {\n queues[key] = [callback];\n fn.apply(null, args.conca
t([function () {\n memo[key] = arguments;\n var q = queues[key];\n delete queues[key];\n for (var i = 0, l = q.length; i < l; i++) {\n q[i].apply(null, arguments);\n }\n }]));\n }\n };\n memoized.unmemoized = fn;\n return memoized;\n };\n\n async.unmemoize = function (fn) {\n return function () {\n return (fn.unmemoized || fn).apply(null, arguments);\n }\n };\n\n}());\n">>},
+ {<<"handlebars">>,
+ <<47,47,32,108,105,98,47,104,97,110,100,108,101,98,97,114,115,47,98,97,115,
+ 101,46,106,115,10,118,97,114,32,72,97,110,100,108,101,98,97,114,115,32,
+ 61,32,123,125,59,10,10,72,97,110,100,108,101,98,97,114,115,46,86,69,82,
+ 83,73,79,78,32,61,32,34,49,46,48,46,98,101,116,97,46,50,34,59,10,10,72,
+ 97,110,100,108,101,98,97,114,115,46,104,101,108,112,101,114,115,32,32,61,
+ 32,123,125,59,10,72,97,110,100,108,101,98,97,114,115,46,112,97,114,116,
+ 105,97,108,115,32,61,32,123,125,59,10,10,72,97,110,100,108,101,98,97,114,
+ 115,46,114,101,103,105,115,116,101,114,72,101,108,112,101,114,32,61,32,
+ 102,117,110,99,116,105,111,110,40,110,97,109,101,44,32,102,110,44,32,105,
+ 110,118,101,114,115,101,41,32,123,10,32,32,105,102,40,105,110,118,101,
+ 114,115,101,41,32,123,32,102,110,46,110,111,116,32,61,32,105,110,118,101,
+ 114,115,101,59,32,125,10,32,32,116,104,105,115,46,104,101,108,112,101,
+ 114,115,91,110,97,109,101,93,32,61,32,102,110,59,10,125,59,10,10,72,97,
+ 110,100,108,101,98,97,114,115,46,114,101,103,105,115,116,101,114,80,97,
+ 114,116,105,97,108,32,61,32,102,117,110,99,116,105,111,110,40,110,97,109,
+ 101,44,32,115,116,114,41,32,123,10,32,32,116,104,105,115,46,112,97,114,
+ 116,105,97,108,115,91,110,97,109,101,93,32,61,32,115,116,114,59,10,125,
+ 59,10,10,72,97,110,100,108,101,98,97,114,115,46,114,101,103,105,115,116,
+ 101,114,72,101,108,112,101,114,40,39,104,101,108,112,101,114,77,105,115,
+ 115,105,110,103,39,44,32,102,117,110,99,116,105,111,110,40,97,114,103,41,
+ 32,123,10,32,32,105,102,40,97,114,103,117,109,101,110,116,115,46,108,101,
+ 110,103,116,104,32,61,61,61,32,50,41,32,123,10,32,32,32,32,114,101,116,
+ 117,114,110,32,117,110,100,101,102,105,110,101,100,59,10,32,32,125,32,
+ 101,108,115,101,32,123,10,32,32,32,32,116,104,114,111,119,32,110,101,119,
+ 32,69,114,114,111,114,40,34,67,111,117,108,100,32,110,111,116,32,102,105,
+ 110,100,32,112,114,111,112,101,114,116,121,32,39,34,32,43,32,97,114,103,
+ 32,43,32,34,39,34,41,59,10,32,32,125,10,125,41,59,10,10,72,97,110,100,
+ 108,101,98,97,114,115,46,114,101,103,105,115,116,101,114,72,101,108,112,
+ 101,114,40,39,98,108,111,99,107,72,101,108,112,101,114,77,105,115,115,
+ 105,110,103,39,44,32,102,117,110,99,116,105,111,110,40,99,111,110,116,
+ 101,120,116,44,32,111,112,116,105,111,110,115,41,32,123,10,32,32,118,97,
+ 114,32,105,110,118,101,114,115,101,32,61,32,111,112,116,105,111,110,115,
+ 46,105,110,118,101,114,115,101,32,124,124,32,102,117,110,99,116,105,111,
+ 110,40,41,32,123,125,44,32,102,110,32,61,32,111,112,116,105,111,110,115,
+ 46,102,110,59,10,10,10,32,32,118,97,114,32,114,101,116,32,61,32,34,34,59,
+ 10,32,32,118,97,114,32,116,121,112,101,32,61,32,79,98,106,101,99,116,46,
+ 112,114,111,116,111,116,121,112,101,46,116,111,83,116,114,105,110,103,46,
+ 99,97,108,108,40,99,111,110,116,101,120,116,41,59,10,10,32,32,105,102,40,
+ 116,121,112,101,32,61,61,61,32,34,91,111,98,106,101,99,116,32,70,117,110,
+ 99,116,105,111,110,93,34,41,32,123,10,32,32,32,32,99,111,110,116,101,120,
+ 116,32,61,32,99,111,110,116,101,120,116,40,41,59,10,32,32,125,10,10,32,
+ 32,105,102,40,99,111,110,116,101,120,116,32,61,61,61,32,116,114,117,101,
+ 41,32,123,10,32,32,32,32,114,101,116,117,114,110,32,102,110,40,116,104,
+ 105,115,41,59,10,32,32,125,32,101,108,115,101,32,105,102,40,99,111,110,
+ 116,101,120,116,32,61,61,61,32,102,97,108,115,101,32,124,124,32,99,111,
+ 110,116,101,120,116,32,61,61,32,110,117,108,108,41,32,123,10,32,32,32,32,
+ 114,101,116,117,114,110,32,105,110,118,101,114,115,101,40,116,104,105,
+ 115,41,59,10,32,32,125,32,101,108,115,101,32,105,102,40,116,121,112,101,
+ 32,61,61,61,32,34,91,111,98,106,101,99,116,32,65,114,114,97,121,93,34,41,
+ 32,123,10,32,32,32,32,105,102,40,99,111,110,116,101,120,116,46,108,101,
+ 110,103,116,104,32,62,32,48,41,32,123,10,32,32,32,32,32,32,102,111,114,
+ 40,118,97,114,32,105,61,48,44,32,106,61,99,111,110,116,101,120,116,46,
+ 108,101,110,103,116,104,59,32,105,60,106,59,32,105,43,43,41,32,123,10,32,
+ 32,32,32,32,32,32,32,114,101,116,32,61,32,114,101,116,32,43,32,102,110,
+ 40,99,111,110,116,101,120,116,91,105,93,41,59,10,32,32,32,32,32,32,125,
+ 10,32,32,32,32,125,32,101,108,115,101,32,123,10,32,32,32,32,32,32,114,
+ 101,116,32,61,32,105,110,118,101,114,115,101,40,116,104,105,115,41,59,10,
+ 32,32,32,32,125,10,32,32,32,32,114,101,116,117,114,110,32,114,101,116,59,
+ 10,32,32,125,32,101,108,115,101,32,123,10,32,32,32,32,114,101,116,117,
+ 114,110,32,102,110,40,99,111,110,116,101,120,116,41,59,10,32,32,125,10,
+ 125,41,59,10,10,72,97,110,100,108,101,98,97,114,115,46,114,101,103,105,
+ 115,116,101,114,72,101,108,112,101,114,40,39,101,97,99,104,39,44,32,102,
+ 117,110,99,116,105,111,110,40,99,111,110,116,101,120,116,44,32,111,112,
+ 116,105,111,110,115,41,32,123,10,32,32,118,97,114,32,102,110,32,61,32,
+ 111,112,116,105,111,110,115,46,102,110,44,32,105,110,118,101,114,115,101,
+ 32,61,32,111,112,116,105,111,110,115,46,105,110,118,101,114,115,101,59,
+ 10,32,32,118,97,114,32,114,101,116,32,61,32,34,34,59,10,10,32,32,105,102,
+ 40,99,111,110,116,101,120,116,32,38,38,32,99,111,110,116,101,120,116,46,
+ 108,101,110,103,116,104,32,62,32,48,41,32,123,10,32,32,32,32,102,111,114,
+ 40,118,97,114,32,105,61,48,44,32,106,61,99,111,110,116,101,120,116,46,
+ 108,101,110,103,116,104,59,32,105,60,106,59,32,105,43,43,41,32,123,10,32,
+ 32,32,32,32,32,114,101,116,32,61,32,114,101,116,32,43,32,102,110,40,99,
+ 111,110,116,101,120,116,91,105,93,41,59,10,32,32,32,32,125,10,32,32,125,
+ 32,101,108,115,101,32,123,10,32,32,32,32,114,101,116,32,61,32,105,110,
+ 118,101,114,115,101,40,116,104,105,115,41,59,10,32,32,125,10,32,32,114,
+ 101,116,117,114,110,32,114,101,116,59,10,125,41,59,10,10,72,97,110,100,
+ 108,101,98,97,114,115,46,114,101,103,105,115,116,101,114,72,101,108,112,
+ 101,114,40,39,105,102,39,44,32,102,117,110,99,116,105,111,110,40,99,111,
+ 110,116,101,120,116,44,32,111,112,116,105,111,110,115,41,32,123,10,32,32,
+ 105,102,40,33,99,111,110,116,101,120,116,32,124,124,32,72,97,110,100,108,
+ 101,98,97,114,115,46,85,116,105,108,115,46,105,115,69,109,112,116,121,40,
+ 99,111,110,116,101,120,116,41,41,32,123,10,32,32,32,32,114,101,116,117,
+ 114,110,32,111,112,116,105,111,110,115,46,105,110,118,101,114,115,101,40,
+ 116,104,105,115,41,59,10,32,32,125,32,101,108,115,101,32,123,10,32,32,32,
+ 32,114,101,116,117,114,110,32,111,112,116,105,111,110,115,46,102,110,40,
+ 116,104,105,115,41,59,10,32,32,125,10,125,41,59,10,10,72,97,110,100,108,
+ 101,98,97,114,115,46,114,101,103,105,115,116,101,114,72,101,108,112,101,
+ 114,40,39,117,110,108,101,115,115,39,44,32,102,117,110,99,116,105,111,
+ 110,40,99,111,110,116,101,120,116,44,32,111,112,116,105,111,110,115,41,
+ 32,123,10,32,32,118,97,114,32,102,110,32,61,32,111,112,116,105,111,110,
+ 115,46,102,110,44,32,105,110,118,101,114,115,101,32,61,32,111,112,116,
+ 105,111,110,115,46,105,110,118,101,114,115,101,59,10,32,32,111,112,116,
+ 105,111,110,115,46,102,110,32,61,32,105,110,118,101,114,115,101,59,10,32,
+ 32,111,112,116,105,111,110,115,46,105,110,118,101,114,115,101,32,61,32,
+ 102,110,59,10,10,32,32,114,101,116,117,114,110,32,72,97,110,100,108,101,
+ 98,97,114,115,46,104,101,108,112,101,114,115,91,39,105,102,39,93,46,99,
+ 97,108,108,40,116,104,105,115,44,32,99,111,110,116,101,120,116,44,32,111,
+ 112,116,105,111,110,115,41,59,10,125,41,59,10,10,72,97,110,100,108,101,
+ 98,97,114,115,46,114,101,103,105,115,116,101,114,72,101,108,112,101,114,
+ 40,39,119,105,116,104,39,44,32,102,117,110,99,116,105,111,110,40,99,111,
+ 110,116,101,120,116,44,32,111,112,116,105,111,110,115,41,32,123,10,32,32,
+ 114,101,116,117,114,110,32,111,112,116,105,111,110,115,46,102,110,40,99,
+ 111,110,116,101,120,116,41,59,10,125,41,59,10,59,10,47,47,32,108,105,98,
+ 47,104,97,110,100,108,101,98,97,114,115,47,99,111,109,112,105,108,101,
+ 114,47,112,97,114,115,101,114,46,106,115,10,47,42,32,74,105,115,111,110,
+ 32,103,101,110,101,114,97,116,101,100,32,112,97,114,115,101,114,32,42,47,
+ 10,118,97,114,32,104,97,110,100,108,101,98,97,114,115,32,61,32,40,102,
+ 117,110,99,116,105,111,110,40,41,123,10,10,118,97,114,32,112,97,114,115,
+ 101,114,32,61,32,123,116,114,97,99,101,58,32,102,117,110,99,116,105,111,
+ 110,32,116,114,97,99,101,40,41,32,123,32,125,44,10,121,121,58,32,123,125,
+ 44,10,115,121,109,98,111,108,115,95,58,32,123,34,101,114,114,111,114,34,
+ 58,50,44,34,114,111,111,116,34,58,51,44,34,112,114,111,103,114,97,109,34,
+ 58,52,44,34,69,79,70,34,58,53,44,34,115,116,97,116,101,109,101,110,116,
+ 115,34,58,54,44,34,115,105,109,112,108,101,73,110,118,101,114,115,101,34,
+ 58,55,44,34,115,116,97,116,101,109,101,110,116,34,58,56,44,34,111,112,
+ 101,110,73,110,118,101,114,115,101,34,58,57,44,34,99,108,111,115,101,66,
+ 108,111,99,107,34,58,49,48,44,34,111,112,101,110,66,108,111,99,107,34,58,
+ 49,49,44,34,109,117,115,116,97,99,104,101,34,58,49,50,44,34,112,97,114,
+ 116,105,97,108,34,58,49,51,44,34,67,79,78,84,69,78,84,34,58,49,52,44,34,
+ 67,79,77,77,69,78,84,34,58,49,53,44,34,79,80,69,78,95,66,76,79,67,75,34,
+ 58,49,54,44,34,105,110,77,117,115,116,97,99,104,101,34,58,49,55,44,34,67,
+ 76,79,83,69,34,58,49,56,44,34,79,80,69,78,95,73,78,86,69,82,83,69,34,58,
+ 49,57,44,34,79,80,69,78,95,69,78,68,66,76,79,67,75,34,58,50,48,44,34,112,
+ 97,116,104,34,58,50,49,44,34,79,80,69,78,34,58,50,50,44,34,79,80,69,78,
+ 95,85,78,69,83,67,65,80,69,68,34,58,50,51,44,34,79,80,69,78,95,80,65,82,
+ 84,73,65,76,34,58,50,52,44,34,112,97,114,97,109,115,34,58,50,53,44,34,
+ 104,97,115,104,34,58,50,54,44,34,112,97,114,97,109,34,58,50,55,44,34,83,
+ 84,82,73,78,71,34,58,50,56,44,34,73,78,84,69,71,69,82,34,58,50,57,44,34,
+ 66,79,79,76,69,65,78,34,58,51,48,44,34,104,97,115,104,83,101,103,109,101,
+ 110,116,115,34,58,51,49,44,34,104,97,115,104,83,101,103,109,101,110,116,
+ 34,58,51,50,44,34,73,68,34,58,51,51,44,34,69,81,85,65,76,83,34,58,51,52,
+ 44,34,112,97,116,104,83,101,103,109,101,110,116,115,34,58,51,53,44,34,83,
+ 69,80,34,58,51,54,44,34,36,97,99,99,101,112,116,34,58,48,44,34,36,101,
+ 110,100,34,58,49,125,44,10,116,101,114,109,105,110,97,108,115,95,58,32,
+ 123,50,58,34,101,114,114,111,114,34,44,53,58,34,69,79,70,34,44,49,52,58,
+ 34,67,79,78,84,69,78,84,34,44,49,53,58,34,67,79,77,77,69,78,84,34,44,49,
+ 54,58,34,79,80,69,78,95,66,76,79,67,75,34,44,49,56,58,34,67,76,79,83,69,
+ 34,44,49,57,58,34,79,80,69,78,95,73,78,86,69,82,83,69,34,44,50,48,58,34,
+ 79,80,69,78,95,69,78,68,66,76,79,67,75,34,44,50,50,58,34,79,80,69,78,34,
+ 44,50,51,58,34,79,80,69,78,95,85,78,69,83,67,65,80,69,68,34,44,50,52,58,
+ 34,79,80,69,78,95,80,65,82,84,73,65,76,34,44,50,56,58,34,83,84,82,73,78,
+ 71,34,44,50,57,58,34,73,78,84,69,71,69,82,34,44,51,48,58,34,66,79,79,76,
+ 69,65,78,34,44,51,51,58,34,73,68,34,44,51,52,58,34,69,81,85,65,76,83,34,
+ 44,51,54,58,34,83,69,80,34,125,44,10,112,114,111,100,117,99,116,105,111,
+ 110,115,95,58,32,91,48,44,91,51,44,50,93,44,91,52,44,51,93,44,91,52,44,
+ 49,93,44,91,52,44,48,93,44,91,54,44,49,93,44,91,54,44,50,93,44,91,56,44,
+ 51,93,44,91,56,44,51,93,44,91,56,44,49,93,44,91,56,44,49,93,44,91,56,44,
+ 49,93,44,91,56,44,49,93,44,91,49,49,44,51,93,44,91,57,44,51,93,44,91,49,
+ 48,44,51,93,44,91,49,50,44,51,93,44,91,49,50,44,51,93,44,91,49,51,44,51,
+ 93,44,91,49,51,44,52,93,44,91,55,44,50,93,44,91,49,55,44,51,93,44,91,49,
+ 55,44,50,93,44,91,49,55,44,50,93,44,91,49,55,44,49,93,44,91,50,53,44,50,
+ 93,44,91,50,53,44,49,93,44,91,50,55,44,49,93,44,91,50,55,44,49,93,44,91,
+ 50,55,44,49,93,44,91,50,55,44,49,93,44,91,50,54,44,49,93,44,91,51,49,44,
+ 50,93,44,91,51,49,44,49,93,44,91,51,50,44,51,93,44,91,51,50,44,51,93,44,
+ 91,51,50,44,51,93,44,91,51,50,44,51,93,44,91,50,49,44,49,93,44,91,51,53,
+ 44,51,93,44,91,51,53,44,49,93,93,44,10,112,101,114,102,111,114,109,65,99,
+ 116,105,111,110,58,32,102,117,110,99,116,105,111,110,32,97,110,111,110,
+ 121,109,111,117,115,40,121,121,116,101,120,116,44,121,121,108,101,110,
+ 103,44,121,121,108,105,110,101,110,111,44,121,121,44,121,121,115,116,97,
+ 116,101,44,36,36,44,95,36,41,32,123,10,10,118,97,114,32,36,48,32,61,32,
+ 36,36,46,108,101,110,103,116,104,32,45,32,49,59,10,115,119,105,116,99,
+ 104,32,40,121,121,115,116,97,116,101,41,32,123,10,99,97,115,101,32,49,58,
+ 32,114,101,116,117,114,110,32,36,36,91,36,48,45,49,93,32,10,98,114,101,
+ 97,107,59,10,99,97,115,101,32,50,58,32,116,104,105,115,46,36,32,61,32,
+ 110,101,119,32,121,121,46,80,114,111,103,114,97,109,78,111,100,101,40,36,
+ 36,91,36,48,45,50,93,44,32,36,36,91,36,48,93,41,32,10,98,114,101,97,107,
+ 59,10,99,97,115,101,32,51,58,32,116,104,105,115,46,36,32,61,32,110,101,
+ 119,32,121,121,46,80,114,111,103,114,97,109,78,111,100,101,40,36,36,91,
+ 36,48,93,41,32,10,98,114,101,97,107,59,10,99,97,115,101,32,52,58,32,116,
+ 104,105,115,46,36,32,61,32,110,101,119,32,121,121,46,80,114,111,103,114,
+ 97,109,78,111,100,101,40,91,93,41,32,10,98,114,101,97,107,59,10,99,97,
+ 115,101,32,53,58,32,116,104,105,115,46,36,32,61,32,91,36,36,91,36,48,93,
+ 93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,54,58,32,36,36,91,36,
+ 48,45,49,93,46,112,117,115,104,40,36,36,91,36,48,93,41,59,32,116,104,105,
+ 115,46,36,32,61,32,36,36,91,36,48,45,49,93,32,10,98,114,101,97,107,59,10,
+ 99,97,115,101,32,55,58,32,116,104,105,115,46,36,32,61,32,110,101,119,32,
+ 121,121,46,73,110,118,101,114,115,101,78,111,100,101,40,36,36,91,36,48,
+ 45,50,93,44,32,36,36,91,36,48,45,49,93,44,32,36,36,91,36,48,93,41,32,10,
+ 98,114,101,97,107,59,10,99,97,115,101,32,56,58,32,116,104,105,115,46,36,
+ 32,61,32,110,101,119,32,121,121,46,66,108,111,99,107,78,111,100,101,40,
+ 36,36,91,36,48,45,50,93,44,32,36,36,91,36,48,45,49,93,44,32,36,36,91,36,
+ 48,93,41,32,10,98,114,101,97,107,59,10,99,97,115,101,32,57,58,32,116,104,
+ 105,115,46,36,32,61,32,36,36,91,36,48,93,32,10,98,114,101,97,107,59,10,
+ 99,97,115,101,32,49,48,58,32,116,104,105,115,46,36,32,61,32,36,36,91,36,
+ 48,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,49,49,58,32,116,104,
+ 105,115,46,36,32,61,32,110,101,119,32,121,121,46,67,111,110,116,101,110,
+ 116,78,111,100,101,40,36,36,91,36,48,93,41,32,10,98,114,101,97,107,59,10,
+ 99,97,115,101,32,49,50,58,32,116,104,105,115,46,36,32,61,32,110,101,119,
+ 32,121,121,46,67,111,109,109,101,110,116,78,111,100,101,40,36,36,91,36,
+ 48,93,41,32,10,98,114,101,97,107,59,10,99,97,115,101,32,49,51,58,32,116,
+ 104,105,115,46,36,32,61,32,110,101,119,32,121,121,46,77,117,115,116,97,
+ 99,104,101,78,111,100,101,40,36,36,91,36,48,45,49,93,91,48,93,44,32,36,
+ 36,91,36,48,45,49,93,91,49,93,41,32,10,98,114,101,97,107,59,10,99,97,115,
+ 101,32,49,52,58,32,116,104,105,115,46,36,32,61,32,110,101,119,32,121,121,
+ 46,77,117,115,116,97,99,104,101,78,111,100,101,40,36,36,91,36,48,45,49,
+ 93,91,48,93,44,32,36,36,91,36,48,45,49,93,91,49,93,41,32,10,98,114,101,
+ 97,107,59,10,99,97,115,101,32,49,53,58,32,116,104,105,115,46,36,32,61,32,
+ 36,36,91,36,48,45,49,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,
+ 49,54,58,32,116,104,105,115,46,36,32,61,32,110,101,119,32,121,121,46,77,
+ 117,115,116,97,99,104,101,78,111,100,101,40,36,36,91,36,48,45,49,93,91,
+ 48,93,44,32,36,36,91,36,48,45,49,93,91,49,93,41,32,10,98,114,101,97,107,
+ 59,10,99,97,115,101,32,49,55,58,32,116,104,105,115,46,36,32,61,32,110,
+ 101,119,32,121,121,46,77,117,115,116,97,99,104,101,78,111,100,101,40,36,
+ 36,91,36,48,45,49,93,91,48,93,44,32,36,36,91,36,48,45,49,93,91,49,93,44,
+ 32,116,114,117,101,41,32,10,98,114,101,97,107,59,10,99,97,115,101,32,49,
+ 56,58,32,116,104,105,115,46,36,32,61,32,110,101,119,32,121,121,46,80,97,
+ 114,116,105,97,108,78,111,100,101,40,36,36,91,36,48,45,49,93,41,32,10,98,
+ 114,101,97,107,59,10,99,97,115,101,32,49,57,58,32,116,104,105,115,46,36,
+ 32,61,32,110,101,119,32,121,121,46,80,97,114,116,105,97,108,78,111,100,
+ 101,40,36,36,91,36,48,45,50,93,44,32,36,36,91,36,48,45,49,93,41,32,10,98,
+ 114,101,97,107,59,10,99,97,115,101,32,50,48,58,32,10,98,114,101,97,107,
+ 59,10,99,97,115,101,32,50,49,58,32,116,104,105,115,46,36,32,61,32,91,91,
+ 36,36,91,36,48,45,50,93,93,46,99,111,110,99,97,116,40,36,36,91,36,48,45,
+ 49,93,41,44,32,36,36,91,36,48,93,93,32,10,98,114,101,97,107,59,10,99,97,
+ 115,101,32,50,50,58,32,116,104,105,115,46,36,32,61,32,91,91,36,36,91,36,
+ 48,45,49,93,93,46,99,111,110,99,97,116,40,36,36,91,36,48,93,41,44,32,110,
+ 117,108,108,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,50,51,58,
+ 32,116,104,105,115,46,36,32,61,32,91,91,36,36,91,36,48,45,49,93,93,44,32,
+ 36,36,91,36,48,93,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,50,
+ 52,58,32,116,104,105,115,46,36,32,61,32,91,91,36,36,91,36,48,93,93,44,32,
+ 110,117,108,108,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,50,53,
+ 58,32,36,36,91,36,48,45,49,93,46,112,117,115,104,40,36,36,91,36,48,93,41,
+ 59,32,116,104,105,115,46,36,32,61,32,36,36,91,36,48,45,49,93,59,32,10,98,
+ 114,101,97,107,59,10,99,97,115,101,32,50,54,58,32,116,104,105,115,46,36,
+ 32,61,32,91,36,36,91,36,48,93,93,32,10,98,114,101,97,107,59,10,99,97,115,
+ 101,32,50,55,58,32,116,104,105,115,46,36,32,61,32,36,36,91,36,48,93,32,
+ 10,98,114,101,97,107,59,10,99,97,115,101,32,50,56,58,32,116,104,105,115,
+ 46,36,32,61,32,110,101,119,32,121,121,46,83,116,114,105,110,103,78,111,
+ 100,101,40,36,36,91,36,48,93,41,32,10,98,114,101,97,107,59,10,99,97,115,
+ 101,32,50,57,58,32,116,104,105,115,46,36,32,61,32,110,101,119,32,121,121,
+ 46,73,110,116,101,103,101,114,78,111,100,101,40,36,36,91,36,48,93,41,32,
+ 10,98,114,101,97,107,59,10,99,97,115,101,32,51,48,58,32,116,104,105,115,
+ 46,36,32,61,32,110,101,119,32,121,121,46,66,111,111,108,101,97,110,78,
+ 111,100,101,40,36,36,91,36,48,93,41,32,10,98,114,101,97,107,59,10,99,97,
+ 115,101,32,51,49,58,32,116,104,105,115,46,36,32,61,32,110,101,119,32,121,
+ 121,46,72,97,115,104,78,111,100,101,40,36,36,91,36,48,93,41,32,10,98,114,
+ 101,97,107,59,10,99,97,115,101,32,51,50,58,32,36,36,91,36,48,45,49,93,46,
+ 112,117,115,104,40,36,36,91,36,48,93,41,59,32,116,104,105,115,46,36,32,
+ 61,32,36,36,91,36,48,45,49,93,32,10,98,114,101,97,107,59,10,99,97,115,
+ 101,32,51,51,58,32,116,104,105,115,46,36,32,61,32,91,36,36,91,36,48,93,
+ 93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,51,52,58,32,116,104,
+ 105,115,46,36,32,61,32,91,36,36,91,36,48,45,50,93,44,32,36,36,91,36,48,
+ 93,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,51,53,58,32,116,104,
+ 105,115,46,36,32,61,32,91,36,36,91,36,48,45,50,93,44,32,110,101,119,32,
+ 121,121,46,83,116,114,105,110,103,78,111,100,101,40,36,36,91,36,48,93,41,
+ 93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,51,54,58,32,116,104,
+ 105,115,46,36,32,61,32,91,36,36,91,36,48,45,50,93,44,32,110,101,119,32,
+ 121,121,46,73,110,116,101,103,101,114,78,111,100,101,40,36,36,91,36,48,
+ 93,41,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,51,55,58,32,116,
+ 104,105,115,46,36,32,61,32,91,36,36,91,36,48,45,50,93,44,32,110,101,119,
+ 32,121,121,46,66,111,111,108,101,97,110,78,111,100,101,40,36,36,91,36,48,
+ 93,41,93,32,10,98,114,101,97,107,59,10,99,97,115,101,32,51,56,58,32,116,
+ 104,105,115,46,36,32,61,32,110,101,119,32,121,121,46,73,100,78,111,100,
+ 101,40,36,36,91,36,48,93,41,32,10,98,114,101,97,107,59,10,99,97,115,101,
+ 32,51,57,58,32,36,36,91,36,48,45,50,93,46,112,117,115,104,40,36,36,91,36,
+ 48,93,41,59,32,116,104,105,115,46,36,32,61,32,36,36,91,36,48,45,50,93,59,
+ 32,10,98,114,101,97,107,59,10,99,97,115,101,32,52,48,58,32,116,104,105,
+ 115,46,36,32,61,32,91,36,36,91,36,48,93,93,32,10,98,114,101,97,107,59,10,
+ 125,10,125,44,10,116,97,98,108,101,58,32,91,123,51,58,49,44,52,58,50,44,
+ 53,58,91,50,44,52,93,44,54,58,51,44,56,58,52,44,57,58,53,44,49,49,58,54,
+ 44,49,50,58,55,44,49,51,58,56,44,49,52,58,91,49,44,57,93,44,49,53,58,91,
+ 49,44,49,48,93,44,49,54,58,91,49,44,49,50,93,44,49,57,58,91,49,44,49,49,
+ 93,44,50,50,58,91,49,44,49,51,93,44,50,51,58,91,49,44,49,52,93,44,50,52,
+ 58,91,49,44,49,53,93,125,44,123,49,58,91,51,93,125,44,123,53,58,91,49,44,
+ 49,54,93,125,44,123,53,58,91,50,44,51,93,44,55,58,49,55,44,56,58,49,56,
+ 44,57,58,53,44,49,49,58,54,44,49,50,58,55,44,49,51,58,56,44,49,52,58,91,
+ 49,44,57,93,44,49,53,58,91,49,44,49,48,93,44,49,54,58,91,49,44,49,50,93,
+ 44,49,57,58,91,49,44,49,57,93,44,50,48,58,91,50,44,51,93,44,50,50,58,91,
+ 49,44,49,51,93,44,50,51,58,91,49,44,49,52,93,44,50,52,58,91,49,44,49,53,
+ 93,125,44,123,53,58,91,50,44,53,93,44,49,52,58,91,50,44,53,93,44,49,53,
+ 58,91,50,44,53,93,44,49,54,58,91,50,44,53,93,44,49,57,58,91,50,44,53,93,
+ 44,50,48,58,91,50,44,53,93,44,50,50,58,91,50,44,53,93,44,50,51,58,91,50,
+ 44,53,93,44,50,52,58,91,50,44,53,93,125,44,123,52,58,50,48,44,54,58,51,
+ 44,56,58,52,44,57,58,53,44,49,49,58,54,44,49,50,58,55,44,49,51,58,56,44,
+ 49,52,58,91,49,44,57,93,44,49,53,58,91,49,44,49,48,93,44,49,54,58,91,49,
+ 44,49,50,93,44,49,57,58,91,49,44,49,49,93,44,50,48,58,91,50,44,52,93,44,
+ 50,50,58,91,49,44,49,51,93,44,50,51,58,91,49,44,49,52,93,44,50,52,58,91,
+ 49,44,49,53,93,125,44,123,52,58,50,49,44,54,58,51,44,56,58,52,44,57,58,
+ 53,44,49,49,58,54,44,49,50,58,55,44,49,51,58,56,44,49,52,58,91,49,44,57,
+ 93,44,49,53,58,91,49,44,49,48,93,44,49,54,58,91,49,44,49,50,93,44,49,57,
+ 58,91,49,44,49,49,93,44,50,48,58,91,50,44,52,93,44,50,50,58,91,49,44,49,
+ 51,93,44,50,51,58,91,49,44,49,52,93,44,50,52,58,91,49,44,49,53,93,125,44,
+ 123,53,58,91,50,44,57,93,44,49,52,58,91,50,44,57,93,44,49,53,58,91,50,44,
+ 57,93,44,49,54,58,91,50,44,57,93,44,49,57,58,91,50,44,57,93,44,50,48,58,
+ 91,50,44,57,93,44,50,50,58,91,50,44,57,93,44,50,51,58,91,50,44,57,93,44,
+ 50,52,58,91,50,44,57,93,125,44,123,53,58,91,50,44,49,48,93,44,49,52,58,
+ 91,50,44,49,48,93,44,49,53,58,91,50,44,49,48,93,44,49,54,58,91,50,44,49,
+ 48,93,44,49,57,58,91,50,44,49,48,93,44,50,48,58,91,50,44,49,48,93,44,50,
+ 50,58,91,50,44,49,48,93,44,50,51,58,91,50,44,49,48,93,44,50,52,58,91,50,
+ 44,49,48,93,125,44,123,53,58,91,50,44,49,49,93,44,49,52,58,91,50,44,49,
+ 49,93,44,49,53,58,91,50,44,49,49,93,44,49,54,58,91,50,44,49,49,93,44,49,
+ 57,58,91,50,44,49,49,93,44,50,48,58,91,50,44,49,49,93,44,50,50,58,91,50,
+ 44,49,49,93,44,50,51,58,91,50,44,49,49,93,44,50,52,58,91,50,44,49,49,93,
+ 125,44,123,53,58,91,50,44,49,50,93,44,49,52,58,91,50,44,49,50,93,44,49,
+ 53,58,91,50,44,49,50,93,44,49,54,58,91,50,44,49,50,93,44,49,57,58,91,50,
+ 44,49,50,93,44,50,48,58,91,50,44,49,50,93,44,50,50,58,91,50,44,49,50,93,
+ 44,50,51,58,91,50,44,49,50,93,44,50,52,58,91,50,44,49,50,93,125,44,123,
+ 49,55,58,50,50,44,50,49,58,50,51,44,51,51,58,91,49,44,50,53,93,44,51,53,
+ 58,50,52,125,44,123,49,55,58,50,54,44,50,49,58,50,51,44,51,51,58,91,49,
+ 44,50,53,93,44,51,53,58,50,52,125,44,123,49,55,58,50,55,44,50,49,58,50,
+ 51,44,51,51,58,91,49,44,50,53,93,44,51,53,58,50,52,125,44,123,49,55,58,
+ 50,56,44,50,49,58,50,51,44,51,51,58,91,49,44,50,53,93,44,51,53,58,50,52,
+ 125,44,123,50,49,58,50,57,44,51,51,58,91,49,44,50,53,93,44,51,53,58,50,
+ 52,125,44,123,49,58,91,50,44,49,93,125,44,123,54,58,51,48,44,56,58,52,44,
+ 57,58,53,44,49,49,58,54,44,49,50,58,55,44,49,51,58,56,44,49,52,58,91,49,
+ 44,57,93,44,49,53,58,91,49,44,49,48,93,44,49,54,58,91,49,44,49,50,93,44,
+ 49,57,58,91,49,44,49,49,93,44,50,50,58,91,49,44,49,51,93,44,50,51,58,91,
+ 49,44,49,52,93,44,50,52,58,91,49,44,49,53,93,125,44,123,53,58,91,50,44,
+ 54,93,44,49,52,58,91,50,44,54,93,44,49,53,58,91,50,44,54,93,44,49,54,58,
+ 91,50,44,54,93,44,49,57,58,91,50,44,54,93,44,50,48,58,91,50,44,54,93,44,
+ 50,50,58,91,50,44,54,93,44,50,51,58,91,50,44,54,93,44,50,52,58,91,50,44,
+ 54,93,125,44,123,49,55,58,50,50,44,49,56,58,91,49,44,51,49,93,44,50,49,
+ 58,50,51,44,51,51,58,91,49,44,50,53,93,44,51,53,58,50,52,125,44,123,49,
+ 48,58,51,50,44,50,48,58,91,49,44,51,51,93,125,44,123,49,48,58,51,52,44,
+ 50,48,58,91,49,44,51,51,93,125,44,123,49,56,58,91,49,44,51,53,93,125,44,
+ 123,49,56,58,91,50,44,50,52,93,44,50,49,58,52,48,44,50,53,58,51,54,44,50,
+ 54,58,51,55,44,50,55,58,51,56,44,50,56,58,91,49,44,52,49,93,44,50,57,58,
+ 91,49,44,52,50,93,44,51,48,58,91,49,44,52,51,93,44,51,49,58,51,57,44,51,
+ 50,58,52,52,44,51,51,58,91,49,44,52,53,93,44,51,53,58,50,52,125,44,123,
+ 49,56,58,91,50,44,51,56,93,44,50,56,58,91,50,44,51,56,93,44,50,57,58,91,
+ 50,44,51,56,93,44,51,48,58,91,50,44,51,56,93,44,51,51,58,91,50,44,51,56,
+ 93,44,51,54,58,91,49,44,52,54,93,125,44,123,49,56,58,91,50,44,52,48,93,
+ 44,50,56,58,91,50,44,52,48,93,44,50,57,58,91,50,44,52,48,93,44,51,48,58,
+ 91,50,44,52,48,93,44,51,51,58,91,50,44,52,48,93,44,51,54,58,91,50,44,52,
+ 48,93,125,44,123,49,56,58,91,49,44,52,55,93,125,44,123,49,56,58,91,49,44,
+ 52,56,93,125,44,123,49,56,58,91,49,44,52,57,93,125,44,123,49,56,58,91,49,
+ 44,53,48,93,44,50,49,58,53,49,44,51,51,58,91,49,44,50,53,93,44,51,53,58,
+ 50,52,125,44,123,53,58,91,50,44,50,93,44,56,58,49,56,44,57,58,53,44,49,
+ 49,58,54,44,49,50,58,55,44,49,51,58,56,44,49,52,58,91,49,44,57,93,44,49,
+ 53,58,91,
<TRUNCATED>
[11/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_gen.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_gen.c b/src/ejson/c_src/yajl/yajl_gen.c
deleted file mode 100644
index 6cfda0a..0000000
--- a/src/ejson/c_src/yajl/yajl_gen.c
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "yajl_gen.h"
-#include "yajl_buf.h"
-#include "yajl_encode.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <math.h>
-
-typedef enum {
- yajl_gen_start,
- yajl_gen_map_start,
- yajl_gen_map_key,
- yajl_gen_map_val,
- yajl_gen_array_start,
- yajl_gen_in_array,
- yajl_gen_complete,
- yajl_gen_error
-} yajl_gen_state;
-
-struct yajl_gen_t
-{
- unsigned int depth;
- unsigned int pretty;
- const char * indentString;
- yajl_gen_state state[YAJL_MAX_DEPTH];
- yajl_print_t print;
- void * ctx; /* yajl_buf */
- /* memory allocation routines */
- yajl_alloc_funcs alloc;
-};
-
-yajl_gen
-yajl_gen_alloc(const yajl_gen_config * config,
- const yajl_alloc_funcs * afs)
-{
- return yajl_gen_alloc2(NULL, config, afs, NULL);
-}
-
-yajl_gen
-yajl_gen_alloc2(const yajl_print_t callback,
- const yajl_gen_config * config,
- const yajl_alloc_funcs * afs,
- void * ctx)
-{
- yajl_gen g = NULL;
- yajl_alloc_funcs afsBuffer;
-
- /* first order of business is to set up memory allocation routines */
- if (afs != NULL) {
- if (afs->malloc == NULL || afs->realloc == NULL || afs->free == NULL)
- {
- return NULL;
- }
- } else {
- yajl_set_default_alloc_funcs(&afsBuffer);
- afs = &afsBuffer;
- }
-
- g = (yajl_gen) YA_MALLOC(afs, sizeof(struct yajl_gen_t));
- memset((void *) g, 0, sizeof(struct yajl_gen_t));
- /* copy in pointers to allocation routines */
- memcpy((void *) &(g->alloc), (void *) afs, sizeof(yajl_alloc_funcs));
-
- if (config) {
- g->pretty = config->beautify;
- g->indentString = config->indentString ? config->indentString : " ";
- }
-
- if (callback) {
- g->print = callback;
- g->ctx = ctx;
- } else {
- g->print = (yajl_print_t)&yajl_buf_append;
- g->ctx = yajl_buf_alloc(&(g->alloc));
- }
-
- return g;
-}
-
-void
-yajl_gen_free(yajl_gen g)
-{
- if (g->print == (yajl_print_t)&yajl_buf_append) yajl_buf_free((yajl_buf)g->ctx);
- YA_FREE(&(g->alloc), g);
-}
-
-#define INSERT_SEP \
- if (g->state[g->depth] == yajl_gen_map_key || \
- g->state[g->depth] == yajl_gen_in_array) { \
- g->print(g->ctx, ",", 1); \
- if (g->pretty) g->print(g->ctx, "\n", 1); \
- } else if (g->state[g->depth] == yajl_gen_map_val) { \
- g->print(g->ctx, ":", 1); \
- if (g->pretty) g->print(g->ctx, " ", 1); \
- }
-
-#define INSERT_WHITESPACE \
- if (g->pretty) { \
- if (g->state[g->depth] != yajl_gen_map_val) { \
- unsigned int _i; \
- for (_i=0;_i<g->depth;_i++) \
- g->print(g->ctx, g->indentString, \
- strlen(g->indentString)); \
- } \
- }
-
-#define ENSURE_NOT_KEY \
- if (g->state[g->depth] == yajl_gen_map_key) { \
- return yajl_gen_keys_must_be_strings; \
- } \
-
-/* check that we're not complete, or in error state. in a valid state
- * to be generating */
-#define ENSURE_VALID_STATE \
- if (g->state[g->depth] == yajl_gen_error) { \
- return yajl_gen_in_error_state;\
- } else if (g->state[g->depth] == yajl_gen_complete) { \
- return yajl_gen_generation_complete; \
- }
-
-#define INCREMENT_DEPTH \
- if (++(g->depth) >= YAJL_MAX_DEPTH) return yajl_max_depth_exceeded;
-
-#define APPENDED_ATOM \
- switch (g->state[g->depth]) { \
- case yajl_gen_start: \
- g->state[g->depth] = yajl_gen_complete; \
- break; \
- case yajl_gen_map_start: \
- case yajl_gen_map_key: \
- g->state[g->depth] = yajl_gen_map_val; \
- break; \
- case yajl_gen_array_start: \
- g->state[g->depth] = yajl_gen_in_array; \
- break; \
- case yajl_gen_map_val: \
- g->state[g->depth] = yajl_gen_map_key; \
- break; \
- default: \
- break; \
- } \
-
-#define FINAL_NEWLINE \
- if (g->pretty && g->state[g->depth] == yajl_gen_complete) \
- g->print(g->ctx, "\n", 1);
-
-yajl_gen_status
-yajl_gen_integer(yajl_gen g, long int number)
-{
- char i[32];
- ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE;
- sprintf(i, "%ld", number);
- g->print(g->ctx, i, strlen(i));
- APPENDED_ATOM;
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
-#include <float.h>
-#define isnan _isnan
-#define isinf !_finite
-#endif
-
-yajl_gen_status
-yajl_gen_double(yajl_gen g, double number)
-{
- char i[32];
- ENSURE_VALID_STATE; ENSURE_NOT_KEY;
- if (isnan(number) || isinf(number)) return yajl_gen_invalid_number;
- INSERT_SEP; INSERT_WHITESPACE;
- sprintf(i, "%g", number);
- g->print(g->ctx, i, strlen(i));
- APPENDED_ATOM;
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_number(yajl_gen g, const char * s, unsigned int l)
-{
- ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE;
- g->print(g->ctx, s, l);
- APPENDED_ATOM;
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_string(yajl_gen g, const unsigned char * str,
- unsigned int len)
-{
- ENSURE_VALID_STATE; INSERT_SEP; INSERT_WHITESPACE;
- g->print(g->ctx, "\"", 1);
- yajl_string_encode2(g->print, g->ctx, str, len);
- g->print(g->ctx, "\"", 1);
- APPENDED_ATOM;
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_null(yajl_gen g)
-{
- ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE;
- g->print(g->ctx, "null", strlen("null"));
- APPENDED_ATOM;
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_bool(yajl_gen g, int boolean)
-{
- const char * val = boolean ? "true" : "false";
-
- ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE;
- g->print(g->ctx, val, strlen(val));
- APPENDED_ATOM;
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_map_open(yajl_gen g)
-{
- ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE;
- INCREMENT_DEPTH;
-
- g->state[g->depth] = yajl_gen_map_start;
- g->print(g->ctx, "{", 1);
- if (g->pretty) g->print(g->ctx, "\n", 1);
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_map_close(yajl_gen g)
-{
- ENSURE_VALID_STATE;
- (g->depth)--;
- if (g->pretty) g->print(g->ctx, "\n", 1);
- APPENDED_ATOM;
- INSERT_WHITESPACE;
- g->print(g->ctx, "}", 1);
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_array_open(yajl_gen g)
-{
- ENSURE_VALID_STATE; ENSURE_NOT_KEY; INSERT_SEP; INSERT_WHITESPACE;
- INCREMENT_DEPTH;
- g->state[g->depth] = yajl_gen_array_start;
- g->print(g->ctx, "[", 1);
- if (g->pretty) g->print(g->ctx, "\n", 1);
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_array_close(yajl_gen g)
-{
- ENSURE_VALID_STATE;
- if (g->pretty) g->print(g->ctx, "\n", 1);
- (g->depth)--;
- APPENDED_ATOM;
- INSERT_WHITESPACE;
- g->print(g->ctx, "]", 1);
- FINAL_NEWLINE;
- return yajl_gen_status_ok;
-}
-
-yajl_gen_status
-yajl_gen_get_buf(yajl_gen g, const unsigned char ** buf,
- unsigned int * len)
-{
- if (g->print != (yajl_print_t)&yajl_buf_append) return yajl_gen_no_buf;
- *buf = yajl_buf_data((yajl_buf)g->ctx);
- *len = yajl_buf_len((yajl_buf)g->ctx);
- return yajl_gen_status_ok;
-}
-
-void
-yajl_gen_clear(yajl_gen g)
-{
- if (g->print == (yajl_print_t)&yajl_buf_append) yajl_buf_clear((yajl_buf)g->ctx);
-}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_gen.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_gen.h b/src/ejson/c_src/yajl/yajl_gen.h
deleted file mode 100644
index 97c2042..0000000
--- a/src/ejson/c_src/yajl/yajl_gen.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-/**
- * \file yajl_gen.h
- * Interface to YAJL's JSON generation facilities.
- */
-
-#include "yajl_common.h"
-
-#ifndef __YAJL_GEN_H__
-#define __YAJL_GEN_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
- /** generator status codes */
- typedef enum {
- /** no error */
- yajl_gen_status_ok = 0,
- /** at a point where a map key is generated, a function other than
- * yajl_gen_string was called */
- yajl_gen_keys_must_be_strings,
- /** YAJL's maximum generation depth was exceeded. see
- * YAJL_MAX_DEPTH */
- yajl_max_depth_exceeded,
- /** A generator function (yajl_gen_XXX) was called while in an error
- * state */
- yajl_gen_in_error_state,
- /** A complete JSON document has been generated */
- yajl_gen_generation_complete,
- /** yajl_gen_double was passed an invalid floating point value
- * (infinity or NaN). */
- yajl_gen_invalid_number,
- /** A print callback was passed in, so there is no internal
- * buffer to get from */
- yajl_gen_no_buf
- } yajl_gen_status;
-
- /** an opaque handle to a generator */
- typedef struct yajl_gen_t * yajl_gen;
-
- /** a callback used for "printing" the results. */
- typedef void (*yajl_print_t)(void * ctx,
- const char * str,
- unsigned int len);
-
- /** configuration structure for the generator */
- typedef struct {
- /** generate indented (beautiful) output */
- unsigned int beautify;
- /** an opportunity to define an indent string. such as \\t or
- * some number of spaces. default is four spaces ' '. This
- * member is only relevant when beautify is true */
- const char * indentString;
- } yajl_gen_config;
-
- /** allocate a generator handle
- * \param config a pointer to a structure containing parameters which
- * configure the behavior of the json generator
- * \param allocFuncs an optional pointer to a structure which allows
- * the client to overide the memory allocation
- * used by yajl. May be NULL, in which case
- * malloc/free/realloc will be used.
- *
- * \returns an allocated handle on success, NULL on failure (bad params)
- */
- YAJL_API yajl_gen yajl_gen_alloc(const yajl_gen_config * config,
- const yajl_alloc_funcs * allocFuncs);
-
- /** allocate a generator handle that will print to the specified
- * callback rather than storing the results in an internal buffer.
- * \param callback a pointer to a printer function. May be NULL
- * in which case, the results will be store in an
- * internal buffer.
- * \param config a pointer to a structure containing parameters
- * which configure the behavior of the json
- * generator.
- * \param allocFuncs an optional pointer to a structure which allows
- * the client to overide the memory allocation
- * used by yajl. May be NULL, in which case
- * malloc/free/realloc will be used.
- * \param ctx a context pointer that will be passed to the
- * printer callback.
- *
- * \returns an allocated handle on success, NULL on failure (bad params)
- */
- YAJL_API yajl_gen yajl_gen_alloc2(const yajl_print_t callback,
- const yajl_gen_config * config,
- const yajl_alloc_funcs * allocFuncs,
- void * ctx);
-
- /** free a generator handle */
- YAJL_API void yajl_gen_free(yajl_gen handle);
-
- YAJL_API yajl_gen_status yajl_gen_integer(yajl_gen hand, long int number);
- /** generate a floating point number. number may not be infinity or
- * NaN, as these have no representation in JSON. In these cases the
- * generator will return 'yajl_gen_invalid_number' */
- YAJL_API yajl_gen_status yajl_gen_double(yajl_gen hand, double number);
- YAJL_API yajl_gen_status yajl_gen_number(yajl_gen hand,
- const char * num,
- unsigned int len);
- YAJL_API yajl_gen_status yajl_gen_string(yajl_gen hand,
- const unsigned char * str,
- unsigned int len);
- YAJL_API yajl_gen_status yajl_gen_null(yajl_gen hand);
- YAJL_API yajl_gen_status yajl_gen_bool(yajl_gen hand, int boolean);
- YAJL_API yajl_gen_status yajl_gen_map_open(yajl_gen hand);
- YAJL_API yajl_gen_status yajl_gen_map_close(yajl_gen hand);
- YAJL_API yajl_gen_status yajl_gen_array_open(yajl_gen hand);
- YAJL_API yajl_gen_status yajl_gen_array_close(yajl_gen hand);
-
- /** access the null terminated generator buffer. If incrementally
- * outputing JSON, one should call yajl_gen_clear to clear the
- * buffer. This allows stream generation. */
- YAJL_API yajl_gen_status yajl_gen_get_buf(yajl_gen hand,
- const unsigned char ** buf,
- unsigned int * len);
-
- /** clear yajl's output buffer, but maintain all internal generation
- * state. This function will not "reset" the generator state, and is
- * intended to enable incremental JSON outputing. */
- YAJL_API void yajl_gen_clear(yajl_gen hand);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_lex.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_lex.c b/src/ejson/c_src/yajl/yajl_lex.c
deleted file mode 100644
index 11e5f7b..0000000
--- a/src/ejson/c_src/yajl/yajl_lex.c
+++ /dev/null
@@ -1,737 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "yajl_lex.h"
-#include "yajl_buf.h"
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <assert.h>
-#include <string.h>
-
-#ifdef YAJL_LEXER_DEBUG
-static const char *
-tokToStr(yajl_tok tok)
-{
- switch (tok) {
- case yajl_tok_bool: return "bool";
- case yajl_tok_colon: return "colon";
- case yajl_tok_comma: return "comma";
- case yajl_tok_eof: return "eof";
- case yajl_tok_error: return "error";
- case yajl_tok_left_brace: return "brace";
- case yajl_tok_left_bracket: return "bracket";
- case yajl_tok_null: return "null";
- case yajl_tok_integer: return "integer";
- case yajl_tok_double: return "double";
- case yajl_tok_right_brace: return "brace";
- case yajl_tok_right_bracket: return "bracket";
- case yajl_tok_string: return "string";
- case yajl_tok_string_with_escapes: return "string_with_escapes";
- }
- return "unknown";
-}
-#endif
-
-/* Impact of the stream parsing feature on the lexer:
- *
- * YAJL support stream parsing. That is, the ability to parse the first
- * bits of a chunk of JSON before the last bits are available (still on
- * the network or disk). This makes the lexer more complex. The
- * responsibility of the lexer is to handle transparently the case where
- * a chunk boundary falls in the middle of a token. This is
- * accomplished is via a buffer and a character reading abstraction.
- *
- * Overview of implementation
- *
- * When we lex to end of input string before end of token is hit, we
- * copy all of the input text composing the token into our lexBuf.
- *
- * Every time we read a character, we do so through the readChar function.
- * readChar's responsibility is to handle pulling all chars from the buffer
- * before pulling chars from input text
- */
-
-struct yajl_lexer_t {
- /* the overal line and char offset into the data */
- unsigned int lineOff;
- unsigned int charOff;
-
- /* error */
- yajl_lex_error error;
-
- /* a input buffer to handle the case where a token is spread over
- * multiple chunks */
- yajl_buf buf;
-
- /* in the case where we have data in the lexBuf, bufOff holds
- * the current offset into the lexBuf. */
- unsigned int bufOff;
-
- /* are we using the lex buf? */
- unsigned int bufInUse;
-
- /* shall we allow comments? */
- unsigned int allowComments;
-
- /* shall we validate utf8 inside strings? */
- unsigned int validateUTF8;
-
- yajl_alloc_funcs * alloc;
-};
-
-#define readChar(lxr, txt, off) \
- (((lxr)->bufInUse && yajl_buf_len((lxr)->buf) && lxr->bufOff < yajl_buf_len((lxr)->buf)) ? \
- (*((const unsigned char *) yajl_buf_data((lxr)->buf) + ((lxr)->bufOff)++)) : \
- ((txt)[(*(off))++]))
-
-#define unreadChar(lxr, off) ((*(off) > 0) ? (*(off))-- : ((lxr)->bufOff--))
-
-yajl_lexer
-yajl_lex_alloc(yajl_alloc_funcs * alloc,
- unsigned int allowComments, unsigned int validateUTF8)
-{
- yajl_lexer lxr = (yajl_lexer) YA_MALLOC(alloc, sizeof(struct yajl_lexer_t));
- memset((void *) lxr, 0, sizeof(struct yajl_lexer_t));
- lxr->buf = yajl_buf_alloc(alloc);
- lxr->allowComments = allowComments;
- lxr->validateUTF8 = validateUTF8;
- lxr->alloc = alloc;
- return lxr;
-}
-
-void
-yajl_lex_free(yajl_lexer lxr)
-{
- yajl_buf_free(lxr->buf);
- YA_FREE(lxr->alloc, lxr);
- return;
-}
-
-/* a lookup table which lets us quickly determine three things:
- * VEC - valid escaped conrol char
- * IJC - invalid json char
- * VHC - valid hex char
- * note. the solidus '/' may be escaped or not.
- * note. the
- */
-#define VEC 1
-#define IJC 2
-#define VHC 4
-static const char charLookupTable[256] =
-{
-/*00*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC ,
-/*08*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC ,
-/*10*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC ,
-/*18*/ IJC , IJC , IJC , IJC , IJC , IJC , IJC , IJC ,
-
-/*20*/ 0 , 0 , VEC|IJC, 0 , 0 , 0 , 0 , 0 ,
-/*28*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , VEC ,
-/*30*/ VHC , VHC , VHC , VHC , VHC , VHC , VHC , VHC ,
-/*38*/ VHC , VHC , 0 , 0 , 0 , 0 , 0 , 0 ,
-
-/*40*/ 0 , VHC , VHC , VHC , VHC , VHC , VHC , 0 ,
-/*48*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
-/*50*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
-/*58*/ 0 , 0 , 0 , 0 , VEC|IJC, 0 , 0 , 0 ,
-
-/*60*/ 0 , VHC , VEC|VHC, VHC , VHC , VHC , VEC|VHC, 0 ,
-/*68*/ 0 , 0 , 0 , 0 , 0 , 0 , VEC , 0 ,
-/*70*/ 0 , 0 , VEC , 0 , VEC , 0 , 0 , 0 ,
-/*78*/ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
-
-/* include these so we don't have to always check the range of the char */
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
-
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
-
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
-
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
- 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
-};
-
-/** process a variable length utf8 encoded codepoint.
- *
- * returns:
- * yajl_tok_string - if valid utf8 char was parsed and offset was
- * advanced
- * yajl_tok_eof - if end of input was hit before validation could
- * complete
- * yajl_tok_error - if invalid utf8 was encountered
- *
- * NOTE: on error the offset will point to the first char of the
- * invalid utf8 */
-#define UTF8_CHECK_EOF if (*offset >= jsonTextLen) { return yajl_tok_eof; }
-
-static yajl_tok
-yajl_lex_utf8_char(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int * offset,
- unsigned char curChar)
-{
- if (curChar <= 0x7f) {
- /* single byte */
- return yajl_tok_string;
- } else if ((curChar >> 5) == 0x6) {
- /* two byte */
- UTF8_CHECK_EOF;
- curChar = readChar(lexer, jsonText, offset);
- if ((curChar >> 6) == 0x2) return yajl_tok_string;
- } else if ((curChar >> 4) == 0x0e) {
- /* three byte */
- UTF8_CHECK_EOF;
- curChar = readChar(lexer, jsonText, offset);
- if ((curChar >> 6) == 0x2) {
- UTF8_CHECK_EOF;
- curChar = readChar(lexer, jsonText, offset);
- if ((curChar >> 6) == 0x2) return yajl_tok_string;
- }
- } else if ((curChar >> 3) == 0x1e) {
- /* four byte */
- UTF8_CHECK_EOF;
- curChar = readChar(lexer, jsonText, offset);
- if ((curChar >> 6) == 0x2) {
- UTF8_CHECK_EOF;
- curChar = readChar(lexer, jsonText, offset);
- if ((curChar >> 6) == 0x2) {
- UTF8_CHECK_EOF;
- curChar = readChar(lexer, jsonText, offset);
- if ((curChar >> 6) == 0x2) return yajl_tok_string;
- }
- }
- }
-
- return yajl_tok_error;
-}
-
-/* lex a string. input is the lexer, pointer to beginning of
- * json text, and start of string (offset).
- * a token is returned which has the following meanings:
- * yajl_tok_string: lex of string was successful. offset points to
- * terminating '"'.
- * yajl_tok_eof: end of text was encountered before we could complete
- * the lex.
- * yajl_tok_error: embedded in the string were unallowable chars. offset
- * points to the offending char
- */
-#define STR_CHECK_EOF \
-if (*offset >= jsonTextLen) { \
- tok = yajl_tok_eof; \
- goto finish_string_lex; \
-}
-
-static yajl_tok
-yajl_lex_string(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int * offset)
-{
- yajl_tok tok = yajl_tok_error;
- int hasEscapes = 0;
-
- for (;;) {
- unsigned char curChar;
-
- STR_CHECK_EOF;
-
- curChar = readChar(lexer, jsonText, offset);
-
- /* quote terminates */
- if (curChar == '"') {
- tok = yajl_tok_string;
- break;
- }
- /* backslash escapes a set of control chars, */
- else if (curChar == '\\') {
- hasEscapes = 1;
- STR_CHECK_EOF;
-
- /* special case \u */
- curChar = readChar(lexer, jsonText, offset);
- if (curChar == 'u') {
- unsigned int i = 0;
-
- for (i=0;i<4;i++) {
- STR_CHECK_EOF;
- curChar = readChar(lexer, jsonText, offset);
- if (!(charLookupTable[curChar] & VHC)) {
- /* back up to offending char */
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_string_invalid_hex_char;
- goto finish_string_lex;
- }
- }
- } else if (!(charLookupTable[curChar] & VEC)) {
- /* back up to offending char */
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_string_invalid_escaped_char;
- goto finish_string_lex;
- }
- }
- /* when not validating UTF8 it's a simple table lookup to determine
- * if the present character is invalid */
- else if(charLookupTable[curChar] & IJC) {
- /* back up to offending char */
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_string_invalid_json_char;
- goto finish_string_lex;
- }
- /* when in validate UTF8 mode we need to do some extra work */
- else if (lexer->validateUTF8) {
- yajl_tok t = yajl_lex_utf8_char(lexer, jsonText, jsonTextLen,
- offset, curChar);
-
- if (t == yajl_tok_eof) {
- tok = yajl_tok_eof;
- goto finish_string_lex;
- } else if (t == yajl_tok_error) {
- lexer->error = yajl_lex_string_invalid_utf8;
- goto finish_string_lex;
- }
- }
- /* accept it, and move on */
- }
- finish_string_lex:
- /* tell our buddy, the parser, wether he needs to process this string
- * again */
- if (hasEscapes && tok == yajl_tok_string) {
- tok = yajl_tok_string_with_escapes;
- }
-
- return tok;
-}
-
-#define RETURN_IF_EOF if (*offset >= jsonTextLen) return yajl_tok_eof;
-
-static yajl_tok
-yajl_lex_number(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int * offset)
-{
- /** XXX: numbers are the only entities in json that we must lex
- * _beyond_ in order to know that they are complete. There
- * is an ambiguous case for integers at EOF. */
-
- unsigned char c;
-
- yajl_tok tok = yajl_tok_integer;
-
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
-
- /* optional leading minus */
- if (c == '-') {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- }
-
- /* a single zero, or a series of integers */
- if (c == '0') {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- } else if (c >= '1' && c <= '9') {
- do {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- } while (c >= '0' && c <= '9');
- } else {
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_missing_integer_after_minus;
- return yajl_tok_error;
- }
-
- /* optional fraction (indicates this is floating point) */
- if (c == '.') {
- int numRd = 0;
-
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
-
- while (c >= '0' && c <= '9') {
- numRd++;
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- }
-
- if (!numRd) {
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_missing_integer_after_decimal;
- return yajl_tok_error;
- }
- tok = yajl_tok_double;
- }
-
- /* optional exponent (indicates this is floating point) */
- if (c == 'e' || c == 'E') {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
-
- /* optional sign */
- if (c == '+' || c == '-') {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- }
-
- if (c >= '0' && c <= '9') {
- do {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- } while (c >= '0' && c <= '9');
- } else {
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_missing_integer_after_exponent;
- return yajl_tok_error;
- }
- tok = yajl_tok_double;
- }
-
- /* we always go "one too far" */
- unreadChar(lexer, offset);
-
- return tok;
-}
-
-static yajl_tok
-yajl_lex_comment(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int * offset)
-{
- unsigned char c;
-
- yajl_tok tok = yajl_tok_comment;
-
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
-
- /* either slash or star expected */
- if (c == '/') {
- /* now we throw away until end of line */
- do {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- } while (c != '\n');
- } else if (c == '*') {
- /* now we throw away until end of comment */
- for (;;) {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- if (c == '*') {
- RETURN_IF_EOF;
- c = readChar(lexer, jsonText, offset);
- if (c == '/') {
- break;
- } else {
- unreadChar(lexer, offset);
- }
- }
- }
- } else {
- lexer->error = yajl_lex_invalid_char;
- tok = yajl_tok_error;
- }
-
- return tok;
-}
-
-yajl_tok
-yajl_lex_lex(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int * offset,
- const unsigned char ** outBuf, unsigned int * outLen)
-{
- yajl_tok tok = yajl_tok_error;
- unsigned char c;
- unsigned int startOffset = *offset;
-
- *outBuf = NULL;
- *outLen = 0;
-
- for (;;) {
- assert(*offset <= jsonTextLen);
-
- if (*offset >= jsonTextLen) {
- tok = yajl_tok_eof;
- goto lexed;
- }
-
- c = readChar(lexer, jsonText, offset);
-
- switch (c) {
- case '{':
- tok = yajl_tok_left_bracket;
- goto lexed;
- case '}':
- tok = yajl_tok_right_bracket;
- goto lexed;
- case '[':
- tok = yajl_tok_left_brace;
- goto lexed;
- case ']':
- tok = yajl_tok_right_brace;
- goto lexed;
- case ',':
- tok = yajl_tok_comma;
- goto lexed;
- case ':':
- tok = yajl_tok_colon;
- goto lexed;
- case '\t': case '\n': case '\v': case '\f': case '\r': case ' ':
- startOffset++;
- break;
- case 't': {
- const char * want = "rue";
- do {
- if (*offset >= jsonTextLen) {
- tok = yajl_tok_eof;
- goto lexed;
- }
- c = readChar(lexer, jsonText, offset);
- if (c != *want) {
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_invalid_string;
- tok = yajl_tok_error;
- goto lexed;
- }
- } while (*(++want));
- tok = yajl_tok_bool;
- goto lexed;
- }
- case 'f': {
- const char * want = "alse";
- do {
- if (*offset >= jsonTextLen) {
- tok = yajl_tok_eof;
- goto lexed;
- }
- c = readChar(lexer, jsonText, offset);
- if (c != *want) {
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_invalid_string;
- tok = yajl_tok_error;
- goto lexed;
- }
- } while (*(++want));
- tok = yajl_tok_bool;
- goto lexed;
- }
- case 'n': {
- const char * want = "ull";
- do {
- if (*offset >= jsonTextLen) {
- tok = yajl_tok_eof;
- goto lexed;
- }
- c = readChar(lexer, jsonText, offset);
- if (c != *want) {
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_invalid_string;
- tok = yajl_tok_error;
- goto lexed;
- }
- } while (*(++want));
- tok = yajl_tok_null;
- goto lexed;
- }
- case '"': {
- tok = yajl_lex_string(lexer, (const unsigned char *) jsonText,
- jsonTextLen, offset);
- goto lexed;
- }
- case '-':
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9': {
- /* integer parsing wants to start from the beginning */
- unreadChar(lexer, offset);
- tok = yajl_lex_number(lexer, (const unsigned char *) jsonText,
- jsonTextLen, offset);
- goto lexed;
- }
- case '/':
- /* hey, look, a probable comment! If comments are disabled
- * it's an error. */
- if (!lexer->allowComments) {
- unreadChar(lexer, offset);
- lexer->error = yajl_lex_unallowed_comment;
- tok = yajl_tok_error;
- goto lexed;
- }
- /* if comments are enabled, then we should try to lex
- * the thing. possible outcomes are
- * - successful lex (tok_comment, which means continue),
- * - malformed comment opening (slash not followed by
- * '*' or '/') (tok_error)
- * - eof hit. (tok_eof) */
- tok = yajl_lex_comment(lexer, (const unsigned char *) jsonText,
- jsonTextLen, offset);
- if (tok == yajl_tok_comment) {
- /* "error" is silly, but that's the initial
- * state of tok. guilty until proven innocent. */
- tok = yajl_tok_error;
- yajl_buf_clear(lexer->buf);
- lexer->bufInUse = 0;
- startOffset = *offset;
- break;
- }
- /* hit error or eof, bail */
- goto lexed;
- default:
- lexer->error = yajl_lex_invalid_char;
- tok = yajl_tok_error;
- goto lexed;
- }
- }
-
-
- lexed:
- /* need to append to buffer if the buffer is in use or
- * if it's an EOF token */
- if (tok == yajl_tok_eof || lexer->bufInUse) {
- if (!lexer->bufInUse) yajl_buf_clear(lexer->buf);
- lexer->bufInUse = 1;
- yajl_buf_append(lexer->buf, jsonText + startOffset, *offset - startOffset);
- lexer->bufOff = 0;
-
- if (tok != yajl_tok_eof) {
- *outBuf = yajl_buf_data(lexer->buf);
- *outLen = yajl_buf_len(lexer->buf);
- lexer->bufInUse = 0;
- }
- } else if (tok != yajl_tok_error) {
- *outBuf = jsonText + startOffset;
- *outLen = *offset - startOffset;
- }
-
- /* special case for strings. skip the quotes. */
- if (tok == yajl_tok_string || tok == yajl_tok_string_with_escapes)
- {
- assert(*outLen >= 2);
- (*outBuf)++;
- *outLen -= 2;
- }
-
-
-#ifdef YAJL_LEXER_DEBUG
- if (tok == yajl_tok_error) {
- printf("lexical error: %s\n",
- yajl_lex_error_to_string(yajl_lex_get_error(lexer)));
- } else if (tok == yajl_tok_eof) {
- printf("EOF hit\n");
- } else {
- printf("lexed %s: '", tokToStr(tok));
- fwrite(*outBuf, 1, *outLen, stdout);
- printf("'\n");
- }
-#endif
-
- return tok;
-}
-
-const char *
-yajl_lex_error_to_string(yajl_lex_error error)
-{
- switch (error) {
- case yajl_lex_e_ok:
- return "ok, no error";
- case yajl_lex_string_invalid_utf8:
- return "invalid bytes in UTF8 string.";
- case yajl_lex_string_invalid_escaped_char:
- return "inside a string, '\\' occurs before a character "
- "which it may not.";
- case yajl_lex_string_invalid_json_char:
- return "invalid character inside string.";
- case yajl_lex_string_invalid_hex_char:
- return "invalid (non-hex) character occurs after '\\u' inside "
- "string.";
- case yajl_lex_invalid_char:
- return "invalid char in json text.";
- case yajl_lex_invalid_string:
- return "invalid string in json text.";
- case yajl_lex_missing_integer_after_exponent:
- return "malformed number, a digit is required after the exponent.";
- case yajl_lex_missing_integer_after_decimal:
- return "malformed number, a digit is required after the "
- "decimal point.";
- case yajl_lex_missing_integer_after_minus:
- return "malformed number, a digit is required after the "
- "minus sign.";
- case yajl_lex_unallowed_comment:
- return "probable comment found in input text, comments are "
- "not enabled.";
- }
- return "unknown error code";
-}
-
-
-/** allows access to more specific information about the lexical
- * error when yajl_lex_lex returns yajl_tok_error. */
-yajl_lex_error
-yajl_lex_get_error(yajl_lexer lexer)
-{
- if (lexer == NULL) return (yajl_lex_error) -1;
- return lexer->error;
-}
-
-unsigned int yajl_lex_current_line(yajl_lexer lexer)
-{
- return lexer->lineOff;
-}
-
-unsigned int yajl_lex_current_char(yajl_lexer lexer)
-{
- return lexer->charOff;
-}
-
-yajl_tok yajl_lex_peek(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int offset)
-{
- const unsigned char * outBuf;
- unsigned int outLen;
- unsigned int bufLen = yajl_buf_len(lexer->buf);
- unsigned int bufOff = lexer->bufOff;
- unsigned int bufInUse = lexer->bufInUse;
- yajl_tok tok;
-
- tok = yajl_lex_lex(lexer, jsonText, jsonTextLen, &offset,
- &outBuf, &outLen);
-
- lexer->bufOff = bufOff;
- lexer->bufInUse = bufInUse;
- yajl_buf_truncate(lexer->buf, bufLen);
-
- return tok;
-}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_lex.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_lex.h b/src/ejson/c_src/yajl/yajl_lex.h
deleted file mode 100644
index 559e54d..0000000
--- a/src/ejson/c_src/yajl/yajl_lex.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __YAJL_LEX_H__
-#define __YAJL_LEX_H__
-
-#include "yajl_common.h"
-
-typedef enum {
- yajl_tok_bool,
- yajl_tok_colon,
- yajl_tok_comma,
- yajl_tok_eof,
- yajl_tok_error,
- yajl_tok_left_brace,
- yajl_tok_left_bracket,
- yajl_tok_null,
- yajl_tok_right_brace,
- yajl_tok_right_bracket,
-
- /* we differentiate between integers and doubles to allow the
- * parser to interpret the number without re-scanning */
- yajl_tok_integer,
- yajl_tok_double,
-
- /* we differentiate between strings which require further processing,
- * and strings that do not */
- yajl_tok_string,
- yajl_tok_string_with_escapes,
-
- /* comment tokens are not currently returned to the parser, ever */
- yajl_tok_comment
-} yajl_tok;
-
-typedef struct yajl_lexer_t * yajl_lexer;
-
-yajl_lexer yajl_lex_alloc(yajl_alloc_funcs * alloc,
- unsigned int allowComments,
- unsigned int validateUTF8);
-
-void yajl_lex_free(yajl_lexer lexer);
-
-/**
- * run/continue a lex. "offset" is an input/output parameter.
- * It should be initialized to zero for a
- * new chunk of target text, and upon subsetquent calls with the same
- * target text should passed with the value of the previous invocation.
- *
- * the client may be interested in the value of offset when an error is
- * returned from the lexer. This allows the client to render useful
-n * error messages.
- *
- * When you pass the next chunk of data, context should be reinitialized
- * to zero.
- *
- * Finally, the output buffer is usually just a pointer into the jsonText,
- * however in cases where the entity being lexed spans multiple chunks,
- * the lexer will buffer the entity and the data returned will be
- * a pointer into that buffer.
- *
- * This behavior is abstracted from client code except for the performance
- * implications which require that the client choose a reasonable chunk
- * size to get adequate performance.
- */
-yajl_tok yajl_lex_lex(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int * offset,
- const unsigned char ** outBuf, unsigned int * outLen);
-
-/** have a peek at the next token, but don't move the lexer forward */
-yajl_tok yajl_lex_peek(yajl_lexer lexer, const unsigned char * jsonText,
- unsigned int jsonTextLen, unsigned int offset);
-
-
-typedef enum {
- yajl_lex_e_ok = 0,
- yajl_lex_string_invalid_utf8,
- yajl_lex_string_invalid_escaped_char,
- yajl_lex_string_invalid_json_char,
- yajl_lex_string_invalid_hex_char,
- yajl_lex_invalid_char,
- yajl_lex_invalid_string,
- yajl_lex_missing_integer_after_decimal,
- yajl_lex_missing_integer_after_exponent,
- yajl_lex_missing_integer_after_minus,
- yajl_lex_unallowed_comment
-} yajl_lex_error;
-
-const char * yajl_lex_error_to_string(yajl_lex_error error);
-
-/** allows access to more specific information about the lexical
- * error when yajl_lex_lex returns yajl_tok_error. */
-yajl_lex_error yajl_lex_get_error(yajl_lexer lexer);
-
-/** get the current offset into the most recently lexed json string. */
-unsigned int yajl_lex_current_offset(yajl_lexer lexer);
-
-/** get the number of lines lexed by this lexer instance */
-unsigned int yajl_lex_current_line(yajl_lexer lexer);
-
-/** get the number of chars lexed by this lexer instance since the last
- * \n or \r */
-unsigned int yajl_lex_current_char(yajl_lexer lexer);
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_parse.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_parse.h b/src/ejson/c_src/yajl/yajl_parse.h
deleted file mode 100644
index a3dcffc..0000000
--- a/src/ejson/c_src/yajl/yajl_parse.h
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-/**
- * \file yajl_parse.h
- * Interface to YAJL's JSON parsing facilities.
- */
-
-#include "yajl_common.h"
-
-#ifndef __YAJL_PARSE_H__
-#define __YAJL_PARSE_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
- /** error codes returned from this interface */
- typedef enum {
- /** no error was encountered */
- yajl_status_ok,
- /** a client callback returned zero, stopping the parse */
- yajl_status_client_canceled,
- /** The parse cannot yet complete because more json input text
- * is required, call yajl_parse with the next buffer of input text.
- * (pertinent only when stream parsing) */
- yajl_status_insufficient_data,
- /** An error occured during the parse. Call yajl_get_error for
- * more information about the encountered error */
- yajl_status_error
- } yajl_status;
-
- /** attain a human readable, english, string for an error */
- YAJL_API const char * yajl_status_to_string(yajl_status code);
-
- /** an opaque handle to a parser */
- typedef struct yajl_handle_t * yajl_handle;
-
- /** yajl is an event driven parser. this means as json elements are
- * parsed, you are called back to do something with the data. The
- * functions in this table indicate the various events for which
- * you will be called back. Each callback accepts a "context"
- * pointer, this is a void * that is passed into the yajl_parse
- * function which the client code may use to pass around context.
- *
- * All callbacks return an integer. If non-zero, the parse will
- * continue. If zero, the parse will be canceled and
- * yajl_status_client_canceled will be returned from the parse.
- *
- * Note about handling of numbers:
- * yajl will only convert numbers that can be represented in a double
- * or a long int. All other numbers will be passed to the client
- * in string form using the yajl_number callback. Furthermore, if
- * yajl_number is not NULL, it will always be used to return numbers,
- * that is yajl_integer and yajl_double will be ignored. If
- * yajl_number is NULL but one of yajl_integer or yajl_double are
- * defined, parsing of a number larger than is representable
- * in a double or long int will result in a parse error.
- */
- typedef struct {
- int (* yajl_null)(void * ctx);
- int (* yajl_boolean)(void * ctx, int boolVal);
- int (* yajl_integer)(void * ctx, long integerVal);
- int (* yajl_double)(void * ctx, double doubleVal);
- /** A callback which passes the string representation of the number
- * back to the client. Will be used for all numbers when present */
- int (* yajl_number)(void * ctx, const char * numberVal,
- unsigned int numberLen);
-
- /** strings are returned as pointers into the JSON text when,
- * possible, as a result, they are _not_ null padded */
- int (* yajl_string)(void * ctx, const unsigned char * stringVal,
- unsigned int stringLen);
-
- int (* yajl_start_map)(void * ctx);
- int (* yajl_map_key)(void * ctx, const unsigned char * key,
- unsigned int stringLen);
- int (* yajl_end_map)(void * ctx);
-
- int (* yajl_start_array)(void * ctx);
- int (* yajl_end_array)(void * ctx);
- } yajl_callbacks;
-
- /** configuration structure for the generator */
- typedef struct {
- /** if nonzero, javascript style comments will be allowed in
- * the json input, both slash star and slash slash */
- unsigned int allowComments;
- /** if nonzero, invalid UTF8 strings will cause a parse
- * error */
- unsigned int checkUTF8;
- } yajl_parser_config;
-
- /** allocate a parser handle
- * \param callbacks a yajl callbacks structure specifying the
- * functions to call when different JSON entities
- * are encountered in the input text. May be NULL,
- * which is only useful for validation.
- * \param config configuration parameters for the parse.
- * \param ctx a context pointer that will be passed to callbacks.
- */
- YAJL_API yajl_handle yajl_alloc(const yajl_callbacks * callbacks,
- const yajl_parser_config * config,
- const yajl_alloc_funcs * allocFuncs,
- void * ctx);
-
- /** free a parser handle */
- YAJL_API void yajl_free(yajl_handle handle);
-
- /** Parse some json!
- * \param hand - a handle to the json parser allocated with yajl_alloc
- * \param jsonText - a pointer to the UTF8 json text to be parsed
- * \param jsonTextLength - the length, in bytes, of input text
- */
- YAJL_API yajl_status yajl_parse(yajl_handle hand,
- const unsigned char * jsonText,
- unsigned int jsonTextLength);
-
- /** Parse any remaining buffered json.
- * Since yajl is a stream-based parser, without an explicit end of
- * input, yajl sometimes can't decide if content at the end of the
- * stream is valid or not. For example, if "1" has been fed in,
- * yajl can't know whether another digit is next or some character
- * that would terminate the integer token.
- *
- * \param hand - a handle to the json parser allocated with yajl_alloc
- */
- YAJL_API yajl_status yajl_parse_complete(yajl_handle hand);
-
- /** get an error string describing the state of the
- * parse.
- *
- * If verbose is non-zero, the message will include the JSON
- * text where the error occured, along with an arrow pointing to
- * the specific char.
- *
- * \returns A dynamically allocated string will be returned which should
- * be freed with yajl_free_error
- */
- YAJL_API unsigned char * yajl_get_error(yajl_handle hand, int verbose,
- const unsigned char * jsonText,
- unsigned int jsonTextLength);
-
- /**
- * get the amount of data consumed from the last chunk passed to YAJL.
- *
- * In the case of a successful parse this can help you understand if
- * the entire buffer was consumed (which will allow you to handle
- * "junk at end of input".
- *
- * In the event an error is encountered during parsing, this function
- * affords the client a way to get the offset into the most recent
- * chunk where the error occured. 0 will be returned if no error
- * was encountered.
- */
- YAJL_API unsigned int yajl_get_bytes_consumed(yajl_handle hand);
-
- /** free an error returned from yajl_get_error */
- YAJL_API void yajl_free_error(yajl_handle hand, unsigned char * str);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_parser.c
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_parser.c b/src/ejson/c_src/yajl/yajl_parser.c
deleted file mode 100644
index 990c860..0000000
--- a/src/ejson/c_src/yajl/yajl_parser.c
+++ /dev/null
@@ -1,470 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "yajl_lex.h"
-#include "yajl_parser.h"
-#include "yajl_encode.h"
-#include "yajl_bytestack.h"
-
-#include <stdlib.h>
-#include <limits.h>
-#include <errno.h>
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-#include <assert.h>
-#include <math.h>
-
-const char *
-yajl_parser_error_to_string(yajl_parser_error error)
-{
- switch (error) {
- case yajl_parser_e_ok:
- return "ok, no error";
- case yajl_parser_client_cancelled:
- return "client cancelled parse via callback return value";
- case yajl_parser_integer_overflow:
- return "integer overflow";
- case yajl_parser_numeric_overflow:
- return "numeric (floating point) overflow";
- case yajl_parser_invalid_token:
- return "unallowed token at this point in JSON text";
- case yajl_parser_internal_invalid_token:
- return "invalid token, internal error";
- case yajl_parser_key_must_be_string:
- return "invalid object key (must be a string)";
- case yajl_parser_pair_missing_colon:
- return "object key and value must be separated by a colon (':')";
- case yajl_parser_bad_token_after_map_value:
- return "after key and value, inside map, I expect ',' or '}'";
- case yajl_parser_bad_token_after_array_value:
- return "after array element, I expect ',' or ']'";
- }
- return "unknown error code";
-}
-
-
-unsigned char *
-yajl_render_error_string(yajl_handle hand, const unsigned char * jsonText,
- unsigned int jsonTextLen, int verbose)
-{
- unsigned int offset = hand->bytesConsumed;
- unsigned char * str;
- const char * errorType = NULL;
- const char * errorText = NULL;
- char text[72];
- const char * arrow = " (right here) ------^\n";
-
- if (yajl_bs_current(hand->stateStack) == yajl_state_parse_error) {
- errorType = "parse";
- errorText = yajl_parser_error_to_string(hand->parserError);
- } else if (yajl_bs_current(hand->stateStack) == yajl_state_lexical_error) {
- errorType = "lexical";
- errorText = yajl_lex_error_to_string(yajl_lex_get_error(hand->lexer));
- } else {
- errorType = "unknown";
- }
-
- {
- unsigned int memneeded = 0;
- memneeded += strlen(errorType);
- memneeded += strlen(" error");
- if (errorText != NULL) {
- memneeded += strlen(": ");
- memneeded += strlen(errorText);
- }
- str = (unsigned char *) YA_MALLOC(&(hand->alloc), memneeded + 2);
- str[0] = 0;
- strcat((char *) str, errorType);
- strcat((char *) str, " error");
- if (errorText != NULL) {
- strcat((char *) str, ": ");
- strcat((char *) str, errorText);
- }
- strcat((char *) str, "\n");
- }
-
- /* now we append as many spaces as needed to make sure the error
- * falls at char 41, if verbose was specified */
- if (verbose) {
- unsigned int start, end, i;
- unsigned int spacesNeeded;
-
- spacesNeeded = (offset < 30 ? 40 - offset : 10);
- start = (offset >= 30 ? offset - 30 : 0);
- end = (offset + 30 > jsonTextLen ? jsonTextLen : offset + 30);
-
- for (i=0;i<spacesNeeded;i++) text[i] = ' ';
-
- for (;start < end;start++, i++) {
- if (jsonText[start] != '\n' && jsonText[start] != '\r')
- {
- text[i] = jsonText[start];
- }
- else
- {
- text[i] = ' ';
- }
- }
- assert(i <= 71);
- text[i++] = '\n';
- text[i] = 0;
- {
- char * newStr = (char *)
- YA_MALLOC(&(hand->alloc), (strlen((char *) str) +
- strlen((char *) text) +
- strlen(arrow) + 1));
- newStr[0] = 0;
- strcat((char *) newStr, (char *) str);
- strcat((char *) newStr, text);
- strcat((char *) newStr, arrow);
- YA_FREE(&(hand->alloc), str);
- str = (unsigned char *) newStr;
- }
- }
- return str;
-}
-
-/* check for client cancelation */
-#define _CC_CHK(x) \
- if (!(x)) { \
- yajl_bs_set(hand->stateStack, yajl_state_parse_error); \
- hand->parserError = yajl_parser_client_cancelled; \
- return yajl_status_client_canceled; \
- }
-
-
-yajl_status
-yajl_do_parse(yajl_handle hand, const unsigned char * jsonText,
- unsigned int jsonTextLen)
-{
- yajl_tok tok;
- const unsigned char * buf;
- unsigned int bufLen;
- unsigned int * offset = &(hand->bytesConsumed);
-
- *offset = 0;
-
-
- around_again:
- switch (yajl_bs_current(hand->stateStack)) {
- case yajl_state_parse_complete:
- return yajl_status_ok;
- case yajl_state_lexical_error:
- case yajl_state_parse_error:
- return yajl_status_error;
- case yajl_state_start:
- case yajl_state_map_need_val:
- case yajl_state_array_need_val:
- case yajl_state_array_start: {
- /* for arrays and maps, we advance the state for this
- * depth, then push the state of the next depth.
- * If an error occurs during the parsing of the nesting
- * enitity, the state at this level will not matter.
- * a state that needs pushing will be anything other
- * than state_start */
- yajl_state stateToPush = yajl_state_start;
-
- tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
- offset, &buf, &bufLen);
-
- switch (tok) {
- case yajl_tok_eof:
- return yajl_status_insufficient_data;
- case yajl_tok_error:
- yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
- goto around_again;
- case yajl_tok_string:
- if (hand->callbacks && hand->callbacks->yajl_string) {
- _CC_CHK(hand->callbacks->yajl_string(hand->ctx,
- buf, bufLen));
- }
- break;
- case yajl_tok_string_with_escapes:
- if (hand->callbacks && hand->callbacks->yajl_string) {
- yajl_buf_clear(hand->decodeBuf);
- yajl_string_decode(hand->decodeBuf, buf, bufLen);
- _CC_CHK(hand->callbacks->yajl_string(
- hand->ctx, yajl_buf_data(hand->decodeBuf),
- yajl_buf_len(hand->decodeBuf)));
- }
- break;
- case yajl_tok_bool:
- if (hand->callbacks && hand->callbacks->yajl_boolean) {
- _CC_CHK(hand->callbacks->yajl_boolean(hand->ctx,
- *buf == 't'));
- }
- break;
- case yajl_tok_null:
- if (hand->callbacks && hand->callbacks->yajl_null) {
- _CC_CHK(hand->callbacks->yajl_null(hand->ctx));
- }
- break;
- case yajl_tok_left_bracket:
- if (hand->callbacks && hand->callbacks->yajl_start_map) {
- _CC_CHK(hand->callbacks->yajl_start_map(hand->ctx));
- }
- stateToPush = yajl_state_map_start;
- break;
- case yajl_tok_left_brace:
- if (hand->callbacks && hand->callbacks->yajl_start_array) {
- _CC_CHK(hand->callbacks->yajl_start_array(hand->ctx));
- }
- stateToPush = yajl_state_array_start;
- break;
- case yajl_tok_integer:
- /*
- * note. strtol does not respect the length of
- * the lexical token. in a corner case where the
- * lexed number is a integer with a trailing zero,
- * immediately followed by the end of buffer,
- * sscanf could run off into oblivion and cause a
- * crash. for this reason we copy the integer
- * (and doubles), into our parse buffer (the same
- * one used for unescaping strings), before
- * calling strtol. yajl_buf ensures null padding,
- * so we're safe.
- */
- if (hand->callbacks) {
- if (hand->callbacks->yajl_number) {
- _CC_CHK(hand->callbacks->yajl_number(
- hand->ctx,(const char *) buf, bufLen));
- } else if (hand->callbacks->yajl_integer) {
- long int i = 0;
- yajl_buf_clear(hand->decodeBuf);
- yajl_buf_append(hand->decodeBuf, buf, bufLen);
- buf = yajl_buf_data(hand->decodeBuf);
- i = strtol((const char *) buf, NULL, 10);
- if ((i == LONG_MIN || i == LONG_MAX) &&
- errno == ERANGE)
- {
- yajl_bs_set(hand->stateStack,
- yajl_state_parse_error);
- hand->parserError = yajl_parser_integer_overflow;
- /* try to restore error offset */
- if (*offset >= bufLen) *offset -= bufLen;
- else *offset = 0;
- goto around_again;
- }
- _CC_CHK(hand->callbacks->yajl_integer(hand->ctx,
- i));
- }
- }
- break;
- case yajl_tok_double:
- if (hand->callbacks) {
- if (hand->callbacks->yajl_number) {
- _CC_CHK(hand->callbacks->yajl_number(
- hand->ctx, (const char *) buf, bufLen));
- } else if (hand->callbacks->yajl_double) {
- double d = 0.0;
- yajl_buf_clear(hand->decodeBuf);
- yajl_buf_append(hand->decodeBuf, buf, bufLen);
- buf = yajl_buf_data(hand->decodeBuf);
- d = strtod((char *) buf, NULL);
- if ((d == HUGE_VAL || d == -HUGE_VAL) &&
- errno == ERANGE)
- {
- yajl_bs_set(hand->stateStack,
- yajl_state_parse_error);
- hand->parserError = yajl_parser_numeric_overflow;
- /* try to restore error offset */
- if (*offset >= bufLen) *offset -= bufLen;
- else *offset = 0;
- goto around_again;
- }
- _CC_CHK(hand->callbacks->yajl_double(hand->ctx,
- d));
- }
- }
- break;
- case yajl_tok_right_brace: {
- if (yajl_bs_current(hand->stateStack) ==
- yajl_state_array_start)
- {
- if (hand->callbacks &&
- hand->callbacks->yajl_end_array)
- {
- _CC_CHK(hand->callbacks->yajl_end_array(hand->ctx));
- }
- yajl_bs_pop(hand->stateStack);
- goto around_again;
- }
- /* intentional fall-through */
- }
- case yajl_tok_colon:
- case yajl_tok_comma:
- case yajl_tok_right_bracket:
- yajl_bs_set(hand->stateStack, yajl_state_parse_error);
- hand->parserError = yajl_parser_invalid_token;
- goto around_again;
- default:
- yajl_bs_set(hand->stateStack, yajl_state_parse_error);
- hand->parserError = yajl_parser_invalid_token;
- goto around_again;
- }
- /* got a value. transition depends on the state we're in. */
- {
- yajl_state s = yajl_bs_current(hand->stateStack);
- if (s == yajl_state_start) {
- yajl_bs_set(hand->stateStack, yajl_state_parse_complete);
- } else if (s == yajl_state_map_need_val) {
- yajl_bs_set(hand->stateStack, yajl_state_map_got_val);
- } else {
- yajl_bs_set(hand->stateStack, yajl_state_array_got_val);
- }
- }
- if (stateToPush != yajl_state_start) {
- yajl_bs_push(hand->stateStack, stateToPush);
- }
-
- goto around_again;
- }
- case yajl_state_map_start:
- case yajl_state_map_need_key: {
- /* only difference between these two states is that in
- * start '}' is valid, whereas in need_key, we've parsed
- * a comma, and a string key _must_ follow */
- tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
- offset, &buf, &bufLen);
- switch (tok) {
- case yajl_tok_eof:
- return yajl_status_insufficient_data;
- case yajl_tok_error:
- yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
- goto around_again;
- case yajl_tok_string_with_escapes:
- if (hand->callbacks && hand->callbacks->yajl_map_key) {
- yajl_buf_clear(hand->decodeBuf);
- yajl_string_decode(hand->decodeBuf, buf, bufLen);
- buf = yajl_buf_data(hand->decodeBuf);
- bufLen = yajl_buf_len(hand->decodeBuf);
- }
- /* intentional fall-through */
- case yajl_tok_string:
- if (hand->callbacks && hand->callbacks->yajl_map_key) {
- _CC_CHK(hand->callbacks->yajl_map_key(hand->ctx, buf,
- bufLen));
- }
- yajl_bs_set(hand->stateStack, yajl_state_map_sep);
- goto around_again;
- case yajl_tok_right_bracket:
- if (yajl_bs_current(hand->stateStack) ==
- yajl_state_map_start)
- {
- if (hand->callbacks && hand->callbacks->yajl_end_map) {
- _CC_CHK(hand->callbacks->yajl_end_map(hand->ctx));
- }
- yajl_bs_pop(hand->stateStack);
- goto around_again;
- }
- default:
- yajl_bs_set(hand->stateStack, yajl_state_parse_error);
- hand->parserError = yajl_parser_key_must_be_string;
- goto around_again;
- }
- }
- case yajl_state_map_sep: {
- tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
- offset, &buf, &bufLen);
- switch (tok) {
- case yajl_tok_colon:
- yajl_bs_set(hand->stateStack, yajl_state_map_need_val);
- goto around_again;
- case yajl_tok_eof:
- return yajl_status_insufficient_data;
- case yajl_tok_error:
- yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
- goto around_again;
- default:
- yajl_bs_set(hand->stateStack, yajl_state_parse_error);
- hand->parserError = yajl_parser_pair_missing_colon;
- goto around_again;
- }
- }
- case yajl_state_map_got_val: {
- tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
- offset, &buf, &bufLen);
- switch (tok) {
- case yajl_tok_right_bracket:
- if (hand->callbacks && hand->callbacks->yajl_end_map) {
- _CC_CHK(hand->callbacks->yajl_end_map(hand->ctx));
- }
- yajl_bs_pop(hand->stateStack);
- goto around_again;
- case yajl_tok_comma:
- yajl_bs_set(hand->stateStack, yajl_state_map_need_key);
- goto around_again;
- case yajl_tok_eof:
- return yajl_status_insufficient_data;
- case yajl_tok_error:
- yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
- goto around_again;
- default:
- yajl_bs_set(hand->stateStack, yajl_state_parse_error);
- hand->parserError = yajl_parser_bad_token_after_map_value;
- /* try to restore error offset */
- if (*offset >= bufLen) *offset -= bufLen;
- else *offset = 0;
- goto around_again;
- }
- }
- case yajl_state_array_got_val: {
- tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
- offset, &buf, &bufLen);
- switch (tok) {
- case yajl_tok_right_brace:
- if (hand->callbacks && hand->callbacks->yajl_end_array) {
- _CC_CHK(hand->callbacks->yajl_end_array(hand->ctx));
- }
- yajl_bs_pop(hand->stateStack);
- goto around_again;
- case yajl_tok_comma:
- yajl_bs_set(hand->stateStack, yajl_state_array_need_val);
- goto around_again;
- case yajl_tok_eof:
- return yajl_status_insufficient_data;
- case yajl_tok_error:
- yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
- goto around_again;
- default:
- yajl_bs_set(hand->stateStack, yajl_state_parse_error);
- hand->parserError = yajl_parser_bad_token_after_array_value;
- goto around_again;
- }
- }
- }
-
- abort();
- return yajl_status_error;
-}
-
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/c_src/yajl/yajl_parser.h
----------------------------------------------------------------------
diff --git a/src/ejson/c_src/yajl/yajl_parser.h b/src/ejson/c_src/yajl/yajl_parser.h
deleted file mode 100644
index f359b45..0000000
--- a/src/ejson/c_src/yajl/yajl_parser.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright 2010, Lloyd Hilaiel.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. Neither the name of Lloyd Hilaiel nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
- * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __YAJL_PARSER_H__
-#define __YAJL_PARSER_H__
-
-#include "yajl_parse.h"
-#include "yajl_bytestack.h"
-#include "yajl_buf.h"
-#include "yajl_lex.h"
-
-typedef enum {
- yajl_state_start = 0,
- yajl_state_parse_complete,
- yajl_state_parse_error,
- yajl_state_lexical_error,
- yajl_state_map_start,
- yajl_state_map_sep,
- yajl_state_map_need_val,
- yajl_state_map_got_val,
- yajl_state_map_need_key,
- yajl_state_array_start,
- yajl_state_array_got_val,
- yajl_state_array_need_val
-} yajl_state;
-
-typedef enum {
- yajl_parser_e_ok = 0,
- yajl_parser_client_cancelled,
- yajl_parser_integer_overflow,
- yajl_parser_numeric_overflow,
- yajl_parser_invalid_token,
- yajl_parser_internal_invalid_token,
- yajl_parser_key_must_be_string,
- yajl_parser_pair_missing_colon,
- yajl_parser_bad_token_after_map_value,
- yajl_parser_bad_token_after_array_value
-} yajl_parser_error;
-
-struct yajl_handle_t {
- const yajl_callbacks * callbacks;
- void * ctx;
- yajl_lexer lexer;
- yajl_parser_error parserError;
- /* the number of bytes consumed from the last client buffer,
- * in the case of an error this will be an error offset, in the
- * case of an error this can be used as the error offset */
- unsigned int bytesConsumed;
- /* temporary storage for decoded strings */
- yajl_buf decodeBuf;
- /* a stack of states. access with yajl_state_XXX routines */
- yajl_bytestack stateStack;
- /* memory allocation routines */
- yajl_alloc_funcs alloc;
-};
-
-yajl_status
-yajl_do_parse(yajl_handle handle, const unsigned char * jsonText,
- unsigned int jsonTextLen);
-
-unsigned char *
-yajl_render_error_string(yajl_handle hand, const unsigned char * jsonText,
- unsigned int jsonTextLen, int verbose);
-
-
-#endif
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/src/ejson.app.src
----------------------------------------------------------------------
diff --git a/src/ejson/src/ejson.app.src b/src/ejson/src/ejson.app.src
deleted file mode 100644
index 7180b81..0000000
--- a/src/ejson/src/ejson.app.src
+++ /dev/null
@@ -1,9 +0,0 @@
-{application, ejson, [
- {description, "EJSON - decode and encode JSON into/from Erlang terms"},
- {vsn, git},
- {modules, [ejson]},
- {registered, []},
- {applications, [kernel, stdlib]},
- {env, []}
-]}.
-
[02/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/short-doubles.txt
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/short-doubles.txt b/src/jiffy/test/cases/short-doubles.txt
new file mode 100644
index 0000000..e5e60b9
--- /dev/null
+++ b/src/jiffy/test/cases/short-doubles.txt
@@ -0,0 +1,100000 @@
+1.3252057186783201350530603e-106.
+1.6899223998841386493367055e-33.
+1.0077972445720390730768089e+138.
+9.1867519315348420150084539e+98.
+2.3806039266050926162811123e-63.
+4.5919976932520640180577270e-133.
+1.7272067615194015698157467e-111.
+5.5137913707606126062645371e-233.
+3.2990959928362161509020688e+106.
+1.4315689338832699942723483e-149.
+2.1841362436256955784396205e-129.
+2.7845681172104227200000000e+17.
+6.1380231397114677888087326e-101.
+2.6204368415809849050731729e+163.
+1.7091289481331723262072421e+248.
+1.0348922753222980178028204e-132.
+2.6497752476476071150763197e-308.
+7.4822449050560397764297518e+124.
+3.1026387904896850915478513e-296.
+3.0231537206859015977526118e+223.
+4.2924296430489070452237882e+156.
+7.5066627297459170218149505e-172.
+3.9313879893508392414664459e+207.
+2.0394747354404426895631238e-131.
+1.0371609095992628396338671e+68.
+4.1825395055009590456043130e+49.
+8.8906970003163962680840814e+176.
+3.1682120479001465281493074e+27.
+3.3116594354284591857730425e-214.
+5.8270435531819559300172525e+69.
+1.2905525787704977015088061e+159.
+1.2656408067594076914048263e+106.
+1.3566244872012328498948729e-288.
+2.7189207429747740999183962e-107.
+5.4962310232325185587188125e+29.
+1.2039901566595156659979987e-60.
+2.4361855217773568894543135e-04.
+1.0431384611214260049484168e-260.
+2.3080541526474416462282047e-04.
+2.4147405619576335917152168e-103.
+1.6834823230746819719710365e-22.
+8.7080426599052213999982265e+203.
+1.3880272487448827645468711e+106.
+3.6283981275999341881623758e-298.
+1.2965691469567775539200000e+20.
+2.6560940581538802992023386e-148.
+1.5137554749791916790439891e+137.
+1.9939019983446637744028162e-199.
+6.5866443194645517284957075e+76.
+1.4468397671540319106137213e-226.
+6.2743981634636702802989226e-259.
+1.1167753989761870020118527e+42.
+1.5742696534217655244510617e+57.
+6.1830190683754924654362154e+266.
+1.6357186464312246507080816e+53.
+8.7626385386502853568828445e-150.
+1.2782686851947397819540970e-177.
+8.5901443961849337528564932e+250.
+2.6498343354321504725755135e-105.
+1.9578020164117920559234815e-131.
+1.5497642141088722240759558e-123.
+9.1691319521469439820480937e+30.
+3.9046157151871221406982948e-249.
+6.3064007483917435584145024e+136.
+3.1146877595590063968280143e+118.
+1.1407354149089334218097764e+226.
+1.8748608908459399556547457e-33.
+7.7011469944270716098450498e+113.
+1.0708849188837334385389633e-78.
+2.8944690604304663858832854e-249.
+2.6865407799434139442608004e-258.
+8.8414360974336110614156311e-158.
+1.7580203265464267510859745e-40.
+6.9915284536696885330088396e+274.
+2.4993141214540274193423965e-194.
+6.8639377438681806661307185e+102.
+2.2421757386952627812710621e-144.
+5.4469612778255034041278577e+36.
+3.4699675909567793999507957e-42.
+3.5656964266388477887743263e+286.
+1.7214351947097940980141862e-235.
+5.7740510393095364965734792e+293.
+1.0683867728180228303032941e+168.
+7.8417136330884926964837217e+254.
+1.4353998706496625043748034e-145.
+1.4386299828739290835809455e-143.
+2.8752786000759308226406574e+06.
+4.5926340384863042757898849e-111.
+5.7265970248538070500226413e+55.
+5.9786442728733652833279224e+66.
+2.1610430481656253174589602e+64.
+1.3165548307748377288297995e-212.
+2.6807666160328904391718750e-225.
+6.2697618655586380144002860e+173.
+1.1751204576545737366175117e+214.
+3.9941186333645135164260864e+07.
+8.7717014790955747616795566e+279.
+3.2875202783733892752405113e-211.
+1.1451502816849844010621653e-106.
+2.6669985486807822575683670e-180.
+8.3970396132495299351252042e+304.
+7.1585056056422905113411816e+59.
+1.3301611505256969880162151e+223.
+6.3974810337750397518136181e-117.
+2.9014002836541182296833307e-73.
+4.1012657428634783268682669e+252.
+3.3909780920685604278184908e-177.
+2.9832462266190784382086972e+277.
+4.2408967264679168771670036e-220.
+5.6511412945945582648522759e+205.
+3.3971922549971354909761837e-36.
+7.0346265078421031435910822e-290.
+5.9838017187523983194475693e+71.
+8.5944520215508656515553637e-221.
+9.8253671983518666267337231e-26.
+4.9976903291979702696563389e+29.
+1.4981662868141252485847889e-23.
+8.6456899086484619304903297e-208.
+8.0925324193140830925919377e-75.
+1.6679947374739701263842679e-251.
+1.2201596791532746727239656e+58.
+1.5749712412767631889730583e+209.
+1.4725958730903781571358689e+126.
+1.1839979122061201231667441e+198.
+4.7885777022264868428508820e-235.
+1.7672793056482473436836944e+101.
+4.1045125029672000177155657e-94.
+8.8494629544539611950448208e+238.
+4.2572035464283417650401276e-126.
+2.0845392765739245845328976e+64.
+1.0673343360022037066815679e-286.
+8.1458016967241863465387808e-110.
+1.5730426911871395345970039e+224.
+3.2397607690678853408245583e-225.
+3.8503078828071335276527576e+210.
+7.8715148646758174089130261e+68.
+4.2948212304455311869537911e-174.
+5.5987737471607980995008864e+73.
+2.4110773802390139039879055e-08.
+6.0827061913910494875452396e+164.
+2.5679453321965104563373886e+69.
+9.3050261252337594470967564e-162.
+6.0036483954760353105202525e-284.
+4.9008085273929314003182709e+239.
+7.1154848273122389191788161e-302.
+1.3765551283886802237534895e-47.
+1.9947604895103773888671955e+301.
+1.7543955487025116793382849e-242.
+9.1940018232811127944349757e+242.
+8.3226879676322187322903194e+186.
+2.6288951130064901865100714e-22.
+3.6862697189529755927824960e-269.
+2.9934715763669705995337155e+111.
+2.0019772311429112433350107e+45.
+4.0439995860910020123459794e-237.
+1.0056583368560327315803436e+47.
+1.7440064841366835624908004e-269.
+8.8238215144632038603425857e+300.
+3.3957896799542624016579082e-69.
+9.3904761476493451819929495e+118.
+2.9139225283507267794304964e+274.
+4.4089423687311979044201468e+91.
+3.7420283999949003439003602e-13.
+7.6949782844885924222778243e+292.
+2.3291631607680878914834466e+03.
+2.3148026010073740800000000e+17.
+2.0924594697637957933806894e+274.
+1.4775302249571262161984658e-52.
+1.6852886819551390499669317e-137.
+7.1358147922548688364036103e-286.
+3.3640750280940265534133815e-175.
+1.1940149073145245295197018e+55.
+1.3765352886315735453816318e-264.
+5.2180151399660783288863712e+258.
+3.8340371652071558098737002e+62.
+1.6795754942307571200000000e+17.
+3.0011308867511879858156509e+134.
+2.3205070222768115984966479e-244.
+3.9573627874437583596378053e+191.
+4.2010848277248547078450142e-239.
+3.6657561704524470303989042e-277.
+1.6567675466054302072787539e+277.
+4.3002681129545479983449793e-290.
+7.3234034973052321104363563e-239.
+2.3753491948884897000397567e-105.
+4.6393260658001027977636281e+214.
+6.6056349255730775801653708e-29.
+1.3206090017038846169726906e+203.
+5.6212788756490541517070043e+166.
+2.9943470266563074836804375e-182.
+2.9979419023068198522067633e-127.
+2.3613624594416414918440045e-113.
+2.2679340090603675931502780e+182.
+2.5193879420328525830036754e-185.
+8.1693690246447407450728184e+55.
+1.8225253590724578509078175e+60.
+1.0632829755946747626324997e-24.
+9.3565528112577019143757304e+274.
+9.2528769754649527721596127e-29.
+1.4337254461439105295285346e-136.
+1.5675691438267007812500000e+13.
+3.1999783212022610888088857e-125.
+9.4331487981794005751778628e-22.
+1.7791144681413448789681551e-152.
+3.6290147402545625740967630e-192.
+9.1273184870709221328461553e-187.
+7.7204396160415584956468932e-202.
+2.3426246409716591228540274e+217.
+6.0224366743815028025460928e+133.
+9.8104575775120268590987183e-95.
+5.7895514907226678504750269e-22.
+6.5620814525753232128877560e-92.
+4.4805247500091707488232353e+274.
+1.0197729527772740793139200e+23.
+5.3398680403612418059890062e+159.
+4.3907618565429465661115873e+91.
+6.2591978877513264260333927e-09.
+1.1149808193914085915428913e-170.
+1.6938872881912762420833190e+143.
+8.4897938948854400536919754e-198.
+5.7164050671861360729309610e-237.
+1.9643049965985094137304425e+70.
+1.7269543333610141105090324e+65.
+8.4344440984995319202775251e-42.
+1.6956345772669280833734374e+184.
+1.4099601372939799403584370e+221.
+2.2877695154204962822453601e-144.
+9.5378710456576656034651542e-220.
+2.6405977645278990468645084e+65.
+3.8135884544654157609049951e+290.
+1.3864867002913154896034389e-244.
+9.3016111937743540802913357e-66.
+2.7320159386501704296258634e+246.
+1.8730212880140122369636650e-225.
+2.9243114702788914695715846e-25.
+9.1493526734852750992166777e+243.
+1.3706459914872642294577831e-210.
+8.3830900726156487341175765e+92.
+3.6274987391260146465496544e-186.
+5.2527773393499212278957185e+170.
+2.3033053883872619541746901e-170.
+1.0674795856319614536244163e-290.
+3.3075658190529578641434144e+152.
+8.2284368698769321563041121e-212.
+1.7695886122563230043947922e+44.
+1.4948354835673943670787729e+276.
+1.0650165563502843228560019e-44.
+2.0582851275965257560811431e-38.
+1.9657847291383164735904734e-290.
+1.5972980781200403938676589e+231.
+9.0856277731029841064930709e+77.
+1.5332316306800722167923968e+190.
+8.7769785228931220042703224e+125.
+1.2811454655361097989521366e-263.
+1.3196177062668286151385272e-107.
+5.6144145182662648149442701e+76.
+1.0602367830533640635081495e-100.
+5.9569777711915523853361396e+199.
+5.8306951824467266526583336e-297.
+5.2353381655782170863398368e-34.
+2.8667373008924498365651965e+133.
+2.2451044144700913279991520e-73.
+8.9138313911807540000000000e+15.
+7.3949535592016293615199862e-85.
+3.5329273900521720030536020e-194.
+3.4052859735811495393463106e+218.
+5.9554903686026828816938837e+136.
+2.7233637031983152035047798e-112.
+5.7099571744669313056242073e+57.
+6.3124625620363610712578438e+98.
+1.9429933146147794357066926e+257.
+3.6822094159788695577371537e+212.
+1.2008407861188531610962982e-26.
+1.4574601711861583590507507e+08.
+1.4281374532351969938706988e-204.
+3.1297253250876101758688193e+105.
+7.9008614361011299355583218e+96.
+3.3658993920806136719180783e+162.
+2.8148504311867329814200320e+24.
+4.0804444112510600613838829e+53.
+2.5987191656465419749644984e+204.
+1.7755910877244279401132892e-232.
+9.0042891538943494877601996e-306.
+8.2345615000236948497122831e-196.
+9.3941615218173532453345837e+229.
+1.1656022500445791916818334e-71.
+3.8220813638371666128690838e-110.
+1.0221208419415078660416365e+67.
+2.8588958441501509987356350e-242.
+5.8626889367815562354159417e-100.
+5.2520036446576433218736820e-123.
+9.3064612587456103507487921e-73.
+5.3230943658826290287923496e+177.
+1.6405915050260188518496344e-205.
+1.0885349434248826456288872e+245.
+2.6735980089604353478343077e-215.
+3.4029025444239711860366291e-66.
+3.2363908614883664121469106e-06.
+2.8099998301161225331681943e+296.
+6.0888515011957304008215861e+252.
+5.6804892302371442831127980e-16.
+1.2590192242462608366000161e-40.
+5.5696683540652885018545137e-294.
+7.5505577644580230411179316e+131.
+2.0861010975800398498678387e-161.
+3.6281112161146322885224760e+202.
+1.0999837613072358765857653e-43.
+4.8974031643957995891002677e-85.
+1.2641761925335491586373335e-163.
+3.1452261719733290773515577e-104.
+3.4813495175878636276889744e-184.
+3.8880123631253744346385103e-295.
+6.2181315417350826240306514e-11.
+5.3122894656197237843921288e+139.
+2.8051913769853345220045176e+190.
+1.4115591302520511185893589e+134.
+6.6403928137032886081290311e+155.
+2.0510457808167118262306742e-162.
+6.3433821675948999202706142e+74.
+2.1597948310181604671751123e-42.
+4.6087504720802515176509891e-241.
+1.1618031865207346719015627e+274.
+2.2197111805315254517246131e-45.
+8.3306381428188699586711279e-243.
+2.2553814893672579278035822e-16.
+1.1383158867467207544339894e+170.
+1.3179686186941692273348227e-246.
+2.6196445384213365332474316e-68.
+2.5651782433184743402618698e+180.
+1.2411074551472883878915418e+61.
+2.8904479504291041227916980e+79.
+4.0858279177176430880176025e-235.
+5.9182974888171418765253305e+78.
+2.1450652291411297881467874e-147.
+1.7743964420165806202533993e+144.
+2.5755156021775778627804936e-153.
+6.2224624441102606287642360e-246.
+4.1343331894051861984187808e+91.
+4.8977627680081415429002180e+140.
+2.6517668888408229234864253e+47.
+6.0113635388444954089136991e-50.
+2.6516973875067384000617005e+273.
+2.0675046880686599988981001e-57.
+5.7114629942576782722137713e-05.
+9.8732675248275036314113039e-165.
+1.0642492068899332198481196e+54.
+5.9770417558475865820313450e+286.
+5.8299302485204621110832196e-301.
+2.7711436225184635289600000e+21.
+2.7812024034878119597916069e+266.
+1.3844552700007161580704430e-06.
+2.6699752866454406983991632e+281.
+1.2506469925279883953283414e+303.
+2.6901893400805121960909579e+272.
+6.4627928393532497022301168e-141.
+3.7834709694125076962501886e+240.
+8.6165072585899351733564477e-177.
+1.5989766238677316038550755e-54.
+1.1135503750103456439633341e-271.
+1.6786972416304121250633976e+275.
+1.7525993295292375390366030e+279.
+3.3758762009532524254613987e+208.
+1.4308413986092842318730549e+246.
+7.9257020633449467823228672e-81.
+1.0381606967749571745034079e+225.
+1.5584746605051994224423064e+49.
+4.0945071469165036871009261e+40.
+3.4788884492661548190271703e+58.
+3.7913074367570616304874420e+07.
+3.5191680399655924715483530e-202.
+3.7129358676425799207232025e-145.
+2.5157703037259128792042172e-128.
+8.4361337428253461640754818e-283.
+5.1309145165592348765935815e-05.
+5.1753011855212564695675390e-40.
+3.4767813788043530273437500e+11.
+6.0816432888155057705118080e+180.
+3.5096653519759345254698625e+243.
+1.0767456584389425554746499e+247.
+9.2578335248671716780904670e+139.
+2.6741441465878269096324149e-106.
+9.8517230925556538321329031e-22.
+7.6894718816011098807754726e-301.
+2.1625402869387663277873702e-10.
+2.3244327647522847297657903e+52.
+1.6917892719065736328125000e+13.
+5.4748582584446826686681102e+169.
+5.6639088167476574113759232e+25.
+1.1217498477746025908736885e+211.
+2.7075358135717521535737552e+77.
+5.1565256345536258720551924e-211.
+4.4262555033399625527702614e-260.
+4.2291132739164204071617588e-34.
+2.0051867495428615286936252e+75.
+1.6540405537750354036688805e+07.
+2.9131755915711620413416698e+53.
+1.1275970447866644680614918e+42.
+4.9038676046464966730870270e+82.
+1.5362233488231069500277957e-287.
+1.9144107332383576344729005e+300.
+4.8953294810489273431279708e-154.
+4.1323322357955800251957467e-33.
+1.3672863781794655016070163e-92.
+9.0210701764702896466616487e-15.
+4.2779354131733019389495677e-143.
+2.0077236953884845000000000e+15.
+8.2423566843110209102261004e-254.
+2.8374839180324989296644417e-306.
+1.0863088088923758545974858e+163.
+4.5523497487425281342150868e+205.
+4.4953676175959275114010220e+191.
+2.9427451907764411317100499e+196.
+7.6699919703835149888177450e-233.
+4.6580315823938870396129880e-43.
+1.0987556715645650658861781e+167.
+1.0749736425755690766206558e+164.
+6.6173072327145658522127567e-55.
+1.2275185050714253630548086e+135.
+1.6349169464601635913322008e-275.
+1.7123557765453176148355230e+192.
+8.6340136402841409178401118e+210.
+1.5257657045162972398148670e+254.
+2.1029849313517603840000000e+18.
+7.3422818894470990896651583e-298.
+7.5590585943362931937043894e+260.
+2.0775062265271774616558304e+265.
+2.7317592624323236224177115e+286.
+3.1500530495933574608801893e+221.
+5.2513348511282718712686651e+76.
+5.8698124552951402098575871e-10.
+3.4622692588980170173196399e+42.
+2.1523483692190352140652079e+288.
+5.8296731159582415966149785e+208.
+1.0072603220354225080980585e-174.
+1.1603052873949141973225169e+253.
+9.9829243314917017349833156e-275.
+3.0009450290491049713707256e-89.
+1.0723482790406715879224608e-292.
+1.3116758729464698421966677e-60.
+1.4016140692684562252261860e-87.
+5.4552900320945399698737684e-30.
+9.3525469055159624998555744e+198.
+9.4179786632506302945625019e+263.
+1.4843588195359611190683962e-237.
+1.1635872661479794393215193e+282.
+4.2256254816510638733933678e+187.
+2.4722010210174776524740949e-258.
+1.8430713666767045405591597e-25.
+1.0455610956240624028511886e+144.
+9.0973200795416116240149442e+230.
+3.6719417471913218476431960e-07.
+3.5685857666358427655923211e+195.
+2.4135660910273678131343544e-204.
+1.8600057133731834829556152e-235.
+7.1383973908915359804782029e-171.
+2.1968263453344398702544771e-145.
+4.1773408659714710608496485e+96.
+1.3606285459499637370480235e+227.
+1.1131695833405029444762116e-249.
+2.8436207238864485410078671e-25.
+1.3490043849982425419481269e+43.
+1.3965556339529240741856433e-170.
+2.4416458930674931113779563e+182.
+5.7085328486597789457568102e-127.
+3.9004043973976580209665507e-42.
+2.1459742907869920318772900e-186.
+7.6721078672264546434880541e+179.
+1.8605356050124399149137683e-180.
+2.1007649898328759513185104e-74.
+2.1830676446380416412226900e+49.
+7.7873659980474211183867106e-302.
+2.0363650457144260191071724e-52.
+1.4602130467049420652637411e-268.
+8.2008533075077323732900219e+265.
+6.6424869952349991759710481e-301.
+2.2028908070352474416272152e+302.
+3.1491441980797487475288714e-60.
+5.5668717247567810866357979e-117.
+6.8899892084968992753763423e-189.
+8.5320682348894343980086422e-180.
+1.4361615265157197303777671e-221.
+1.6136842514045886098164114e-292.
+2.3816093291014615430004680e-265.
+3.8424346023913397887905975e-106.
+7.3096914491769312269505782e-160.
+2.6397666438556662529826716e-93.
+8.5759619722993585398372397e+82.
+2.0593186136355680553869025e+303.
+1.0535591729634440134931986e-254.
+2.1477493498222501486459717e+223.
+3.9163236424504972536386230e+47.
+1.8152134371209147500000000e+15.
+1.2526281259648992695868324e-132.
+3.6989552989579744473714054e-272.
+6.5256887845227895261971110e-257.
+4.5964313829629227498534429e-278.
+1.0429841874152707104688387e+181.
+2.0308124628577242190245672e-239.
+2.6988491023784264125141484e+27.
+1.0273006801248830660396493e+127.
+6.8422302892959303515504683e+234.
+2.7781086478904628432405088e+257.
+1.0540294975491971825676970e+196.
+8.2205363278578959439779306e-201.
+1.1870205672126785725480075e+205.
+2.1802629531850213577036136e+28.
+1.0899213558935850708356364e+231.
+1.7538817643896664039140824e+184.
+1.9834494884230872482727672e+79.
+3.5013552605346451251663220e-260.
+3.9753904376403247271164286e+282.
+4.4078175690560219995430478e-162.
+2.0366452072486408769899460e-201.
+1.6108437237209144897807353e+285.
+6.2111804455537607764242412e+202.
+3.0950353634665868267001288e-47.
+2.7026690026038819816243130e-22.
+8.1330378627320255854820094e+288.
+3.9659952549629960394018484e+184.
+1.4847762397973917202572001e+287.
+1.2516260097679597892066539e-123.
+9.9377353498016420222350512e-140.
+2.7066423582217504530544856e-192.
+8.6814696082155275320486845e-58.
+2.6218588804914351421686690e-46.
+4.9497276772153642657010513e+164.
+5.9391926068859515214701567e+112.
+4.5004266656065335345684331e-107.
+9.5573892049034581705200907e+155.
+3.0781135923553783384333116e-125.
+5.1064187991350534476470941e+105.
+7.4206483379278181536455996e-37.
+3.5980874425121345261402439e+00.
+4.9214367351217734813690186e+08.
+1.5134354377891934445307617e+178.
+4.1185611809512004678137379e+89.
+1.3684229710921207832608420e-117.
+1.6108611632904279442612960e-01.
+2.0514708066051097962246313e-104.
+4.9975938377417102331852183e-266.
+2.9142870452623561656474546e+105.
+3.1882150336694038830354740e-268.
+2.3450991022645954850696357e+289.
+1.5152297213133222824868731e-223.
+7.4883584824729053530756897e-191.
+1.9353237313133502005786060e-279.
+3.2827790871328487656422950e-228.
+4.3303680025356081035128059e+275.
+3.5237324814143355750832948e-184.
+1.1255976693164556034460525e-264.
+1.5580499262130915131828266e+59.
+5.3284296709467959149704014e-192.
+4.4032853398707042673090972e-140.
+4.7123747347050985801773077e+285.
+2.1333003194917812202048983e-35.
+7.8860049292165095798581481e+43.
+2.2280552673677283278341884e+115.
+3.3736045835999768534321042e+231.
+1.4905366343982321883185586e-261.
+6.8040811677802860736846924e+08.
+4.7592431482429127199712870e+27.
+3.0858007856668262592203302e-214.
+1.0612800803323668476047014e+57.
+5.2208908682067687567609979e+166.
+2.2773701968943883509119626e-187.
+4.2534271988230189242817133e-273.
+5.1988347461953751953351776e+279.
+2.2533006421223974788495242e-130.
+7.5827913439042593009313256e-174.
+4.8857594080063271359544232e-89.
+6.5589626419466284801274014e+00.
+5.1836047088116497525402494e+223.
+6.0148462733850683778722909e-66.
+4.5453580299440796868504536e-239.
+1.6042678753041807220272034e+79.
+3.5958825840309125384339668e-206.
+3.5557143666711580437691260e+147.
+2.0104787891369734702397479e+74.
+4.9768211817455067464099479e+273.
+1.7809278467943286682834726e-262.
+3.1030633069555300933855626e+48.
+7.4014831958371614720000000e+18.
+6.9586250964710515672064245e+159.
+1.9636505292244308000000000e+16.
+7.0744202787192557678600608e-127.
+3.3446140934341212423306616e+187.
+7.5474245079758011278660892e-196.
+6.1803564091497348830232741e+201.
+3.2820127213056162554848726e-80.
+6.0561431829999420770582881e-80.
+4.8661918575977485264043207e+179.
+1.1636030303301013519088073e-14.
+1.7256307622535892404875005e+207.
+4.7270649763859016839236511e-34.
+6.0495517498358452354743042e+203.
+2.3705102570735323609825280e+25.
+8.7978450097147003351772922e+182.
+2.9749173135401334059306322e+71.
+5.7276357269393017287956617e-282.
+1.1302793603695105476493432e+83.
+7.5921402820781118182291821e-159.
+1.6254081055625022066240257e-194.
+8.4226278529053413390753441e-68.
+1.6409077777504151603780459e+199.
+3.2880141509905740528391138e-134.
+1.4105383991895487607372848e-06.
+1.3861607558441971540125073e-222.
+2.3300064307139133030447706e+99.
+2.8231754200179377148982970e+57.
+1.0056248895492101959444525e-28.
+5.4235655420446036959238482e+251.
+6.9275966803491959837414974e-142.
+3.2841114592571477757268143e-35.
+5.0441601892866781580441578e+193.
+3.9429343459095874230251600e+278.
+1.4944465126427461917759781e+249.
+9.0288988951850115439536270e+281.
+9.4137420595313971440929903e+59.
+3.2552503361919121710031985e+132.
+8.0453035852275756522243483e+35.
+3.1326039939940154713594019e+286.
+4.1615911959553047045708418e+299.
+1.7294011234418034838078418e-269.
+8.4558180246379399249395854e+100.
+1.2054774268784735818318992e+50.
+9.2977922877318535208164046e-123.
+5.7374756476823698063127137e-298.
+9.6031584417104526995349068e+207.
+6.3294429628802055619480273e-23.
+8.9026658387256498187147673e+229.
+3.9339105271336171584748218e-278.
+3.6965692930481016029349269e-48.
+2.4118081430191125066064607e-132.
+3.5754963395914710614641004e-107.
+2.1634023919552813973449354e-120.
+2.0029495601737256645110369e-181.
+5.9387611698050335432687774e-91.
+4.7684224147159045229408185e-116.
+1.8069139035182560263087199e+211.
+9.3632020316495968458317338e-58.
+9.0644077243372618631737114e-284.
+3.2152681309691837679890438e+246.
+3.6518335146218788841839550e-98.
+4.4170370059383524465032067e-244.
+5.2576869294174541640323068e-181.
+9.9457708976588919867985982e-154.
+9.6730871331012804954501503e-201.
+4.1992198868871932718756818e+305.
+2.0393912899191427874246777e-75.
+1.3611957738673203008251221e+206.
+6.6879869905497771569554736e+283.
+4.0137184015767043937069475e+228.
+9.7078553929519084935759665e-214.
+1.5620532604527217086125128e-47.
+8.6963226310449810817198527e+131.
+1.9101298103395454976000000e+19.
+2.0324357502070080051734310e+253.
+2.2470365506360581981406671e+263.
+5.5067460447218554751265254e+200.
+3.9961463836622550967338855e+275.
+1.1917788104884457060539452e-46.
+6.7484586515027347965263845e-109.
+7.6825881102077401837652966e+274.
+1.8058171060559254018114212e+300.
+6.8785315046320305723169168e-75.
+8.7734060543049402955618332e+49.
+1.6692309132804079158107768e-02.
+2.8187938589807857862044508e-244.
+6.2656747277698818120365414e-200.
+5.7855084666075759667281332e+228.
+6.6472356215367193922787588e+201.
+2.8786441537235603681273049e+154.
+2.7016902463684271037839650e+229.
+5.0396113427444918577079311e-111.
+7.1817209373229604726409811e+86.
+8.3108003158133969260144281e+85.
+5.7455133833488578752349988e+112.
+7.6844923260261058198799070e+223.
+1.1387720646996824535836223e+59.
+8.9806469261406009123934768e-304.
+1.0954532193965921776129159e-216.
+3.8236584917552931250000000e+14.
+1.7429282123717299187938238e-272.
+3.0157612538717755805592769e+294.
+9.9654546669667527121576345e-75.
+2.9750053573037065200881067e+146.
+2.5222426596007685690447866e-55.
+7.1436285878658417405727939e-94.
+1.7186910084171140811034415e+79.
+1.4086354841246821414600424e-307.
+4.3974494647591318753065842e-113.
+7.0356348296234220196550914e+135.
+3.4524342942878488259379449e-181.
+1.2875581235989579607019271e-258.
+1.3808161986894217552592896e+25.
+2.0065943485147973017076236e+30.
+2.4825555639633685184883033e-59.
+1.9897649776974680163880072e+189.
+2.7279179234722659837095885e+76.
+3.3923896264508526134184746e-13.
+2.2010647836620163743752765e+285.
+3.3879773183063512484018038e+42.
+2.7214103533527500117623843e-41.
+1.1048134857521495311083989e+93.
+1.4771786287198834025949272e+134.
+1.7556814575234142041425215e+263.
+1.5608494605150308752271094e-103.
+5.0034884046144098626720632e+305.
+2.9481197245916468551352320e+26.
+3.1286845347922742834000513e-53.
+2.7329301014605288305666843e-83.
+4.2811880283797362432734645e+180.
+2.6807038560196646734243935e+127.
+1.3642072207081474550865755e-238.
+5.1236173182082259806609497e-137.
+2.0743654539899040335881089e-129.
+4.0115924376071069844237516e+65.
+1.9644705059867296921351871e-188.
+2.0942348989218174542354036e-168.
+2.7221402419376932249028053e-254.
+2.1227121891912381010529366e+138.
+1.3837940376173655366680014e+65.
+2.0147127312825119431829487e-57.
+1.1255733111190901647945399e+133.
+6.7476048317306985867983868e-254.
+3.5757356546869148948177675e-65.
+5.3476709588039491298613803e+103.
+3.1596961735802702749722765e+241.
+2.6164848772947258622766134e+167.
+1.2011948183863013203243921e+105.
+1.6771175509144391596610546e+184.
+2.8738932548427247337766382e-307.
+5.3289032991237255048211997e-245.
+3.4375817854061215152484470e-102.
+5.4214868809504171591961146e+57.
+2.7281876863165128906250000e+13.
+8.0965761368958679680770668e+303.
+2.3990419087008743924860779e-197.
+7.6987252286507301362231339e+251.
+3.6661051597895799053959734e+291.
+5.2670407563704927951714137e+42.
+1.6661198438998280352028232e-113.
+5.6863394138990843558179623e+102.
+1.9186046494112488327848268e+224.
+2.4178663566179458454923745e-204.
+1.1303439789125948816103287e-184.
+1.5740755060072737557166065e+183.
+1.9869146963617893760275833e-60.
+3.6451692179176789333931098e-158.
+2.1892940164898723351207493e+291.
+2.2198213877514254583614963e-64.
+3.5923149055039747681668317e+142.
+1.0573720297151749940669783e+73.
+3.8672544238899761034168088e-250.
+1.1400051084220270402241326e+154.
+7.4849086924474008448757065e-32.
+5.6541057387778690196219376e+261.
+6.2281026819658877217468356e-57.
+5.3163798653829711776317447e-290.
+2.0497398548964914067397552e+244.
+1.6480189999274608466609946e-155.
+6.0735558518917897302959585e-116.
+6.1472378655360530682132890e-73.
+1.1792393298661614754251977e+186.
+2.0981718768435202598854285e+261.
+3.3058188954143413453999732e-265.
+6.8174628553579902699509832e-154.
+4.6019731827548075127492591e+196.
+2.2495325646558485470602371e+67.
+2.5505620001445034168034824e-193.
+4.2742651215850609082899625e-293.
+2.7045162024290951517455911e+281.
+2.0912163577310935756235654e-212.
+9.9141711953564291625373329e-17.
+3.6096320124781622886657715e+09.
+5.5773068171843111051089115e+212.
+1.8131632712258855857931032e+33.
+2.5613692304085285042869045e+241.
+5.2857715541376620531082153e+06.
+3.2682088290881328967767445e-229.
+6.3909599041466698329082701e-39.
+2.4027937059394691111957621e+226.
+8.5916491882086466875298658e+298.
+8.8884819229654865533469058e+194.
+3.0026541032662238470006101e-286.
+8.7888163527927742387847032e-295.
+8.2009546871925967638374788e+68.
+2.0444673693579852208720652e-281.
+3.9393539600809555552069123e-115.
+3.0803785553975217216023654e-214.
+1.2907796482762249883074841e-168.
+1.8902325974245726735021906e+234.
+4.1535824500087913078729562e-266.
+1.7598860931129253253826623e-103.
+2.0995336182393240978532175e+259.
+5.9690343940075563100577938e-01.
+1.0205637861901978457631122e-31.
+2.2738096161702265286257301e-55.
+1.8867771141804993655643495e+133.
+3.0372531387043330656709384e+101.
+1.6932861219322357285603570e+226.
+1.4849983127095263798341132e+87.
+9.1201334505827886308532149e-04.
+1.1372724746171669149511536e+60.
+5.7091472713197507599684066e+169.
+4.7075121063754156443475062e-299.
+2.2511738156532974400930504e-253.
+4.1800880028840342640453641e+125.
+7.1436445321426872423486998e-02.
+5.2040093546068113973510621e+175.
+1.5135095738532524103625722e+151.
+1.1641915941515764500352603e+147.
+3.4896209960276145537870189e+236.
+1.4468701714921936253135559e-09.
+2.0072711679287834800485652e-197.
+2.7481993362792816929664101e-83.
+2.5799686161132505925653320e+303.
+1.8340618031658417439303503e+292.
+9.1652484461142518698610844e-182.
+1.9953411464078682019743160e-161.
+2.3232675743970475957845398e+160.
+3.9188381941620187006746373e+77.
+1.1387157282632062911987305e+10.
+9.4993276251154197563507060e-121.
+1.9010926521692247393337353e+292.
+3.5474028323843935300579224e-100.
+5.7176685817857561533165531e-277.
+3.3741938634502666107943101e+108.
+1.7456436491387906518809141e+44.
+2.4824878056564076607293054e+58.
+7.8466940460756903770548570e-197.
+1.8700357296194009956352000e+22.
+5.5714584387371756612905093e+238.
+8.5151701038721837319752979e+186.
+3.4834493416561995541750321e+272.
+6.0965560910799208706576948e-17.
+6.3519261319691547957002240e+24.
+6.6909096364736425093356120e+146.
+9.8362769261505859432319046e+137.
+9.0217327054609436430728496e-182.
+5.0558696146554739686052294e-295.
+4.6861144719161040860696221e-82.
+3.3605851447041528699325137e-303.
+1.9723341459929370690577175e-259.
+4.2957641173641149100335990e+186.
+1.2355894394329637544265336e+179.
+1.0308766991103956829375190e-166.
+1.6539231935744669231153322e+57.
+1.7089862299671835205199749e-223.
+1.4264192482594090542648149e+208.
+5.1232653624384342570101843e-35.
+9.1516496191408620380140427e+175.
+1.9780193799915671557881707e+196.
+1.1853836414995119569987059e-09.
+2.2596892935182304173642037e-74.
+2.6167029744626260553533870e-292.
+1.7187874614222420737087211e-141.
+7.4513714551024437162698670e+194.
+3.2406065906361539165177889e-93.
+6.2770315375605163532388015e-66.
+6.4060091533057107961275902e-146.
+2.4745211214995314505766996e-292.
+3.3248302667111527025646292e+30.
+7.4467817937100875150514561e+168.
+1.1708576008855669731687276e-73.
+4.5182409908336197635917451e+106.
+2.8855124793485796409767867e-66.
+2.5178790177353879132975822e+51.
+2.0877894555635177128132560e+189.
+1.0131922384752667424905803e+171.
+1.0888625663118925209804603e+250.
+2.9116617358370312689507645e+269.
+2.2269882380928733653243094e-139.
+5.4929172017084430547150113e+176.
+1.1330490931993441465431926e-194.
+2.3486010344141669533337174e+76.
+6.1130385487857184000000000e+16.
+4.0521949798916609416335211e-150.
+1.0824899623146905964364780e-274.
+1.1970666601565364202637503e+205.
+1.7720054176358666810085413e-43.
+4.8334984670945800138473260e-196.
+2.9202184705044473099906248e-58.
+9.3159760130978225856333478e+173.
+2.9965820892098839837809197e-171.
+5.7767815100826441760571994e+187.
+2.9391254199718084958569076e-247.
+2.6508734636879739696193004e+264.
+3.3081684840588372871844908e+289.
+7.0312076315037519081131699e+214.
+8.1290970321979435643402060e+34.
+4.3359419004571735518994720e+120.
+3.4556693590395541525073633e+57.
+3.1141889474879827481046206e-133.
+3.3010238337108989364513098e-33.
+3.7892594930709304529589954e-252.
+2.2110089000919883342659744e+159.
+2.5368207925184071746648495e+151.
+4.5498180978136769032645032e-221.
+5.5452416115258278834239846e-260.
+1.4562473921284788333387120e-58.
+2.5563619187771035157714624e-72.
+3.9495081297416403204609686e+68.
+5.7051301620212512442963191e-19.
+1.0569337929722703413585742e+32.
+2.3199407379716585523894952e+296.
+2.2764552722549805439259407e-177.
+6.7176201645241527881709057e+258.
+9.7644793506755902255213094e+147.
+4.6701426397633949043569806e+53.
+6.8183305849875323707991641e-38.
+9.9866882536578022958072000e+294.
+9.8118994034748566179793272e-02.
+6.9981734071505505729185304e-225.
+3.3395769350969929166617919e-61.
+5.8347567683276308002978798e-210.
+1.0021061566680697107979175e-55.
+5.0077676436275131255315943e+230.
+1.8861710043777578045320079e-60.
+1.5467759893756816548720182e+264.
+6.3788455736403722344596602e+267.
+4.2980091470728228287671782e-103.
+2.6865298625225955585388795e-76.
+5.9426732506617235448102108e+287.
+3.5198420163679050367339405e-145.
+2.9525511663688744182250248e+65.
+8.6861363789271775903471941e-94.
+3.2054603619295294034347362e+59.
+7.2217728808994052975667033e-77.
+4.6173366333150373066925458e+271.
+1.8967180780127829678139429e+265.
+2.8513228553715588823887358e-96.
+1.0219767068434721785261962e-268.
+1.8984369716043205664806471e-16.
+1.2653118175378037769300707e+170.
+1.8321259992245574514138882e+211.
+2.5158282764157380534187425e-30.
+2.5569194153364598471370358e-301.
+1.1469220360480353183009362e-179.
+3.6888458108200878197096194e-280.
+7.0067811939605278332798755e+139.
+8.0197603052058892163343483e-30.
+1.4605611071465004742727247e-153.
+2.7008273765632454018165934e-248.
+1.9815327403636706802746776e-195.
+1.5419758375255137534208515e+152.
+5.2452870785550060699570320e-111.
+7.3347158032722124484286090e-303.
+2.0507845792850676957638498e-185.
+3.8535298226333487998298968e-271.
+3.0547520137446686836703662e-250.
+5.2431780043205920145765975e-17.
+1.8908023796288588485737953e+170.
+4.1295510399768061717255748e-210.
+1.8833567702098789159208536e+06.
+5.8380439776091971814195573e-26.
+4.8085366130731823097922834e+104.
+1.1802072995116952216831287e-64.
+7.9988025469102520110227172e+105.
+6.1612912445810842487097610e-226.
+4.1965161940367485778472149e+278.
+1.1576125150255336652800000e+21.
+9.9262986704658985049597889e+281.
+1.6011958219556102394143924e-156.
+1.1721617090812578550132665e-62.
+3.6906411194035375184476326e-242.
+2.0460132789146983894284194e-231.
+4.1351985452792606814651174e+165.
+3.2370754073386987502341328e+221.
+1.0426594797596559621068626e+186.
+4.8156771644369269442976006e+190.
+1.3206407929344789672099840e+24.
+5.4532898765625042558298567e-260.
+5.9408791568208287929306576e+236.
+3.9404685030386387144613246e+293.
+1.5026372890301841441692345e-89.
+3.8478190407428177240588708e-123.
+1.4718026076466209363661080e+134.
+6.7041201513122017951855292e-208.
+4.5839557135322494538726856e-243.
+1.7207897946602303885831800e-305.
+1.9604139032161201307463799e+167.
+1.9246089407989488977954609e-75.
+2.9632855506624488579655433e-115.
+2.5096867107286982656000000e+19.
+2.1822271790447417761655380e-234.
+4.0489627207467218354377932e+172.
+1.4010321940677539496871806e-187.
+4.2327662096906741554997077e+90.
+5.6622678560823200410281598e-180.
+3.3792875529452238927665584e+104.
+1.0007457053565162676094468e+39.
+6.9420955324836812800000000e+17.
+1.0375568272143978301472793e+244.
+1.9237568152496744098647327e-147.
+8.6492531444344250051264167e-119.
+8.2458537609570476929922339e-222.
+4.3390924335054150997124638e-255.
+4.6286090765086721270375477e+148.
+1.0744070084892460318720000e+21.
+5.3291985888837447851064732e+203.
+6.8325628529860918529062026e-137.
+5.2891582618178166166651076e+221.
+1.2536991163602116433453917e-185.
+2.2271606771079911644184854e+175.
+5.4331578160589665878436419e-245.
+1.3358668451953350391121169e-41.
+3.1371808161527677742829076e-203.
+1.7858498845158154453950238e-121.
+4.3754479840556452517798280e-281.
+5.4213354383801197350058308e+179.
+3.2152601744206109978276853e-38.
+9.4169838162293414801793547e-185.
+1.4013115914615414297155104e+80.
+7.1263963758163149366328871e+51.
+2.3469041158269360457438306e-102.
+1.6528232264373550786235697e+257.
+9.1099608462152740577016160e-13.
+1.0542666852547930390629116e-54.
+8.6225594436390638027963092e-145.
+4.5893888083290946353714561e-184.
+1.3697735760104449621978014e-102.
+1.5283564998816136585161228e+235.
+7.6836307703944078817548240e-12.
+3.8208605023111774978830393e-150.
+1.9626449854372133909077579e-236.
+2.8282670810926512387816156e-154.
+7.2031673591321332126603973e-240.
+9.9088584479669436931830905e-143.
+9.8362864831035309092570807e+38.
+1.0974118067264197987446118e-296.
+1.6123755896435815712277230e+163.
+5.7045832184818133700252306e+69.
+9.8229526773639028088941725e-237.
+9.5596213642514705928799823e-166.
+3.8971978425279419247048917e+74.
+4.7739346262836109324855410e-222.
+2.1450962857136447885454410e+136.
+3.3334079936045735891175382e-119.
+6.5136872940664660945905077e+229.
+7.5804828870773324946911374e+300.
+1.1248075703456099715293976e-139.
+1.0629128981424451941872353e+193.
+1.8358956508002222401965747e+139.
+5.7078631784847183940436747e+128.
+2.8041849493439041374819280e-307.
+5.3461448298071530217162401e-49.
+4.6722580794292647794236630e-54.
+8.0481510468279647128459221e+97.
+3.2223729770599608870070334e+283.
+2.3782167131344176004876656e+210.
+8.3779189508499139043649147e+294.
+4.0451915659259938884148799e+189.
+1.1301287093016426930028317e+229.
+8.0262782921970751220836011e-270.
+8.2044327760951178192007910e-119.
+7.6328178703280874506376108e-02.
+6.8854497647926055768493489e+43.
+8.7036590394386919029536367e+176.
+2.5941620605753531561637841e-194.
+1.0451819640314440504780258e-129.
+1.3604716314396409208739885e+224.
+7.9185786294436732890737178e+177.
+1.4681736907393420876578816e+25.
+7.0247113120859784760356477e-241.
+3.0293868644045645315890133e+266.
+2.9221863306595993808681423e-252.
+9.6693556994667780533917356e+233.
+1.5841062607638813737828577e+217.
+8.0293533499507159691617933e+272.
+5.3136935045797308734437791e+179.
+1.9631515389232944758105148e-144.
+2.6046582378339704326957958e+101.
+2.4611843811625579954282356e-108.
+2.7644197042529818141173595e-67.
+1.9038473525488376698406273e-259.
+2.9916496295015965502377134e+210.
+1.5277123772646204290063730e-140.
+5.5417299971291780658176762e-155.
+8.5817020870327169692493807e-77.
+1.6868507389905160273846950e+153.
+2.5713604826204290957729909e+54.
+2.1370576989374894828024545e+113.
+8.9230531066812457802323435e-208.
+1.5386942824881083625937414e-136.
+3.3840067490366078355965404e+61.
+1.7824904494778712465876088e-50.
+3.7166636322688623382791560e-72.
+7.8871327912588090228007220e-140.
+8.5812246232859854334355468e-156.
+1.6986743830811041438826081e+243.
+2.4176242586472405572694372e-44.
+7.2325780565609088735673023e-18.
+4.1923309167578729240412473e-187.
+1.1076005418612767208082260e+155.
+6.2432901346236679793341057e-291.
+9.7611970042603424876904002e+124.
+4.5990453871990102850791052e+285.
+2.6985680890256322125372600e+104.
+1.2531483765294019800393967e-11.
+1.0426985688750015924770079e-129.
+6.4653902742150674811336866e+217.
+9.2375085659825538182358117e-110.
+7.9295057435760186668548542e+251.
+2.6709615762043859720693424e-264.
+9.8233981154814822822635811e+198.
+1.2393024557017377705005386e+182.
+8.1538499029025559570861261e+26.
+4.3719364809124419597084625e+139.
+7.1996622580839633761638587e+221.
+5.4936022645308364386525357e-217.
+6.7622832639414469098058728e-190.
+2.3078167343011420153393044e+223.
+7.8174471037448672468217977e+296.
+6.2054934572952793340991351e+95.
+1.9643204323746612960248804e+98.
+2.5816588130100219645997355e-11.
+1.0492865364300151354190220e-102.
+7.2428811587722008840786706e-60.
+2.0898648258289543054860741e+128.
+8.9777056648065632699679626e+107.
+9.3851556981158490773907939e+137.
+2.8905003785708204855985727e+176.
+4.3778359418297442030620867e+210.
+2.3302592665317623560201113e+227.
+4.6063278373000369526684716e-267.
+2.7343388838435768752095035e+156.
+2.1815042339858825419862232e-272.
+5.6707083736838410068910962e+195.
+3.6221988959020504924581791e-276.
+5.5342118279682958808081884e-161.
+3.6414838467770064756732500e+92.
+1.7672619332876751867369135e+96.
+7.5026854288996850865814525e+269.
+5.7777072108788380632184955e-242.
+3.9765491052977118969341298e+132.
+2.6593302565509531396424037e+87.
+1.4998936493466558593750000e+13.
+3.5515807737730479341077580e-208.
+7.0121054810602461860986880e+24.
+4.6375920633736717439706267e+175.
+1.6042794650961588987462094e-242.
+1.6868361234445976412423176e+255.
+1.3327196025214308223429389e-264.
+5.8477805484244631750582419e+196.
+5.5594085052985159515972040e-44.
+1.5106740127948433202179640e-177.
+4.7904236358140316230177428e-162.
+1.0693270137169565625000000e+14.
+5.9064846061072385099726416e-300.
+2.6689789833023025272924455e-191.
+2.4270168574935937840152452e+49.
+4.1026962477420426016207232e+263.
+4.2082888881055798738203843e-109.
+1.8560438087379260049270599e+153.
+5.7184261044598433962367217e+132.
+2.5258851060860268423115818e-151.
+3.4766170330361416644323175e-79.
+6.1059016067956920769332355e-89.
+2.1763750805863206056568453e+300.
+5.0030196259562205478912000e+22.
+1.1670559018423963395048619e+121.
+1.0757592648931728500889509e-187.
+5.6845824999634022308666094e+202.
+2.0473735651209506504484947e-259.
+6.6810695130603786107745483e-41.
+2.7571530703721327011338458e+199.
+2.9191348441301859961881355e-172.
+5.1598492876979001403131012e+71.
+5.1507427062552362041427386e+54.
+3.3095749520324676539664825e-166.
+7.6990439092057462236688105e+250.
+6.0745272076261427742395011e+265.
+3.2510880631181247982659498e+243.
+2.6084973390798776164407452e-219.
+1.4576409501444372848965401e+253.
+7.2194218941568459145984378e+130.
+1.2645415504791979314520890e-143.
+3.9539706907815447840191584e+90.
+1.7216712000565340936807877e-253.
+5.9734860163767613440000000e+18.
+6.9797274320287622367782748e+33.
+4.4211720409610693440946101e-256.
+5.8037341296648818489028086e-123.
+5.4066876184510315785780136e+82.
+1.4720920555305589078590218e-87.
+5.7592528821869278782694954e-63.
+2.3072254772649203926808175e+151.
+3.4495385799905326498744935e-77.
+8.9334901069731191824985217e+00.
+3.0597102214405583488921674e+92.
+7.5978747436221014658382485e+60.
+1.2795501105192118439705943e-261.
+5.3190015262381030989615962e+282.
+9.0918293399998382150471279e-151.
+1.7264340737818786000000000e+16.
+1.0314141019455524042711288e-05.
+4.2055270092720296428734581e-265.
+3.5217403859490337114268272e+188.
+2.3802337496408179868850132e+235.
+1.8214182351875138279249382e-199.
+2.4199203066077928957830729e-110.
+1.0379951087268111100804132e+244.
+1.1489167416497917440000000e+18.
+1.7326397670268967843999909e-188.
+5.8973383924355892586162322e-266.
+9.2779232024572754732956652e+160.
+1.6946780703350964832311261e+90.
+7.0028692650362870321276297e-138.
+1.7772175961409085972784648e+298.
+2.2748525331821691447026934e-237.
+3.0524096436934187469643461e-231.
+1.7075836238672720932394675e-223.
+1.5858273812749126707299677e+173.
+2.6021353797645173689770335e-33.
+1.0175423348320388195124202e-258.
+6.5830683706422896356741511e+78.
+2.9521007510909915496288932e-263.
+1.8728540000971021336331050e+264.
+1.5594379738766255963766223e-265.
+2.9626344503126269205826395e-176.
+4.7123654978741445113566470e+122.
+1.5976513494798925674931349e+176.
+4.1793904429212541349520033e+70.
+4.8683685610090740742459350e+42.
+1.3914323593420918920918513e+308.
+2.7713120038066503391679056e-236.
+6.0039361209944780237658992e-149.
+6.3071555245389356167892425e-133.
+1.0320734936086769900674164e-112.
+3.4961896267525478063001163e-137.
+2.4830978643780902827030205e-165.
+5.3148770003078746988457065e+98.
+3.9665180643215329745387882e-52.
+4.1302997037828901852583208e-134.
+1.4538828095147216355358149e+274.
+3.2675431440120367404470565e-186.
+9.5822496014802810963555921e-82.
+3.0868506405480110764547460e-243.
+2.3876488751713308172642680e+279.
+2.5825269570386746607988423e-209.
+1.6851921836105803690994916e-42.
+7.0760766223767538785452419e+227.
+1.5965689514572396390049864e+151.
+2.4650958725235153888190959e+97.
+4.5566239023340888318861050e-297.
+5.9918413046956593844775268e-05.
+1.1031854187530889142175848e-24.
+4.2352825122518060808543554e-107.
+2.3448891661409115993732917e+160.
+1.1365879654792738675684590e+235.
+4.8876210771198349482681607e-308.
+7.6798019685093840171190802e-80.
+5.8896206179789787328835016e+89.
+5.8991863694939168522425117e-231.
+9.0201247750686415209052868e-12.
+9.4243187877357630204563972e+295.
+7.2003368357463026073047536e+189.
+1.1170632727531784473971004e-274.
+5.3735411226304952813189316e-127.
+3.5219169927312058208265772e+102.
+6.7168899843950858341281468e+127.
+3.0309462208205359202458634e-187.
+1.0373931412354675038728606e-65.
+3.9458435465879835946426221e+285.
+1.4899549997721200061660803e-167.
+3.4529583136115808311333368e-193.
+1.1313946880638896633174594e+78.
+8.9862149234587008281091782e+110.
+1.7299523869574012723192537e-54.
+1.7245846944308662831420487e-235.
+7.9138704257349515820841204e+116.
+1.2715105087267376068296974e+287.
+4.5753495160352513483372355e-123.
+3.2329523306050968116249993e+152.
+2.6265177995828270320131955e-239.
+1.1513178992183675054333251e-237.
+6.7608104536792123731319874e+124.
+2.1745482296660209702925073e-49.
+1.2270519034602948872661179e-250.
+3.0749159605144014307855425e+146.
+1.4490535577081743844967310e-150.
+4.9286713163349009141146994e+240.
+1.2067400953892218480327490e+135.
+6.1307103188752867000320000e+22.
+3.6683317886113335321119175e-268.
+9.1046711179409162241514525e-74.
+4.9004345856058831163976720e+228.
+6.1248543885420155684265601e-239.
+6.1437370567884149543576030e+143.
+1.7852802090295616515753769e-217.
+1.2364043610711455589990400e+24.
+4.2116138581338930042780887e+126.
+4.3132247750150698394948563e-15.
+2.2403258527489977836926366e-55.
+1.4707160233626557924265644e+305.
+1.3272554880727198499845957e-33.
+2.4017319707056034807731152e+33.
+8.5490443842463515625000000e+13.
+3.2841732888645166830759199e-122.
+6.0553207759369165441612851e-261.
+2.4966234353959714303919918e-135.
+6.3775136435710311580493741e-46.
+8.2352162551656804403408678e-19.
+6.3353691404632144946057988e-156.
+2.6247580156228524029090391e-162.
+3.6199514556255047018555586e-237.
+2.5793134407573432784019577e-27.
+1.9843576487255036151189771e-153.
+4.5488956349296282540711412e+111.
+9.1635960653964563534543075e+82.
+4.8857425312593887859827782e-189.
+8.3598813015674832937289992e+284.
+1.8810213526805035064385125e+104.
+7.2348174429511901347716328e-16.
+1.9394591706193233662961935e-86.
+4.1741588709020050381940265e+136.
+2.0055319014110377572131181e-172.
+2.2243362547244120352594837e-26.
+2.0360939297106500150941390e-255.
+3.5574098160094475635363024e-82.
+6.8077336865054852289212566e-100.
+2.9736116942996882585136132e+280.
+1.2156969796251729777162279e-276.
+1.3014796747852566962715969e+155.
+2.8326045826568663330697952e+50.
+3.3209812531585725648344786e-283.
+1.8194247718815661268378159e+206.
+1.3645640014547106451977228e+80.
+2.7673864163325878061340552e+189.
+1.2651256573456803699740860e-16.
+1.1580282267981062932819981e-58.
+3.6349907950526645342571125e+297.
+5.2831778907079194066590770e-274.
+1.2430136559101756901187249e+140.
+3.1382834977905056802126321e-249.
+8.1123725819653615190458320e+292.
+1.7946265597570823070154752e+27.
+4.2450258361813740533363682e+304.
+6.5534075287062330276379706e+142.
+2.3973663580268130000000000e+15.
+5.7627398434521208683808034e+214.
+1.2619433183830903940709403e+161.
+7.1455959810388411624940655e-123.
+5.3549529255015675893234348e+182.
+6.1566971844088445025902360e+286.
+5.2639876143348738307779184e-73.
+3.1610703517288669978849828e+201.
+1.9841312505166199371419090e+142.
+6.6619330073225482902911968e-200.
+5.4428093119260043951520347e+65.
+1.5434645248684403532982825e+80.
+5.7714339622189672207926214e-129.
+2.3150022150636492676658495e+38.
+1.5351279933355663471720318e-99.
+5.9581455944493754283566252e+150.
+2.1465973758200831756265918e-44.
+1.0473398398260730417582223e-265.
+3.1480223215279580251033677e-93.
+6.2851635048880900865982434e+214.
+5.3891776698755073970262484e-217.
+2.3317873837637293810856264e+118.
+1.8445652466184327176335075e-196.
+3.8852316893799485207544147e-290.
+2.7489071980627971463695250e-126.
+4.3060926430871974246716356e+31.
+6.9710099655627787296386522e+72.
+2.6715515935255577038595039e+209.
+1.3198547037308311737865705e+250.
+3.2856143578991818889834912e+305.
+1.3236965921418290688910744e+291.
+6.3396181582354529717041664e-212.
+5.4477972828462108845583099e+66.
+4.1692490429493367831750191e-182.
+6.2101478978352904830208129e+99.
+3.9365794386108922545494287e+161.
+2.4970336864268171507967078e-207.
+6.1271693004874148437500000e+13.
+5.9414032646666864682040314e-83.
+1.4491309089752366585576590e+291.
+4.6229818425893396946335761e+54.
+1.9156656853391755014998283e-208.
+1.5500216503754383775508228e+300.
+1.5078658935136574875285434e+40.
+1.2059892613743625073613763e-222.
+1.6999114002062628079088944e-109.
+2.4487444126481221886790569e-48.
+4.0387329653179702778555229e-196.
+1.3323516624237511250542592e+26.
+4.4858681602285250000000000e+15.
+1.8316745673206093888809726e+245.
+7.0987538323600602275208296e+196.
+1.2681044054648717476718742e-56.
+3.2686902068309606750829632e-38.
+1.6404606396808615903519445e+87.
+2.9703757731321959209558874e+80.
+1.2083572722924902540858824e-135.
+5.5528317370655967066936091e-272.
+3.5093985819518573318347208e+55.
+2.8047536527597312586849112e+62.
+2.2251691334349594116210938e+10.
+1.1142849989492641902315029e-41.
+1.5535440909109525659408711e-192.
+1.1930479550592345609933937e-182.
+1.6979344220091822414318828e+185.
+1.2700275129188527255817396e+72.
+1.0029183813603940103018672e+91.
+2.9820690957331878590634217e-58.
+3.5968272097135512940947752e-304.
+5.2179981822642182115038970e+80.
+3.7811354957839527165141158e+186.
+2.5574351647057701381895895e+236.
+1.2680674487130067085929855e-308.
+7.1130805109332939579185707e-309.
+6.9651618185544344000000000e+16.
+6.7842691696090040096513336e-292.
+1.2989552226982332282550584e-205.
+7.2144242469238519220171131e+52.
+1.7492130788013063872410525e-114.
+1.4670539688045423701563698e-200.
+2.2006567722909413258833669e-154.
+5.8588089873797264345781279e+70.
+1.1483344720436903500239914e-85.
+3.5787435963594623334436354e+136.
+3.4962574359129475786989726e+89.
+4.5928820679242726706283458e-156.
+2.1149206413164683342020929e+176.
+1.3459794689358877851255657e+84.
+3.1695442643458008169410993e-169.
+1.3312355428913746684103348e-273.
+4.8849187269279564964555567e-217.
+9.8617885370290550917633064e-15.
+1.7823487685051355834094901e-144.
+3.7982325416929531684509854e+44.
+7.2657025899176696934839642e+127.
+1.2184167065380715575845187e-48.
+4.4188039956041900377812744e-271.
+3.5359840966055521227924405e-39.
+2.6662925346384808615234215e-125.
+1.0342637459640459198833021e+75.
+2.6173811897228897186186410e-139.
+3.5668514041596207084409701e+71.
+4.3775101360399681296246918e-117.
+2.1631615506868754202163907e-175.
+2.0631976984424742515087951e+101.
+2.4669879753910743517759204e+189.
+2.5772062754457251395330869e-36.
+8.8938906665174614046075398e+248.
+2.3409259241328514708724767e+61.
+5.5440712047673087225155841e+62.
+5.3117780171076958945530839e-217.
+3.2973993268063365211263058e+54.
+3.5788207631611559032278530e+288.
+8.3016163757104402516685235e-63.
+4.3039754723356706127808257e+275.
+6.0603982728541691537281669e-216.
+9.6120014540667150000000000e+14.
+7.3907630653458325687932372e+111.
+2.8395632037985301519827081e+262.
+8.1055914704888502517515661e-130.
+6.0734791564834315254573162e-229.
+3.9194876763000356593272353e+257.
+1.5770756425871036632538464e-195.
+8.3264556009988792724937303e-289.
+2.5802611775897681268958071e-285.
+1.2722878352559876476937732e+66.
+4.8062653201200269007259260e+39.
+1.4870727660702827364304358e-282.
+1.8708047058511867692892043e+149.
+2.7463175755435065936246821e+283.
+8.6107676152238853033479466e-297.
+1.0303182862655795262420323e-138.
+1.3845472089856465447985379e+107.
+3.5527799707819721271653374e-203.
+2.3203990294695002661203201e+253.
+1.5146912429420203585013135e-06.
+1.1556840141820213545202220e-294.
+1.3233853696674460571785895e+40.
+1.4755343692140195258898635e+304.
+3.1384338573218960676746918e+212.
+2.9210340967140866664843748e+251.
+2.6413250187480575804843225e-121.
+6.9137218596197129805502565e-89.
+2.2377014817559497014927813e+57.
+1.2794305985656031066363517e+289.
+1.5566909077324293430688030e+126.
+4.4235921724750306666907710e-132.
+6.3036245871807115003660141e+255.
+6.5539176876979625193727204e+169.
+2.0695260206014591352958994e+68.
+2.9712884040822986940474905e+212.
+2.4400817425085366640083337e-292.
+8.3001416924086760392243196e+130.
+1.5939734913107947729294847e+30.
+3.0704792183237480927116300e-186.
+1.6307777884033076016240629e-145.
+5.4283461144465329344270829e-118.
+2.5810491396697076288970357e-180.
+9.5003526337801934250911686e-296.
+8.4650964181766939842858518e+113.
+1.8751389107848104879433859e-28.
+2.6833186308225770425332208e+168.
+2.6677480687637455931878298e+185.
+5.8785263165187411463372800e+23.
+3.4542385990142302662379316e-220.
+1.0451944940360034894764794e-192.
+6.0173175772288236712519719e+168.
+4.4709430461261932373046875e+10.
+1.2674442192057354666002762e+129.
+1.2157524499690070841450372e-120.
+7.1985465508047686472955179e-101.
+5.6627914482045985350217686e+77.
+7.7792683202741635139046672e+92.
+1.3894758157597031020492248e+137.
+3.3595797750214672214291161e-102.
+2.9161838116899776742810899e+224.
+2.0394386071014953489342212e+165.
+5.1886693782764842964668518e+190.
+2.6116520075431991888407355e+151.
+5.1665822568685836023003360e+209.
+2.6614583478042802092260610e+49.
+2.1155401884905221175245254e+145.
+3.7365645107826543913631667e+00.
+4.3291626566363515074538173e-141.
+4.9809487174652510930984874e-205.
+3.4469293855236511839416426e+202.
+4.0580420719497646988069256e+110.
+3.5612637045023791300638520e-265.
+8.6598556145948970256213769e+45.
+5.0407699299686635885721731e-140.
+1.5368449339356787578573132e-177.
+1.1780791527861243926768930e-227.
+1.3122524257373844955606027e+76.
+1.0895198203820014375154942e+176.
+9.9403355134342290027146486e+157.
+2.1981808414138154300012374e-158.
+1.0947104890762156161995563e-281.
+1.3795257715475015369923041e-77.
+3.8545729915999568952884409e-161.
+5.3018246187373198637919989e+166.
+6.0884891808639765833246157e+251.
+5.0516749088287079167606012e-95.
+1.3460292605078235553651694e+37.
+1.7342046860741005465209974e-267.
+1.6358492707576588767487157e-171.
+2.4483881140840124395014027e+234.
+2.3721577651334162864675260e-201.
+3.3675062079155673414077959e-223.
+7.3849391069303238647245920e+118.
+2.0195258906294205379492435e-301.
+1.1082069235066596268800730e-161.
+1.6657954847363196453906587e+74.
+5.8459756997670643056170495e-299.
+3.1482145650583209001420863e+239.
+3.4364384823330160280801596e+252.
+1.0875079753564315904583412e-288.
+4.3031504000158025182925474e+223.
+8.1676320549240192000000000e+16.
+1.6093486561672280645365034e+209.
+1.7120839887562374455616630e-237.
+8.5572577060395135234053657e+247.
+2.0700776952111330087610678e-62.
+2.1756230546717057860939684e+35.
+1.1271961887218589702546762e+71.
+2.5930902115674347372052777e+169.
+8.9570458990611587432425825e-173.
+1.9887867738577362892835406e+139.
+2.7452842975820774378630028e+63.
+2.7993193693310803590177507e+218.
+1.5915232898324035200000000e+17.
+6.4714722288567513367251666e+209.
+4.9932460163269635982132062e+145.
+6.9442262218196952425356847e-211.
+4.6231481982029212012264759e-208.
+1.0081970125366064618405888e+25.
+8.1969033127096864814413825e+126.
+2.2894277503466728865143307e+236.
+4.8842729838559543059816173e-179.
+1.4703713269272574329456116e-192.
+2.5038229144736320104808910e+190.
+1.9616318209537901253501834e+32.
+4.1746947289019663452055473e-107.
+1.8098378974921201830100544e-257.
+2.0062199532912928626687577e-181.
+1.7796487930198364849122332e+198.
+2.9818395767278140724560749e-105.
+1.5327430991555972877405678e+40.
+1.7781649657351119730508377e+151.
+1.7311759553961070668031308e-220.
+6.0426988443539753456735413e-16.
+5.0307123115307487619794017e+217.
+4.1460358853277510400000000e+17.
+8.0798619212042556064945185e+99.
+6.2057855544472364323510128e-10.
+4.8590399392956275251706052e-219.
+1.5946178192397528613620465e+179.
+4.4307768436732159893294021e-14.
+2.2370433921967989796721904e-45.
+6.1634180989557387874743218e-285.
+1.6899541404892080206395984e-190.
+6.4468156867546869232626492e+128.
+7.5461993562421301269531250e+11.
+3.4805568325871225406815351e+146.
+5.6653678950904954880000000e+18.
+5.1075010574393785467356649e-227.
+6.1071202689751395944529577e-174.
+5.8961376339231235976071795e-248.
+3.2852564100528391899140347e+233.
+3.9021450774866991350183092e-192.
+6.7343568903959636171333162e+41.
+7.7901699137073559686541557e+06.
+5.6610174317286852845457933e+176.
+5.5692523543545275508763191e+194.
+1.6487343031938505732619038e-201.
+1.0860770718785332281402601e+306.
+6.4602158128703099391467594e-240.
+1.2261487338548765806964729e+271.
+1.4348131309954168100535391e+52.
+1.6564456619661211639550948e+186.
+1.9152444706095153010359261e-271.
+3.8474607844291171761427245e+87.
+9.5509214702432584066297844e+81.
+4.9383566992237461616943946e-198.
+1.0300617390763055785193695e-269.
+1.0654522939466963596637936e+61.
+2.1034025355418483377434313e+05.
+7.7772803804907562142821867e-10.
+6.8390440258845398128981458e+286.
+2.9065874828268880038447304e-305.
+1.5179548663895316677171751e+122.
+2.1977247875569743144062106e+119.
+1.8220421060930586257821652e+293.
+6.1663850764343919436238116e-128.
+9.4983563980323989680769746e+61.
+6.6288522681614489573398430e-03.
+1.7089572306726119198470895e-247.
+6.5430789796122923359647169e-06.
+3.5483542283106370571146085e-124.
+7.2052637252289022966431735e-59.
+1.4313756898363504359171783e-196.
+3.4655141392444926181724419e-10.
+3.4724562451630269044492475e+148.
+8.7666014162950511093818070e+56.
+3.2745340703112085582372802e+62.
+2.9135899904127195456227755e+264.
+1.4082099222357189785253619e-130.
+7.3255721252100913527480324e-238.
+6.9451381554481127810456315e-302.
+1.2486375571176442282072520e-77.
+2.8524785420301743901263460e+122.
+1.6400707237685886522427268e-137.
+7.7852520106262909638239478e-02.
+1.9399744354310813869087541e-21.
+1.1671542230450894673349821e-247.
+1.6747551448586005133793970e-191.
+1.0857799645479816253916047e-73.
+7.4921085500687665810243594e-69.
+6.4858108729651811561268095e-226.
+1.8199101028971336725230172e+265.
+6.3911927975135696026526508e-65.
+6.7630465967118726896898501e-95.
+1.8976119772948733813644517e+67.
+7.5592179487110771625862223e+240.
+5.4445581202182434584985282e+48.
+1.9100912810111587182141670e-44.
+1.2719967448203130419753795e+108.
+7.5689851267001306747711512e-104.
+1.2615628621413901273242997e+161.
+1.5461290978212199236487260e-182.
+4.7809215731004573210048067e-115.
+5.7003127793928933044275380e-08.
+4.1171364679651542935288803e-232.
+1.9935738559041702660473284e-221.
+4.7179370790554681680914767e+173.
+8.8183845665950273246560158e-85.
+1.7502701518179288228728723e-07.
+1.0580519510304023136187348e+53.
+1.0046458999682004926236145e+93.
+1.5968422770783808564174614e-75.
+6.9796569024975959095743395e-46.
+1.8048248462608527913832158e+235.
+2.7292938805041167044040818e-92.
+1.5753847202045295126534142e+142.
+1.9728162282909304175585967e+65.
+4.6387587982365456904016447e+119.
+1.5059749130634311449865870e-292.
+5.1978883613415730726815858e+111.
+2.4248350137208067096176498e+182.
+8.4489864313620555064921345e-240.
+3.7148821155406442602679419e+174.
+9.6543214996538199926178405e-154.
+2.6643383375050534399270140e-280.
+5.1861194150713359074588333e+237.
+2.8876109473948031864961467e+71.
+1.5321081894902134355977912e+249.
+8.1877462583387261474746814e+249.
+5.4121107133518155795271848e-59.
+1.3021593959778977579489615e-11.
+1.0137677854058306026730486e-203.
+4.5105145759740388647506759e-26.
+2.3509052533516117727066133e-191.
+6.5435691523376597619559257e-08.
+1.3383101316252945384155382e-02.
+4.3681053193692674084932960e+242.
+7.9003194895224528201214705e+106.
+2.9793609314001381383016471e+283.
+1.0384647404751641432506521e+71.
+2.7050424302160370685261949e+64.
+4.1824324438801010420405474e+160.
+3.3876617811183462434986256e+68.
+5.1007572915189364508288110e-202.
+1.4414188109767746703268875e-10.
+1.4707991103581251065861368e-130.
+7.2087029240094740992189326e+35.
+7.2189969764142874196637105e-261.
+1.1340586087880326434969902e+07.
+5.8156027389340141914635762e+43.
+4.4770902980387611662005827e+298.
+5.0781110255448667765043783e+272.
+5.5020210737341007535124466e-282.
+4.7909562674806075945250046e-306.
+2.1690343895694046440442045e+244.
+2.9215321592720666284990910e-175.
+6.4020560096411644183564303e+232.
+4.9023398450705318789947076e+112.
+1.0896032858177345192425708e-197.
+5.3878683111340581878315845e+209.
+3.7817275881750310038205852e-74.
+3.1933920350974356667391500e+123.
+1.7880175309787250520760461e+294.
+1.3183567170336652808021601e+123.
+9.2469964960722567522779064e-89.
+3.5646630274509017560214488e+76.
+5.2413717711840563092631084e-76.
+1.1258214925960858510703434e-161.
+3.1831963689540043139887713e+268.
+5.1578535352048236195750112e-95.
+1.6721515992121482849121094e+10.
+4.8579542201968839884800000e+20.
+8.2119595739006765499363665e-122.
+8.0366707074680096458324465e-117.
+2.2848299482661580324096976e-260.
+8.4248832449436688020559123e-88.
+2.5660663030000378666290258e-244.
+2.6574500714464377395349331e-124.
+1.9268698488522545560328404e+178.
+4.8213345170961817168451934e+178.
+3.2218214879279163333218116e+155.
+9.7818498344781318547469510e+78.
+3.2076855574875034502725440e-256.
+6.1745483775296386723914277e-300.
+2.1119238727562145238486149e+244.
+4.8108075120505669716593970e+213.
+1.5693361765301174500072775e+106.
+1.2449195852992973608109013e-57.
+9.0862535274189892224776532e-256.
+8.4106551188558421875000000e+13.
+1.3820253780247688905319506e+89.
+1.0483636139525581090615661e-214.
+3.3196818786821738651123215e+48.
+1.0384998881944749587539199e-07.
+7.8909971073190814795564342e+180.
+1.0778114025450442925913871e-80.
+1.2094240261458982770108564e-88.
+2.9284587327092106658806593e-141.
+3.6062143025573113215675525e+272.
+4.9864021269803191266085210e+211.
+4.4866251124496825086518628e-129.
+3.8856305110320043080159827e-292.
+6.1256879448008517716837549e-137.
+5.8058775682401009263645561e-173.
+2.8140959207353292189669190e+295.
+1.9072052972291645558798990e-260.
+2.8064279886585418882812539e-14.
+4.2068406834093350476392217e+288.
+2.3350575825745844881868149e+55.
+1.3208939144023966181650099e+273.
+7.3617488080166628589425745e+293.
+3.6462351378911858996346638e+233.
+4.1778052530162898195799109e-70.
+4.2804029352036359981731848e-213.
+2.2207855440971462136575172e+131.
+3.1624430974175549505233995e-04.
+9.8309635150712823480282945e+74.
+1.5252431733353320415922263e-256.
+1.2391376119835762043532527e+53.
+1.8613510017561994027346373e+05.
+6.4569908206478396856976365e-110.
+8.6650392245839631091223493e+305.
+4.9890693616602837723947357e-152.
+1.2964506221335332122580655e-28.
+1.2258018691138390639690390e-79.
+2.4143123032316689482365969e-121.
+1.9222818041004585095748191e+43.
+3.3850018568140458174439706e-122.
+1.1713849961319158197839250e-219.
+1.7082535701639156992009899e+301.
+1.8617718656505047364184465e+240.
+5.0858484129748603663756512e+01.
+1.4865242036476745370457928e+78.
+9.2583174700061428596058460e-93.
+2.7963409533014073759106970e+141.
+5.3584044745276026375471469e-248.
+2.9222560217470839391187785e+115.
+3.1388194000793760895193626e+150.
+1.4527184804159141073449236e+209.
+2.7343360831275407352042200e-261.
+2.6914561916278420885885114e-116.
+3.3001618905688454966755556e-293.
+6.7427124044142956436397794e+236.
+3.2371821642201087504280384e-64.
+2.6895994417415935664123283e-77.
+3.9326587229006890732721919e-125.
+9.6679242349967572720971605e-250.
+1.9244221320403727694221735e-88.
+5.5532019403204308419598255e-187.
+1.7167115000632933259770033e+260.
+2.7940603816999078547771612e+43.
+1.4110105228238952095341385e+237.
+2.8075102904311790283764466e+115.
+4.1634252360796263718124061e-175.
+4.7202629444520382545993588e-205.
+3.9988572075507467317372719e+37.
+7.0913990242747371816945164e-243.
+3.6491355211537438746865563e+110.
+1.2786188645812729264783277e+179.
+5.2747742849312580442426137e+64.
+2.6761005887546451136041753e-253.
+1.0890899989241711691426777e+71.
+4.6022894915770761903690287e+144.
+6.5386001024525053799152374e+05.
+8.3416095190419218150473481e-09.
+2.8726757114104648502136382e+134.
+3.2734848877137007266019727e-87.
+1.7599550981553736589214101e+53.
+1.4092293480411619546967177e-285.
+1.6332000740101821585360754e+260.
+1.3923030167864300220996837e-173.
+4.9802907839001903701375975e-222.
+8.6051683297290361591065179e+272.
+1.2932712952503615141403436e-219.
+9.4585012483773886718750000e+12.
+6.7249200510173677016812343e+32.
+7.8272154950046411519643566e+251.
+5.5975084864734629544407203e-229.
+1.5585937659604863875552323e+150.
+2.0232666209979828352270594e-99.
+1.3599865038329992519854374e-44.
+5.0366750015542039881344920e+46.
+1.5971990428236674360669781e-84.
+7.8592100159068119073518227e-150.
+1.8527601851145893065749389e-250.
+3.1452633070571007151010329e+94.
+9.4174097187316820054547861e+03.
+3.0227822366677531138793204e-142.
+1.0157340172878417441040567e-07.
+7.8425171645813920688598699e-23.
+5.4743823739166098653639282e+178.
+6.7820825878375872891237905e+182.
+2.3380729782293143927837474e-100.
+2.3754384592665220637968385e+176.
+1.3055646701316589635732330e-49.
+6.7698209065607458217848359e-43.
+8.4989934601003180632757778e+223.
+1.1991764890146712366036337e+63.
+1.0607173929869320987897654e+140.
+7.9370372551833101582019481e-02.
+9.1566172674316477916110864e+67.
+4.4238237313590187151050217e-39.
+5.6085511583090640392386873e-101.
+1.3678869492074642382832685e-157.
+1.8335038944514616687797570e+00.
+5.8139294069333137766934037e+251.
+4.1287967294778648105733720e-18.
+9.3681880703523160488566626e+259.
+1.7939739969666920653591417e-91.
+2.3983321515677894423612336e-48.
+4.2233058723025352692499549e+39.
+5.2013884668422196144942143e-199.
+4.4248164356789941787719727e+09.
+2.5250932529675455110617081e+38.
+1.3171925567397904815386825e-288.
+1.0554487027929699168140202e+96.
+6.1842389968179163262007267e-172.
+1.4392362509484948868007547e+171.
+2.5429835856653808178610973e+99.
+3.6071607208367726608994471e+232.
+5.6620814809946665211377370e-278.
+4.5315981740318084236562868e-01.
+3.3019080910889056268900072e+272.
+5.5460199398691428120094255e+119.
+6.2801689583509509255117486e-158.
+7.2100920410635079431303268e+292.
+6.8346676672125427700768052e+93.
+1.3205346936768347977714131e-229.
+3.3165027715285466383739783e-118.
+1.8363241063450416326311862e-17.
+1.3700829067172576836789856e+266.
+1.5735511849514278530339560e+99.
+2.7736649723300961855962208e-301.
+6.5777226712427165783947543e+50.
+1.6883081215120417780988265e+61.
+1.5825202098850134181009706e+240.
+1.1962085152478373764126515e-105.
+8.1334740109436116516257453e-05.
+1.5236341362053712156729359e-167.
+1.6819742148164654318573106e+113.
+4.8816720184249804443814427e-307.
+1.5252629652164728861901512e+275.
+3.0370394229533813826720588e-56.
+6.0400182669927087103374926e+113.
+1.9142541628765492381363193e-168.
+3.7605300718090027563682330e-50.
+9.7180291395201711971243393e-67.
+3.3237019399657722560394424e+100.
+4.7054806696159246835659693e-94.
+4.3717250776740881003076439e-141.
+3.8365462937525817261582299e+32.
+7.5768422985963830646856263e-139.
+3.9988629642870583512268800e+23.
+1.1693602728826603561125260e-173.
+8.6418512508342938149019463e+100.
+7.9454927344432027359358412e+159.
+1.0854884746291417488877406e+108.
+1.6552056942585991113155929e+290.
+8.2505025272888034738369662e+111.
+2.4523274674407489708561265e-94.
+1.1016459634555898264420658e+218.
+1.7635423040993018926742238e-39.
+3.5065653745367326226559327e+51.
+3.2315872219674953081268827e-108.
+2.3239086182998319312565494e-82.
+1.4122627789035431799846355e-300.
+3.5304041304568315047999022e-206.
+3.9237034721380988693495520e-263.
+9.8320722149373337500000000e+14.
+5.1760660932845289798170776e-187.
+5.7301525886139557371004317e+87.
+4.1663027006453225787549940e-202.
+3.9033489929994191429796282e-65.
+2.1377669513870751601568679e-60.
+3.4338052043254346591751435e-158.
+2.4088456699461189583151943e-115.
+4.1640252405614204773141468e-103.
+1.1653476519423717435425633e+206.
+1.6878176179153542827437767e-91.
+2.2690257739588937055043628e+236.
+6.4855037644870452582836151e+07.
+1.2086274663811928139075477e+154.
+3.2110557463066809999542611e+122.
+3.7902612035464362592681386e-166.
+3.6524382178926821967365949e-162.
+1.2775307109933909586295442e+194.
+5.2057468250032565107342227e-13.
+9.6102644982597254504138597e-124.
+1.4650506062401609624199589e-19.
+7.5328729774166205467764666e-09.
+1.9770346043638059002321794e+132.
+3.6152694765667953115904452e-47.
+1.3017268443467134521850434e-92.
+1.0834394887547268406448665e-114.
+1.2225169916287053112173604e+101.
+6.1236151731299399359204125e-64.
+7.1890717463226681709758298e-40.
+2.4688988316081859948171339e-89.
+1.4409066975222826805212580e-53.
+4.0871060290156832726018830e+48.
+7.4108216499618953302102842e+104.
+1.8483117087233420418527488e+193.
+4.0192405541984625623290270e-81.
+2.5826388815703516998672441e+219.
+6.4870425420984007602539420e+130.
+7.4434107495815197908133081e+151.
+4.1334442585943995154367266e-129.
+4.1670870698662864812123570e-279.
+5.5163260932920512926355619e+196.
+8.7775893351080043370101277e+98.
+1.1599403991755554088106070e-20.
+3.5519014827499723368814422e+180.
+1.0758579457252688777401138e-236.
+2.5788596864423736776959757e-30.
+7.8977371607288008950231864e+91.
+3.2305956838069611198472121e+74.
+3.8902237796695642286893142e-151.
+3.2379002808730423207657472e+25.
+4.9279853855253747651136329e+211.
+3.4579960918414791906803059e-134.
+6.3470524976577221999975915e-273.
+3.6147113765366848796649062e+26.
+7.3563796917279110499080238e-218.
+6.0192359285799831262157822e-241.
+1.4368414392379145717204905e-289.
+6.6720372943192484286060136e-293.
+4.7519021590314176000000000e+17.
+5.3568635240406023984802347e+152.
+3.9538932229860933285895567e+200.
+1.2829097967201873434381495e-284.
+1.5419592729842843750000000e+14.
+1.1170132770655750000000000e+13.
+3.6139885429558537818360788e-215.
+2.5442708038520180284801779e-186.
+9.7005375033251732407296437e-279.
+1.9340273488397006190097059e+104.
+8.3210130138703558150787687e-11.
+1.9876885052553167345839468e-117.
+4.7714690896451465967908646e+231.
+1.1753224485535143045780083e+236.
+1.9679092665273664004835425e-07.
+5.0702792688310734776787347e-93.
+4.7957300436228909773959462e-51.
+1.6219460360367044813150301e-289.
+3.4621012530730281303695703e-305.
+4.3972573810636238094099185e+69.
+3.9094451121743535075544269e+26.
+2.8983519978693043455312028e-86.
+1.4276885458499699227840245e+135.
+8.1424483417601676732275346e-240.
+7.6812915336911581248870309e+118.
+4.3942993700024977399296126e-293.
+8.1142864814514673033052361e-02.
+3.2001797765355984988904125e+278.
+1.3718687183618339993639299e-210.
+1.4502214534413017282293741e-301.
+1.3510843953944860326442558e+120.
+7.5951842579574636981661246e-161.
+5.8282080915023134432072652e+123.
+1.9457293596733258543234092e-298.
+7.8053354953350832000000000e+16.
+4.0837401216865372174561320e-109.
+1.9481457790425483091165779e-199.
+2.7114169943291054882322186e-45.
+1.2638670609922155305224569e-188.
+2.0090511193460411160337891e+224.
+2.3340440774161371126924906e-193.
+3.2255482211312114132165077e-164.
+1.9177166536305262671761797e-16.
+6.6762277485439577092650143e+255.
+2.0981361326444801604493535e-289.
+4.9855199026486553981231910e+161.
+2.2787110335050254868679990e+209.
+1.2107275753382450588608793e+196.
+1.0342829513785960367928878e-61.
+1.2915271183891931487735769e-229.
+2.4770484858416096751058189e-26.
+5.8834787141711107801606624e+306.
+6.5540638159915622735595391e+239.
+3.4772851916209036111831665e+08.
+6.4480355622336432138210357e+34.
+2.8741000335340013539519876e+127.
+4.9146982550148414149902445e+182.
+9.1280712021813949903055688e+251.
+2.1418616591363449544562774e-279.
+1.0362180184894959399150510e+281.
+1.3556689511133099274998884e+184.
+1.0087159170105736810670136e+53.
+1.2219706762625801471822906e-109.
+7.2262465258265214070845326e-73.
+7.9239602604991647775709759e-133.
+2.8847708761132974833306905e+307.
+1.7037802615887541145925401e-12.
+1.0742678989774105760652274e-248.
+1.0088322516805741677752139e-41.
+7.5173181224960826765976378e+70.
+2.8486543433871786519475633e+186.
+6.3802563214099795252305133e+212.
+3.9417716501513654992184103e-94.
+3.6988333741496242192964188e-227.
+9.8024049836567287451290990e+124.
+5.6330153565227379105895564e-250.
+1.3660372744980724591432039e-201.
+1.8605966281797526412980546e+92.
+9.0552272726879373349173468e-119.
+1.2456704714849356923690308e+48.
+8.0953850995300705587031828e+207.
+4.3776508275901479602119258e+123.
+1.6855556257147624321863376e+70.
+1.2893001820269392627971161e-03.
+6.7210426659260031193210643e-239.
+3.1026695824331064796573506e+163.
+5.4376792797885493361792162e-259.
+9.7015289470101480315448149e-166.
+1.7920049920867948937730635e+133.
+2.8743155463358490489695270e-287.
+3.2809882731634037592575168e-195.
+8.6118433944293315034238988e+157.
+5.2108688074593239598743124e+33.
+1.8889250440209064184225673e-63.
+4.9844141270776763558387756e+06.
+9.6576770504249135558113279e+130.
+1.8530161533027035388093459e-253.
+4.0392916680871317794838307e-248.
+7.6490815378538759785536681e-222.
+3.4455356653552616747680406e+50.
+7.5087969967819713842527582e+105.
+4.2836361776315433942124781e+272.
+1.9263388869855029979124611e+156.
+4.2405721453072370002836943e+178.
+1.9484642445919718951385325e-276.
+1.8734081969728912000000000e+17.
+2.8940516295674526538944994e+240.
+4.3319803654251584341322711e+114.
+6.0933006462878921018067164e+109.
+2.6075886164371219083909748e-136.
+1.0153616425748073105282198e-291.
+5.2336541422926305079339497e+68.
+1.7233000720963831509673015e-200.
+5.0444614603456048839320094e+149.
+3.7076545971330514735013909e+290.
+1.1127945794395121517453095e+36.
+9.2426915359648059082031250e+11.
+5.2533302928361538190584409e-105.
+5.6178915751115478203491500e+125.
+6.7628222815300740947700390e+277.
+5.8273016200382073769837769e-10.
+1.7565098890358562203144330e+136.
+8.4222328279689448007331948e-30.
+2.3459290196002489211737768e+59.
+2.5081595496710542283321766e+79.
+9.4675511643255063148276757e+216.
+2.2063311336266132509549745e-59.
+1.2610861754822845430402692e-37.
+2.7041532510596421675646976e+25.
+2.4031383712512535232585771e-108.
+2.1499827774669038372882100e-22.
+2.7405965208201651643592369e-179.
+1.8542336005837174811840590e+31.
+2.0542615070661391138847613e+263.
+6.2463000927789766314468523e-02.
+3.1733297951657611591855246e-04.
+1.0765669937041190054455791e+35.
+6.2885209670860216524365052e+138.
+2.8689805042418936124762280e-288.
+1.8272040053110420697886361e+231.
+1.6420381765464600373091573e+289.
+6.0559507218805448286576033e+144.
+4.1877226433751424101658713e-286.
+3.0536068952806242417231564e+288.
+1.9277554002776541908980204e+28.
+1.5799939066762181761119366e-04.
+1.8743917240980036155108648e-155.
+2.0339534628483233504235656e+202.
+5.8133857249348334387200000e+20.
+4.5950722344969590000000000e+15.
+1.0252932377234532900008951e-225.
+2.7268880782838553485529402e-167.
+1.4623140785878385172869792e-210.
+1.0614782960184317949796848e+225.
+2.4568486243152450769737856e+63.
+1.3196885717727739525672558e+287.
+4.0915485490936680854922176e+258.
+1.3786850053926465061605437e-305.
+4.5350774432208757812500000e+13.
+3.8389991016588808656291914e+287.
+3.9396347068542250760318513e-107.
+2.3486785373354976613973105e+261.
+6.2387609197801166633751937e-11.
+1.0328573266281174427145415e-59.
+4.7179685749167881228527399e-04.
+1.2354232585125748129295098e+259.
+8.3853264169977021479894598e-29.
+9.4572432201552498080844143e+37.
+1.3344930761857313264685520e-126.
+1.0287837378814401600000000e+17.
+1.5324822080688293790471273e+183.
+3.6913938767859603900521156e-151.
+1.0807740074546391701975060e-290.
+4.3139440977413661236739929e-97.
+1.6970294364210480642731040e+124.
+1.5744319855206305171528250e+39.
+2.2905324978665183076177585e-238.
+1.7196778953736696619359121e+151.
+4.3888625235630291284457138e+158.
+3.6883341346755421243991864e+29.
+9.3658956308717918108344033e+116.
+6.4626107826300447430091649e+253.
+1.8862875810013062896433000e-52.
+1.7684851337110502290406760e-60.
+2.0243012515756401640486667e+69.
+9.7789400090529006207258107e-289.
+1.7436762350089123388029587e+294.
+4.3882188442690124800000000e+18.
+1.2601333162253728049754332e+89.
+1.6796447348182419811997322e+83.
+6.2901800993753214877787034e-170.
+7.4860964378276392817497253e+07.
+1.8460002119030610417417420e+241.
+1.1545918185938116955017797e-290.
+3.0017553534794881759596490e-215.
+1.5960500530445223828274268e+158.
+1.2124948224725861735182947e-154.
+3.0730667308850668478384830e+121.
+3.6866724306756125712447840e-59.
+3.4059814926014982494674577e+98.
+1.1436915212286048042363893e-10.
+3.9424503826953730816912708e+229.
+5.1687135082900734837690874e+197.
+2.2778847591170551039656234e-75.
+7.6277406679561940788224909e-38.
+8.8029102446160716403903875e+132.
+4.6552699322855073181510753e-135.
+2.7202658786317864870938396e-289.
+2.0781310780985193948859859e-38.
+1.8019625593232128482307510e+130.
+1.5593707280528000471029044e+215.
+2.0323424150362618285708640e-301.
+1.0777485403369308179893529e-78.
+4.9401290970355990438953726e-199.
+3.1182150574898764119893585e-234.
+9.6165779048119541371524220e-141.
+9.8708891241668173095528865e-281.
+1.9161264748366315318086349e-63.
+2.0940709638473898426153120e-88.
+1.7109153942937037523961030e+274.
+9.4783632474423456663518487e+34.
+1.5523036538654105153880956e-99.
+3.9152545451779392265912170e+46.
+6.3620320553317353033012363e+138.
+3.2292008919430946460334760e+91.
+3.3141570303299820109308945e+79.
+2.2309191216585987887511324e+237.
+7.4857724318299275618959732e+81.
+7.9760996842389418554181074e-86.
+3.2498882789352469706592360e-238.
+8.6436366901181114509080248e+203.
+9.7462414782175554624628126e+104.
+1.1420822529456058952227161e-281.
+2.3168222970703006740715665e+181.
+2.8522677461534228266153766e+247.
+9.4350947738955085688071965e-41.
+4.6432886908188017006832701e+81.
+4.5780123712776788570350210e+87.
+3.6254898808021285148908802e+287.
+3.4376584002058591695025354e-180.
+4.2991913719415459116849562e+26.
+3.0115361390123952945726891e-109.
+6.5950826454125078508600794e-199.
+6.7482481857690978289836981e-123.
+4.4399003248087375173277375e-68.
+5.9426204265305235934586414e-270.
+7.8614263097954373539170566e-136.
+1.7647273198166810728002537e+174.
+2.5161484799779026209837085e-40.
+2.3233167487965873575655253e+137.
+5.2196214074413346170346408e-298.
+2.4580543236259367175272424e-39.
+2.5730375381261529550407104e-265.
+2.4636684290183660724425393e+160.
+1.8152338029853438024066254e-94.
+3.1470792751102361829454766e-280.
+9.7915151232011718199852240e+229.
+2.4662988888549044772554130e-135.
+3.0927420407411100685185980e+34.
+2.3459848970484382260624943e+130.
+4.8661333753386867064426849e-51.
+8.4549442390727501314059874e-227.
+3.1828569525188114531964041e+279.
+6.1156707601690868511488116e-194.
+4.1426819150546480569267576e-70.
+3.6516149260540701731616420e-67.
+6.8771986108114977349517901e+43.
+8.3437729627502785828626383e+160.
+4.0070303319994055241320229e-108.
+3.8346320715710995483006129e-214.
+9.2073189070633475952171368e-127.
+1.2243679508574744503910400e+23.
+6.1241826598287582176434844e+88.
+1.1555051863624551707541105e+124.
+1.0042464440189470573552326e+111.
+1.3492486122203610774101356e+228.
+6.1484383147971289418245641e+171.
+1.0917922602894520350906195e+80.
+5.1634862055377761188686793e+278.
+4.2666899299352520195288378e+60.
+5.2243660199206391981836856e-123.
+6.6507591259919704995695611e+00.
+1.3980323899215374090355558e+289.
+1.4899106797816156778894000e-288.
+9.2426089765657587559738060e-94.
+4.4566978739488994363722247e-203.
+3.2157944589339019581322732e-04.
+3.2207233428004095831998528e-70.
+2.4920032943624630272694543e+174.
+1.4623675411046833415113138e+165.
+6.8894417628624905044113619e+135.
+4.3400058762842883202825972e+224.
+6.8211721135247267254065450e-63.
+1.5926038679305568654991467e+243.
+1.1620898060822574976985854e-247.
+6.3404929726617238935586040e+131.
+3.8677038249926629095939499e+293.
+4.8181016847220067652435265e+109.
+1.5253338984959568673734829e+168.
+4.4381123639925612465306221e-65.
+4.9640294440692245937651396e-275.
+1.9790099946792774602387341e-247.
+2.6298797770253795859229391e+102.
+4.7962554286097375541274287e+116.
+9.6891382742893648962957023e+218.
+1.2569413673898460585296232e+148.
+2.7331272277147256769838882e+286.
+7.9938327978968575364036484e-197.
+6.9077530545091011411220896e-72.
+3.1474907917961116780789942e-139.
+6.9846989995605750704710982e-305.
+6.1302320897364848782971637e-171.
+1.5023718288907385803558937e-249.
+3.5281191399065270682792862e+195.
+1.0251189275830737500000000e+14.
+1.3707959620096356918442646e-195.
+7.1629433778880004712527607e-05.
+2.0854559736631838016156402e+130.
+7.8753384884609716038430473e-13.
+7.8056088587620195094689373e+264.
+1.6216116834032689006844252e-166.
+3.8707253679800868781998066e+244.
+1.1201710078292840589241605e-51.
+8.4113865961374441057074325e-224.
+5.2187071794875975486464550e+167.
+1.1221561467009620826327873e-257.
+2.9056935620065306271823986e-225.
+8.3831138824142496122128217e+266.
+4.1497349068154594604498025e+164.
+3.0463742409862029276867777e+88.
+7.0784073021684919102057329e+233.
+1.9989399352536845604005390e-234.
+3.8430357549443778228723717e+244.
+7.3092155073858419861936620e-239.
+5.6569879868352720612881669e-31.
+8.3994764219286560019108531e+32.
+3.5680709545601248951199481e+66.
+1.1231526478261936583110852e+58.
+1.2371238238478237975870252e+231.
+3.5201150166028084042025668e-174.
+1.2934101296612768842611500e+124.
+8.5449284741880283201341213e-222.
+2.1839301180158113141334092e-206.
+2.1509917456457187639420244e-83.
+7.4316838789783101444757605e+125.
+6.2343897980251279916257125e-307.
+4.3865226502242964744382752e+294.
+3.3872775268483647991467625e-132.
+2.0983249526587749493395600e+64.
+2.6731296810166026659787088e-293.
+8.1847446231210745494552817e-12.
+1.2764867291699019614702323e+161.
+1.2345480092436014821693859e-97.
+1.2515865367846232270032658e-01.
+1.5659440690509532957852869e+73.
+5.5441600436628388706594706e+05.
+4.9928099274119318675423739e-250.
+1.9109473142211539182088006e-272.
+3.3919277690925924334455530e+225.
+1.3288883922473156727159545e+212.
+1.6769674334261766846371871e-23.
+2.4181914266637855118371078e+39.
+7.0363963825743134099665471e-40.
+5.9347783917503953012434889e-92.
+1.2712417396453596651554108e+07.
+1.3616435386365601228732498e+54.
+5.4927038772904660527706933e-38.
+9.9737774121372415121270594e+203.
+5.2468246533921284012959173e+291.
+5.0890287210601570016751949e-05.
+2.7663518327491048057180871e+221.
+2.3019376598610145293297321e-167.
+6.1403145192178946942801050e+271.
+6.4858771642183675094191781e-52.
+1.7056495684214485720566607e-73.
+3.9893646323746174445105462e-299.
+2.1580618062232941733796887e-162.
+1.4531939562145873747154136e-297.
+4.1486972250796454930721501e-218.
+1.0127835873548030993081439e-266.
+3.0322695016841751173724209e-193.
+1.8362578914546676402846112e-78.
+1.0089916148160329830383024e-263.
+1.9761875023377208436530762e-275.
+6.7709450309918942090270377e-02.
+1.9700392567882407197044164e-302.
+1.6950451907681876223234843e+171.
+1.4806725373928389748880444e+263.
+6.7600401771517308309697387e-236.
+2.7562594766533547790677319e+168.
+2.0355058220795578507930322e-296.
+4.6426526024806454101312846e+156.
+1.7913280306271772669122922e-280.
+1.9017546006208523832440364e+58.
+1.7513175799485854153866686e-06.
+3.7954907209331104891907278e+289.
+5.2510387824465941381207222e+121.
+4.7002775765742512165694236e-278.
+7.2747330840056296513047024e-287.
+8.3416488020030323264460601e-142.
+8.8904856885636088148296717e-13.
+1.6827528961955022168694995e+02.
+6.1337239294348633059379579e-57.
+3.3596697954163221178451467e+157.
+1.9209936913172182819673008e-172.
+1.6007853619872017631749671e+164.
+5.1606720203246572440084349e-169.
+1.5315981570775718912209024e-195.
+4.7925451273826343988953579e+192.
+1.5597730987367632827200212e+88.
+5.3309383451576566441986399e-183.
+6.1034879820443981830798121e-253.
+3.1840412224494598126032513e-283.
+2.7941952752445885266861513e+222.
+4.9640205750740839368443893e+223.
+3.9193551785536510689498227e-87.
+3.8836340795058838846656598e+234.
+4.1696498515550418393358957e+206.
+2.2350712079478341872543447e+174.
+1.4992810159027787998640757e-101.
+1.5931277531665860977265219e+173.
+1.9333357802093969307055343e+124.
+1.1885045762518267039566898e+124.
+8.5582903199885224627041398e+49.
+3.0407987353673819495691264e-286.
+1.7913472827921016095906451e+128.
+4.3535261489526191744774165e+126.
+3.2960937592709801110250264e-265.
+4.4206441762126913157412175e+251.
+1.1303773534952525515109301e+06.
+4.6842869583820586605972539e-37.
+1.2711287054278908691094952e-73.
+3.5719194029229399934408321e+252.
+1.0633228435903701398514237e-276.
+3.9173038990480459315493714e+190.
+3.1017819886903955361515556e+209.
+2.1138146509530130456393288e-230.
+4.7169146532094091429066136e+225.
+2.2083325574661339839571649e-212.
+2.4305064487553591968064724e+129.
+4.4983124983808258746334629e+152.
+3.7735713232181828563085925e+183.
+8.1353586009714425058568448e+82.
+1.4635332260148940763826851e+111.
+1.3023901996430522418732315e+92.
+3.3090983273680968747602012e-212.
+2.8094226567560071452448640e+105.
+9.0802821361090856956005998e-216.
+1.4644928503759859068101023e+290.
+5.5234125665168160720691362e-75.
+5.7782487733914776596941675e-64.
+4.9245826305279690137082204e-271.
+1.1400938985628273277375770e-246.
+1.5133461922460444541014797e-149.
+1.8144362250878865536529163e+40.
+1.1941508119590216185912368e-01.
+1.0242942161623132228851318e+08.
+7.1701951737987611325246704e-305.
+4.3508885331278208201195732e+92.
+8.1253727625220644196913556e-268.
+7.6590269841095394872959396e-144.
+5.2173691826261489928279476e-42.
+2.8120686230580042968750000e+13.
+3.7188169627909889533274977e+260.
+6.1120568200602709676531261e-59.
+1.1280876459042229529142539e-182.
+6.8555804833509070061551489e-40.
+4.6133183315928850090316892e-186.
+6.7046538160031469368371431e+134.
+1.8892820199074400275107687e-14.
+1.6080894169262749051372394e+62.
+1.7957345769131850276915171e-10.
+1.2134643487691305732123384e+286.
+3.8885153727968104305045318e-180.
+1.5549506593798175921655411e+277.
+3.5699856895995510225944658e+70.
+9.3039150618260458861583906e+100.
+9.7366849721221400953974757e+156.
+6.4264428509378234463137154e-130.
+1.9672430674052509231814563e+292.
+3.2992843442525948700671932e+219.
+2.0921884094336964989267007e-178.
+4.9737542877807617556284141e+40.
+6.1248914375088565302079612e+99.
+6.1839002829162613326860117e-118.
+9.2125693976611791646208273e+120.
+1.5691106282509040355304694e+66.
+1.6632357196808397965640343e-237.
+3.7570840370255457986199121e-112.
+2.5869201764306185924166190e+162.
+2.3254813599995365632916172e-210.
+7.5722071082727984106186280e-182.
+3.1333797187329482287168503e+07.
+3.4631617151263995522259119e-124.
+4.4505505789300319078630457e+77.
+2.7834468584089507026124721e-02.
+3.0409486047698588070008661e-219.
+1.3269433815228064629554711e+31.
+1.8731342751581068853017129e-207.
+5.9071116087888574289134994e+127.
+8.4433818592320824754127297e-225.
+1.8381844438923066413701318e+288.
+3.0184454657019258305756823e+210.
+1.1508866629115624370068092e+38.
+1.4580894488668100089163358e+60.
+1.3294933867595711990192818e-101.
+1.1380627425760601246395270e+64.
+6.5944553385606020314237918e-282.
+2.2533492783192685144749232e+300.
+8.3272035937474822998046875e+08.
+4.4976315458099746393944194e+205.
+4.1094154035530830078508659e+180.
+2.5158271557959386089617595e-17.
+4.1097380387935278035799554e+53.
+1.0010059180553018798828125e+12.
+1.8096831070390827608595784e+133.
+4.3298118658252681942358157e-237.
+2.6820683988334506700451407e-294.
+8.5278840278226518097010482e+96.
+3.4907139843676869451981048e+249.
+1.2192400510683256171213627e+212.
+6.7789682187377429621913096e+283.
+4.6184037774260654480481424e-102.
+2.4900326253680337662587769e-69.
+1.9620780855747686002242430e+217.
+1.2092452008780889374306242e+36.
+2.5021866197127322064201046e+252.
+1.9250437204911822572567714e-279.
+1.0782498783314412060364238e+178.
+1.5063245606455140078603271e+263.
+1.1261631537457284820436152e-173.
+1.5376488406421243166999805e-20.
+4.8326360967323080502984531e+291.
+7.3951863160313736733573102e-275.
+7.2641508539628946694628057e-75.
+1.5900081838080843964730734e+263.
+1.5375881046216687992581913e+184.
+7.0365050428380789934467527e+117.
+3.5208652321994970851983292e-160.
+2.2698023301905779138444193e+72.
+8.9937377521973452857107760e+190.
+3.3623388973026288317021935e-306.
+7.2565587727376961169056813e+00.
+6.0841627137060631574996356e-14.
+1.2255149725452948447696401e+104.
+1.1950552297790469651644483e-246.
+1.0557126844758346065811819e-128.
+5.9979267281865554783969781e-175.
+8.5261154335488114341723758e+169.
+3.2943684623977164032965096e+257.
+2.9636262716979234609138736e-137.
+1.4901452558877062250342428e+249.
+2.0409406153914362684065417e-51.
+3.1638920326346707679649609e-293.
+1.0787221589313895476139427e-180.
+6.1218210091280898728664447e-06.
+1.5309748755056345085220013e+186.
+7.5336942222891894505832322e+291.
+3.8058003828402487455925897e-22.
+2.5741343878867646490932212e+86.
+2.9643788985265650907389343e+66.
+3.4344539944242660472693200e-297.
+1.2075927997492895236891557e-260.
+6.6271651667618755650920661e+115.
+9.7587493210787819896638972e+142.
+1.6535582290304309081054506e-174.
+1.2258673125709878228650328e+124.
+1.1900071311323810449151068e+236.
+2.7152766835289521887152207e+80.
+2.8672698767264375249175083e-240.
+1.0354836842491846905481742e-12.
+7.3537540538557473951937433e-65.
+1.6790303661406536572219255e-07.
+7.6726474406340755193856000e+22.
+1.1835778544008184303999901e-190.
+7.7400261093398379118843973e+184.
+7.5418154350165400009124478e+242.
+1.0195579651
<TRUNCATED>
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/simple.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/simple.eterm b/src/jiffy/test/cases/simple.eterm
new file mode 100644
index 0000000..fdc4deb
--- /dev/null
+++ b/src/jiffy/test/cases/simple.eterm
@@ -0,0 +1,5 @@
+{[
+ {<<"this">>, <<"is">>},
+ {<<"really">>, <<"simple">>},
+ {<<"json">>, <<"right?">>}
+]}.
\ No newline at end of file
[03/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/010-short-doubles.t
----------------------------------------------------------------------
diff --git a/src/jiffy/test/010-short-doubles.t b/src/jiffy/test/010-short-doubles.t
new file mode 100755
index 0000000..4aac375
--- /dev/null
+++ b/src/jiffy/test/010-short-doubles.t
@@ -0,0 +1,29 @@
+#! /usr/bin/env escript
+% This file is part of Jiffy released under the MIT license.
+% See the LICENSE file for more information.
+
+filename() -> "test/cases/short-doubles.txt".
+
+main([]) ->
+ code:add_pathz("ebin"),
+ code:add_pathz("test"),
+
+ etap:plan(100000),
+
+ etap:diag("Loading test cases..."),
+ {ok, Cases} = file:consult(filename()),
+
+ etap:diag("Running tests..."),
+ ok = run_tests(Cases),
+
+ etap:end_tests().
+
+
+run_tests([]) ->
+ ok;
+run_tests([Double | Rest]) ->
+ RoundTrip = jiffy:decode(jiffy:encode(Double)),
+ Desc = lists:flatten(io_lib:format("~e", [Double])),
+ etap:is(RoundTrip, Double, "Roundtrip: " ++ Desc),
+ run_tests(Rest).
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/array.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/array.eterm b/src/jiffy/test/cases/array.eterm
new file mode 100644
index 0000000..8a9688e
--- /dev/null
+++ b/src/jiffy/test/cases/array.eterm
@@ -0,0 +1,16 @@
+[
+ <<"foo">>,
+ <<"bar">>,
+ <<"baz">>,
+ true,
+ false,
+ null,
+ {[{<<"key">>, <<"value">>}]},
+ [
+ null,
+ null,
+ null,
+ []
+ ],
+ <<"\n\r\\">>
+].
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/array.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/array.json b/src/jiffy/test/cases/array.json
new file mode 100644
index 0000000..f76058d
--- /dev/null
+++ b/src/jiffy/test/cases/array.json
@@ -0,0 +1,6 @@
+["foo",
+ "bar", "baz",
+ true,false,null,{"key":"value"},
+ [null,null,null,[]],
+ "\n\r\\"
+]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/array_close.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/array_close.eterm b/src/jiffy/test/cases/array_close.eterm
new file mode 100644
index 0000000..4aa294e
--- /dev/null
+++ b/src/jiffy/test/cases/array_close.eterm
@@ -0,0 +1 @@
+{error,{1,invalid_json}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/array_close.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/array_close.json b/src/jiffy/test/cases/array_close.json
new file mode 100644
index 0000000..079b579
--- /dev/null
+++ b/src/jiffy/test/cases/array_close.json
@@ -0,0 +1 @@
+]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/array_open.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/array_open.eterm b/src/jiffy/test/cases/array_open.eterm
new file mode 100644
index 0000000..9fa573a
--- /dev/null
+++ b/src/jiffy/test/cases/array_open.eterm
@@ -0,0 +1 @@
+{error,{3,truncated_json}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/array_open.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/array_open.json b/src/jiffy/test/cases/array_open.json
new file mode 100644
index 0000000..558ed37
--- /dev/null
+++ b/src/jiffy/test/cases/array_open.json
@@ -0,0 +1 @@
+[
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/bogus_char.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/bogus_char.eterm b/src/jiffy/test/cases/bogus_char.eterm
new file mode 100644
index 0000000..9ecbac7
--- /dev/null
+++ b/src/jiffy/test/cases/bogus_char.eterm
@@ -0,0 +1 @@
+{error,{97,invalid_literal}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/bogus_char.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/bogus_char.json b/src/jiffy/test/cases/bogus_char.json
new file mode 100644
index 0000000..8163bd8
--- /dev/null
+++ b/src/jiffy/test/cases/bogus_char.json
@@ -0,0 +1,4 @@
+["this","is","what","should","be",
+ "a happy bit of json",
+ "but someone, misspelled \"true\"", ture,
+ "who says JSON is easy for humans to generate?"]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/codepoints_from_unicode_org.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/codepoints_from_unicode_org.eterm b/src/jiffy/test/cases/codepoints_from_unicode_org.eterm
new file mode 100644
index 0000000..086d058
--- /dev/null
+++ b/src/jiffy/test/cases/codepoints_from_unicode_org.eterm
@@ -0,0 +1 @@
+<<77, 208, 176, 228, 186, 140, 240, 144, 140, 130>>.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/codepoints_from_unicode_org.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/codepoints_from_unicode_org.json b/src/jiffy/test/cases/codepoints_from_unicode_org.json
new file mode 100644
index 0000000..f91f3be
--- /dev/null
+++ b/src/jiffy/test/cases/codepoints_from_unicode_org.json
@@ -0,0 +1 @@
+"\u004d\u0430\u4e8c\ud800\udf02"
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/deep_arrays.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/deep_arrays.eterm b/src/jiffy/test/cases/deep_arrays.eterm
new file mode 100644
index 0000000..2721754
--- /dev/null
+++ b/src/jiffy/test/cases/deep_arrays.eterm
@@ -0,0 +1 @@
+[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]].
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/deep_arrays.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/deep_arrays.json b/src/jiffy/test/cases/deep_arrays.json
new file mode 100644
index 0000000..82d1b0d
--- /dev/null
+++ b/src/jiffy/test/cases/deep_arrays.json
@@ -0,0 +1 @@
+[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/difficult_json_c_test_case.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/difficult_json_c_test_case.eterm b/src/jiffy/test/cases/difficult_json_c_test_case.eterm
new file mode 100644
index 0000000..591fafe
--- /dev/null
+++ b/src/jiffy/test/cases/difficult_json_c_test_case.eterm
@@ -0,0 +1,19 @@
+{[
+ {<<"glossary">>, {[
+ {<<"title">>, <<"example glossary">>},
+ {<<"GlossDiv">>, {[
+ {<<"title">>, <<"S">>},
+ {<<"GlossList">>, [
+ {[
+ {<<"ID">>, <<"SGML">>},
+ {<<"SortAs">>, <<"SGML">>},
+ {<<"GlossTerm">>, <<"Standard Generalized Markup Language">>},
+ {<<"Acronym">>, <<"SGML">>},
+ {<<"Abbrev">>, <<"ISO 8879:1986">>},
+ {<<"GlossDef">>, <<"A meta-markup language, used to create markup languages such as DocBook.">>},
+ {<<"GlossSeeAlso">>, [<<"GML">>, <<"XML">>, <<"markup">>]}
+ ]}
+ ]}
+ ]}}
+ ]}}
+]}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/difficult_json_c_test_case.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/difficult_json_c_test_case.json b/src/jiffy/test/cases/difficult_json_c_test_case.json
new file mode 100644
index 0000000..6998f55
--- /dev/null
+++ b/src/jiffy/test/cases/difficult_json_c_test_case.json
@@ -0,0 +1 @@
+{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": [ { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML", "markup"] } ] } } }
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/doubles.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/doubles.eterm b/src/jiffy/test/cases/doubles.eterm
new file mode 100644
index 0000000..76a7f07
--- /dev/null
+++ b/src/jiffy/test/cases/doubles.eterm
@@ -0,0 +1 @@
+[10, 10, 3.141569, 1000].
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/doubles.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/doubles.json b/src/jiffy/test/cases/doubles.json
new file mode 100644
index 0000000..626f21c
--- /dev/null
+++ b/src/jiffy/test/cases/doubles.json
@@ -0,0 +1 @@
+[ 0.1e2, 1e1, 3.141569, 10000000000000e-10]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/empty_array.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/empty_array.eterm b/src/jiffy/test/cases/empty_array.eterm
new file mode 100644
index 0000000..2600237
--- /dev/null
+++ b/src/jiffy/test/cases/empty_array.eterm
@@ -0,0 +1 @@
+[].
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/empty_array.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/empty_array.json b/src/jiffy/test/cases/empty_array.json
new file mode 100644
index 0000000..0637a08
--- /dev/null
+++ b/src/jiffy/test/cases/empty_array.json
@@ -0,0 +1 @@
+[]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/empty_string.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/empty_string.eterm b/src/jiffy/test/cases/empty_string.eterm
new file mode 100644
index 0000000..e0f2023
--- /dev/null
+++ b/src/jiffy/test/cases/empty_string.eterm
@@ -0,0 +1 @@
+<<"">>.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/empty_string.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/empty_string.json b/src/jiffy/test/cases/empty_string.json
new file mode 100644
index 0000000..e16c76d
--- /dev/null
+++ b/src/jiffy/test/cases/empty_string.json
@@ -0,0 +1 @@
+""
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/escaped_bulgarian.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/escaped_bulgarian.eterm b/src/jiffy/test/cases/escaped_bulgarian.eterm
new file mode 100644
index 0000000..15287cc
--- /dev/null
+++ b/src/jiffy/test/cases/escaped_bulgarian.eterm
@@ -0,0 +1,6 @@
+[
+ <<208, 148, 208, 176>>,
+ <<208, 156, 209, 131>>,
+ <<208, 149, 208, 177, 208, 176>>,
+ <<208, 156, 208, 176, 208, 185, 208, 186, 208, 176, 209, 130, 208, 176>>
+].
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/escaped_bulgarian.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/escaped_bulgarian.json b/src/jiffy/test/cases/escaped_bulgarian.json
new file mode 100644
index 0000000..9ce1d1c
--- /dev/null
+++ b/src/jiffy/test/cases/escaped_bulgarian.json
@@ -0,0 +1,4 @@
+["\u0414\u0430",
+ "\u041c\u0443",
+ "\u0415\u0431\u0430",
+ "\u041c\u0430\u0439\u043a\u0430\u0442\u0430"]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/escaped_foobar.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/escaped_foobar.eterm b/src/jiffy/test/cases/escaped_foobar.eterm
new file mode 100644
index 0000000..de9c37d
--- /dev/null
+++ b/src/jiffy/test/cases/escaped_foobar.eterm
@@ -0,0 +1 @@
+<<"foobar">>.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/escaped_foobar.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/escaped_foobar.json b/src/jiffy/test/cases/escaped_foobar.json
new file mode 100644
index 0000000..2c0e25f
--- /dev/null
+++ b/src/jiffy/test/cases/escaped_foobar.json
@@ -0,0 +1 @@
+"\u0066\u006f\u006f\u0062\u0061\u0072"
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/false.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/false.eterm b/src/jiffy/test/cases/false.eterm
new file mode 100644
index 0000000..aca5de7
--- /dev/null
+++ b/src/jiffy/test/cases/false.eterm
@@ -0,0 +1 @@
+false.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/false.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/false.json b/src/jiffy/test/cases/false.json
new file mode 100644
index 0000000..c508d53
--- /dev/null
+++ b/src/jiffy/test/cases/false.json
@@ -0,0 +1 @@
+false
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/false_then_garbage.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/false_then_garbage.eterm b/src/jiffy/test/cases/false_then_garbage.eterm
new file mode 100644
index 0000000..fc13df2
--- /dev/null
+++ b/src/jiffy/test/cases/false_then_garbage.eterm
@@ -0,0 +1 @@
+{error,{6,invalid_trailing_data}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/false_then_garbage.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/false_then_garbage.json b/src/jiffy/test/cases/false_then_garbage.json
new file mode 100644
index 0000000..78f4e96
--- /dev/null
+++ b/src/jiffy/test/cases/false_then_garbage.json
@@ -0,0 +1 @@
+falsex
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/four_byte_utf8.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/four_byte_utf8.eterm b/src/jiffy/test/cases/four_byte_utf8.eterm
new file mode 100644
index 0000000..20da680
--- /dev/null
+++ b/src/jiffy/test/cases/four_byte_utf8.eterm
@@ -0,0 +1 @@
+{[{<<"U+10ABCD">>, <<244, 138, 175, 141>>}]}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/four_byte_utf8.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/four_byte_utf8.json b/src/jiffy/test/cases/four_byte_utf8.json
new file mode 100644
index 0000000..582c575
--- /dev/null
+++ b/src/jiffy/test/cases/four_byte_utf8.json
@@ -0,0 +1,2 @@
+{ "U+10ABCD": "" }
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/integers.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/integers.eterm b/src/jiffy/test/cases/integers.eterm
new file mode 100644
index 0000000..bd642e4
--- /dev/null
+++ b/src/jiffy/test/cases/integers.eterm
@@ -0,0 +1,13 @@
+[
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 123456789,
+ -123456789,
+ 2147483647,
+ -2147483647
+].
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/integers.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/integers.json b/src/jiffy/test/cases/integers.json
new file mode 100644
index 0000000..c50e4c9
--- /dev/null
+++ b/src/jiffy/test/cases/integers.json
@@ -0,0 +1,3 @@
+[ 1,2,3,4,5,6,7,
+ 123456789 , -123456789,
+ 2147483647, -2147483647 ]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/invalid_utf8.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/invalid_utf8.eterm b/src/jiffy/test/cases/invalid_utf8.eterm
new file mode 100644
index 0000000..f0baaf0
--- /dev/null
+++ b/src/jiffy/test/cases/invalid_utf8.eterm
@@ -0,0 +1 @@
+{error,{10,invalid_string}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/invalid_utf8.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/invalid_utf8.json b/src/jiffy/test/cases/invalid_utf8.json
new file mode 100644
index 0000000..12f1718
--- /dev/null
+++ b/src/jiffy/test/cases/invalid_utf8.json
@@ -0,0 +1 @@
+["Да М� Еба Майката"]
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/isolated_surrogate_marker.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/isolated_surrogate_marker.eterm b/src/jiffy/test/cases/isolated_surrogate_marker.eterm
new file mode 100644
index 0000000..06113c7
--- /dev/null
+++ b/src/jiffy/test/cases/isolated_surrogate_marker.eterm
@@ -0,0 +1 @@
+{error,{8,invalid_string}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/isolated_surrogate_marker.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/isolated_surrogate_marker.json b/src/jiffy/test/cases/isolated_surrogate_marker.json
new file mode 100644
index 0000000..36959f4
--- /dev/null
+++ b/src/jiffy/test/cases/isolated_surrogate_marker.json
@@ -0,0 +1 @@
+"\ud800"
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/leading_zero_in_number.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/leading_zero_in_number.eterm b/src/jiffy/test/cases/leading_zero_in_number.eterm
new file mode 100644
index 0000000..5bc5d8c
--- /dev/null
+++ b/src/jiffy/test/cases/leading_zero_in_number.eterm
@@ -0,0 +1 @@
+{error,{17,invalid_json}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/leading_zero_in_number.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/leading_zero_in_number.json b/src/jiffy/test/cases/leading_zero_in_number.json
new file mode 100644
index 0000000..959f5ba
--- /dev/null
+++ b/src/jiffy/test/cases/leading_zero_in_number.json
@@ -0,0 +1 @@
+{ "bad thing": 01 }
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/lonely_minus_sign.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/lonely_minus_sign.eterm b/src/jiffy/test/cases/lonely_minus_sign.eterm
new file mode 100644
index 0000000..5f172a4
--- /dev/null
+++ b/src/jiffy/test/cases/lonely_minus_sign.eterm
@@ -0,0 +1 @@
+{error,{83,invalid_number}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/lonely_minus_sign.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/lonely_minus_sign.json b/src/jiffy/test/cases/lonely_minus_sign.json
new file mode 100644
index 0000000..c343683
--- /dev/null
+++ b/src/jiffy/test/cases/lonely_minus_sign.json
@@ -0,0 +1,7 @@
+[
+ "foo", true,
+ true, "blue",
+ "baby where are you?", "oh boo hoo!",
+ -
+]
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/lonely_number.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/lonely_number.eterm b/src/jiffy/test/cases/lonely_number.eterm
new file mode 100644
index 0000000..b52af81
--- /dev/null
+++ b/src/jiffy/test/cases/lonely_number.eterm
@@ -0,0 +1 @@
+123456789.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/lonely_number.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/lonely_number.json b/src/jiffy/test/cases/lonely_number.json
new file mode 100644
index 0000000..e2e107a
--- /dev/null
+++ b/src/jiffy/test/cases/lonely_number.json
@@ -0,0 +1 @@
+123456789
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/map_close.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/map_close.eterm b/src/jiffy/test/cases/map_close.eterm
new file mode 100644
index 0000000..4aa294e
--- /dev/null
+++ b/src/jiffy/test/cases/map_close.eterm
@@ -0,0 +1 @@
+{error,{1,invalid_json}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/map_close.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/map_close.json b/src/jiffy/test/cases/map_close.json
new file mode 100644
index 0000000..5c34318
--- /dev/null
+++ b/src/jiffy/test/cases/map_close.json
@@ -0,0 +1 @@
+}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/map_open.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/map_open.eterm b/src/jiffy/test/cases/map_open.eterm
new file mode 100644
index 0000000..9fa573a
--- /dev/null
+++ b/src/jiffy/test/cases/map_open.eterm
@@ -0,0 +1 @@
+{error,{3,truncated_json}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/map_open.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/map_open.json b/src/jiffy/test/cases/map_open.json
new file mode 100644
index 0000000..98232c6
--- /dev/null
+++ b/src/jiffy/test/cases/map_open.json
@@ -0,0 +1 @@
+{
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/missing_integer_after_decimal_point.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/missing_integer_after_decimal_point.eterm b/src/jiffy/test/cases/missing_integer_after_decimal_point.eterm
new file mode 100644
index 0000000..046f3c7
--- /dev/null
+++ b/src/jiffy/test/cases/missing_integer_after_decimal_point.eterm
@@ -0,0 +1 @@
+{error,{4,invalid_number}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/missing_integer_after_decimal_point.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/missing_integer_after_decimal_point.json b/src/jiffy/test/cases/missing_integer_after_decimal_point.json
new file mode 100644
index 0000000..2369f4b
--- /dev/null
+++ b/src/jiffy/test/cases/missing_integer_after_decimal_point.json
@@ -0,0 +1 @@
+10.e2
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/missing_integer_after_exponent.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/missing_integer_after_exponent.eterm b/src/jiffy/test/cases/missing_integer_after_exponent.eterm
new file mode 100644
index 0000000..046f3c7
--- /dev/null
+++ b/src/jiffy/test/cases/missing_integer_after_exponent.eterm
@@ -0,0 +1 @@
+{error,{4,invalid_number}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/missing_integer_after_exponent.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/missing_integer_after_exponent.json b/src/jiffy/test/cases/missing_integer_after_exponent.json
new file mode 100644
index 0000000..a62b45d
--- /dev/null
+++ b/src/jiffy/test/cases/missing_integer_after_exponent.json
@@ -0,0 +1 @@
+10e
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/non_utf8_char_in_string.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/non_utf8_char_in_string.eterm b/src/jiffy/test/cases/non_utf8_char_in_string.eterm
new file mode 100644
index 0000000..0ca5740
--- /dev/null
+++ b/src/jiffy/test/cases/non_utf8_char_in_string.eterm
@@ -0,0 +1 @@
+{error,{125,invalid_string}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/non_utf8_char_in_string.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/non_utf8_char_in_string.json b/src/jiffy/test/cases/non_utf8_char_in_string.json
new file mode 100644
index 0000000..253a664
--- /dev/null
+++ b/src/jiffy/test/cases/non_utf8_char_in_string.json
@@ -0,0 +1 @@
+{"CoreletAPIVersion":2,"CoreletType":"standalone","documentation":"A corelet that provides the capability to upload a folder�s contents into a user�s locker.","functions":[{"documentation":"Displays a dialog box that allows user to select a folder on the local system.","name":"ShowBrowseDialog","parameters":[{"documentation":"The callback function for results.","name":"callback","required":true,"type":"callback"}]},{"documentation":"Uploads all mp3 files in the folder provided.","name":"UploadFolder","parameters":[{"documentation":"The path to upload mp3 files from.","name":"path","required":true,"type":"string"},{"documentation":"The callback function for progress.","name":"callback","required":true,"type":"callback"}]},{"documentation":"Returns the server name to the current locker service.","name":"GetLockerService","parameters":[]},{"documentation":"Changes the name of the locker service.","name":"SetLockerService","parameters":[{"documentation":"The value of the locker serv
ice to set active.","name":"LockerService","required":true,"type":"string"}]},{"documentation":"Downloads locker files to the suggested folder.","name":"DownloadFile","parameters":[{"documentation":"The origin path of the locker file.","name":"path","required":true,"type":"string"},{"documentation":"The Window destination path of the locker file.","name":"destination","required":true,"type":"integer"},{"documentation":"The callback function for progress.","name":"callback","required":true,"type":"callback"}]}],"name":"LockerUploader","version":{"major":0,"micro":1,"minor":0},"versionString":"0.0.1"}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/null.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/null.eterm b/src/jiffy/test/cases/null.eterm
new file mode 100644
index 0000000..bed1002
--- /dev/null
+++ b/src/jiffy/test/cases/null.eterm
@@ -0,0 +1 @@
+null.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/null.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/null.json b/src/jiffy/test/cases/null.json
new file mode 100644
index 0000000..19765bd
--- /dev/null
+++ b/src/jiffy/test/cases/null.json
@@ -0,0 +1 @@
+null
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/null_then_garbage.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/null_then_garbage.eterm b/src/jiffy/test/cases/null_then_garbage.eterm
new file mode 100644
index 0000000..30b0113
--- /dev/null
+++ b/src/jiffy/test/cases/null_then_garbage.eterm
@@ -0,0 +1 @@
+{error,{5,invalid_trailing_data}}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/null_then_garbage.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/null_then_garbage.json b/src/jiffy/test/cases/null_then_garbage.json
new file mode 100644
index 0000000..7b65b35
--- /dev/null
+++ b/src/jiffy/test/cases/null_then_garbage.json
@@ -0,0 +1 @@
+nullx
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/nulls_and_bools.eterm
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/nulls_and_bools.eterm b/src/jiffy/test/cases/nulls_and_bools.eterm
new file mode 100644
index 0000000..68544ed
--- /dev/null
+++ b/src/jiffy/test/cases/nulls_and_bools.eterm
@@ -0,0 +1,5 @@
+{[
+ {<<"boolean, true">>, true},
+ {<<"boolean, false">>, false},
+ {<<"null">>, null}
+]}.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/test/cases/nulls_and_bools.json
----------------------------------------------------------------------
diff --git a/src/jiffy/test/cases/nulls_and_bools.json b/src/jiffy/test/cases/nulls_and_bools.json
new file mode 100644
index 0000000..65eb01f
--- /dev/null
+++ b/src/jiffy/test/cases/nulls_and_bools.json
@@ -0,0 +1,5 @@
+{
+ "boolean, true": true,
+ "boolean, false": false,
+ "null": null
+}
[10/12] Replace ejson with jiffy
Posted by rn...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/src/ejson.erl
----------------------------------------------------------------------
diff --git a/src/ejson/src/ejson.erl b/src/ejson/src/ejson.erl
deleted file mode 100644
index 72bb6c1..0000000
--- a/src/ejson/src/ejson.erl
+++ /dev/null
@@ -1,168 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(ejson).
--export([encode/1, decode/1]).
--on_load(init/0).
-
-init() ->
- SoName = case code:priv_dir(ejson) of
- {error, bad_name} ->
- case filelib:is_dir(filename:join(["..", priv])) of
- true ->
- filename:join(["..", priv, ejson]);
- false ->
- filename:join([priv, ejson])
- end;
- Dir ->
- filename:join(Dir, ejson)
- end,
- (catch erlang:load_nif(SoName, 0)),
- case erlang:system_info(otp_release) of
- "R13B03" -> true;
- _ -> ok
- end.
-
-
-decode(undefined) ->
- throw({invalid_json, undefined});
-decode(IoList) ->
- try
- nif_decode(IoList)
- catch exit:ejson_nif_not_loaded ->
- erl_decode(IoList)
- end.
-
-encode(EJson) ->
- try
- nif_encode(EJson)
- catch exit:ejson_nif_not_loaded ->
- erl_encode(EJson)
- end.
-
-
-nif_decode(IoList) ->
- case reverse_tokens(IoList) of
- {ok, ReverseTokens} ->
- [[EJson]] = make_ejson(ReverseTokens, [[]]),
- EJson;
- Error ->
- throw({invalid_json, {Error, IoList}})
- end.
-
-
-erl_decode(IoList) ->
- try
- (mochijson2:decoder([{object_hook, fun({struct, L}) -> {L} end}]))(IoList)
- catch _Type:Error ->
- throw({invalid_json, {Error, IoList}})
- end.
-
-
-nif_encode(EJson) ->
- RevList = encode_rev(EJson),
- final_encode(lists:reverse(lists:flatten([RevList]))).
-
-
-erl_encode(EJson) ->
- Opts = [{handler, fun mochi_encode_handler/1}],
- iolist_to_binary((mochijson2:encoder(Opts))(EJson)).
-
-mochi_encode_handler({L}) when is_list(L) ->
- {struct, L};
-mochi_encode_handler(Bad) ->
- exit({json_encode, {bad_term, Bad}}).
-
-
-% Encode the json into a reverse list that's almost an iolist
-% everything in the list is the final output except for tuples with
-% {0, Strings} and {1, Floats}, which are to be converted to strings
-% inside the NIF.
-encode_rev(true) ->
- <<"true">>;
-encode_rev(false) ->
- <<"false">>;
-encode_rev(null) ->
- <<"null">>;
-encode_rev(I) when is_integer(I) ->
- list_to_binary(integer_to_list(I));
-encode_rev(S) when is_binary(S) ->
- {0, S};
-encode_rev(S) when is_atom(S) ->
- {0, list_to_binary(atom_to_list(S))};
-encode_rev(F) when is_float(F) ->
- {1, F};
-encode_rev({Props}) when is_list(Props) ->
- encode_proplist_rev(Props, [<<"{">>]);
-encode_rev(Array) when is_list(Array) ->
- encode_array_rev(Array, [<<"[">>]);
-encode_rev(Bad) ->
- throw({json_encode, {bad_term, Bad}}).
-
-
-encode_array_rev([], Acc) ->
- [<<"]">> | Acc];
-encode_array_rev([Val | Rest], [<<"[">>]) ->
- encode_array_rev(Rest, [encode_rev(Val), <<"[">>]);
-encode_array_rev([Val | Rest], Acc) ->
- encode_array_rev(Rest, [encode_rev(Val), <<",">> | Acc]).
-
-
-encode_proplist_rev([], Acc) ->
- [<<"}">> | Acc];
-encode_proplist_rev([{Key,Val} | Rest], [<<"{">>]) ->
- encode_proplist_rev(
- Rest, [encode_rev(Val), <<":">>, {0, as_binary(Key)}, <<"{">>]);
-encode_proplist_rev([{Key,Val} | Rest], Acc) ->
- encode_proplist_rev(
- Rest, [encode_rev(Val), <<":">>, {0, as_binary(Key)}, <<",">> | Acc]).
-
-as_binary(B) when is_binary(B) ->
- B;
-as_binary(A) when is_atom(A) ->
- list_to_binary(atom_to_list(A));
-as_binary(L) when is_list(L) ->
- list_to_binary(L).
-
-
-make_ejson([], Stack) ->
- Stack;
-make_ejson([0 | RevEvs], [ArrayValues, PrevValues | RestStack]) ->
- % 0 ArrayStart
- make_ejson(RevEvs, [[ArrayValues | PrevValues] | RestStack]);
-make_ejson([1 | RevEvs], Stack) ->
- % 1 ArrayEnd
- make_ejson(RevEvs, [[] | Stack]);
-make_ejson([2 | RevEvs], [ObjValues, PrevValues | RestStack]) ->
- % 2 ObjectStart
- make_ejson(RevEvs, [[{ObjValues} | PrevValues] | RestStack]);
-make_ejson([3 | RevEvs], Stack) ->
- % 3 ObjectEnd
- make_ejson(RevEvs, [[] | Stack]);
-make_ejson([{0, Value} | RevEvs], [Vals | RestStack] = _Stack) ->
- % {0, IntegerString}
- make_ejson(RevEvs, [[list_to_integer(binary_to_list(Value)) | Vals] | RestStack]);
-make_ejson([{1, Value} | RevEvs], [Vals | RestStack] = _Stack) ->
- % {1, FloatString}
- make_ejson(RevEvs, [[list_to_float(binary_to_list(Value)) | Vals] | RestStack]);
-make_ejson([{3, String} | RevEvs], [[PrevValue|RestObject] | RestStack] = _Stack) ->
- % {3 , ObjectKey}
- make_ejson(RevEvs, [[{String, PrevValue}|RestObject] | RestStack]);
-make_ejson([Value | RevEvs], [Vals | RestStack] = _Stack) ->
- make_ejson(RevEvs, [[Value | Vals] | RestStack]).
-
-
-reverse_tokens(_) ->
- exit(ejson_nif_not_loaded).
-
-final_encode(_) ->
- exit(ejson_nif_not_loaded).
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/src/mochijson2.erl
----------------------------------------------------------------------
diff --git a/src/ejson/src/mochijson2.erl b/src/ejson/src/mochijson2.erl
deleted file mode 100644
index 954a07d..0000000
--- a/src/ejson/src/mochijson2.erl
+++ /dev/null
@@ -1,849 +0,0 @@
-%% @author Bob Ippolito <bo...@mochimedia.com>
-%% @copyright 2007 Mochi Media, Inc.
-
-%% @doc Yet another JSON (RFC 4627) library for Erlang. mochijson2 works
-%% with binaries as strings, arrays as lists (without an {array, _})
-%% wrapper and it only knows how to decode UTF-8 (and ASCII).
-%%
-%% JSON terms are decoded as follows (javascript -> erlang):
-%% <ul>
-%% <li>{"key": "value"} ->
-%% {struct, [{<<"key">>, <<"value">>}]}</li>
-%% <li>["array", 123, 12.34, true, false, null] ->
-%% [<<"array">>, 123, 12.34, true, false, null]
-%% </li>
-%% </ul>
-%% <ul>
-%% <li>Strings in JSON decode to UTF-8 binaries in Erlang</li>
-%% <li>Objects decode to {struct, PropList}</li>
-%% <li>Numbers decode to integer or float</li>
-%% <li>true, false, null decode to their respective terms.</li>
-%% </ul>
-%% The encoder will accept the same format that the decoder will produce,
-%% but will also allow additional cases for leniency:
-%% <ul>
-%% <li>atoms other than true, false, null will be considered UTF-8
-%% strings (even as a proplist key)
-%% </li>
-%% <li>{json, IoList} will insert IoList directly into the output
-%% with no validation
-%% </li>
-%% <li>{array, Array} will be encoded as Array
-%% (legacy mochijson style)
-%% </li>
-%% <li>A non-empty raw proplist will be encoded as an object as long
-%% as the first pair does not have an atom key of json, struct,
-%% or array
-%% </li>
-%% </ul>
-
--module(mochijson2).
--author('bob@mochimedia.com').
--export([encoder/1, encode/1]).
--export([decoder/1, decode/1]).
-
-% This is a macro to placate syntax highlighters..
--define(Q, $\").
--define(ADV_COL(S, N), S#decoder{offset=N+S#decoder.offset,
- column=N+S#decoder.column}).
--define(INC_COL(S), S#decoder{offset=1+S#decoder.offset,
- column=1+S#decoder.column}).
--define(INC_LINE(S), S#decoder{offset=1+S#decoder.offset,
- column=1,
- line=1+S#decoder.line}).
--define(INC_CHAR(S, C),
- case C of
- $\n ->
- S#decoder{column=1,
- line=1+S#decoder.line,
- offset=1+S#decoder.offset};
- _ ->
- S#decoder{column=1+S#decoder.column,
- offset=1+S#decoder.offset}
- end).
--define(IS_WHITESPACE(C),
- (C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
-
-%% @type iolist() = [char() | binary() | iolist()]
-%% @type iodata() = iolist() | binary()
-%% @type json_string() = atom | binary()
-%% @type json_number() = integer() | float()
-%% @type json_array() = [json_term()]
-%% @type json_object() = {struct, [{json_string(), json_term()}]}
-%% @type json_iolist() = {json, iolist()}
-%% @type json_term() = json_string() | json_number() | json_array() |
-%% json_object() | json_iolist()
-
--record(encoder, {handler=null,
- utf8=false}).
-
--record(decoder, {object_hook=null,
- offset=0,
- line=1,
- column=1,
- state=null}).
-
-%% @spec encoder([encoder_option()]) -> function()
-%% @doc Create an encoder/1 with the given options.
-%% @type encoder_option() = handler_option() | utf8_option()
-%% @type utf8_option() = boolean(). Emit unicode as utf8 (default - false)
-encoder(Options) ->
- State = parse_encoder_options(Options, #encoder{}),
- fun (O) -> json_encode(O, State) end.
-
-%% @spec encode(json_term()) -> iolist()
-%% @doc Encode the given as JSON to an iolist.
-encode(Any) ->
- json_encode(Any, #encoder{}).
-
-%% @spec decoder([decoder_option()]) -> function()
-%% @doc Create a decoder/1 with the given options.
-decoder(Options) ->
- State = parse_decoder_options(Options, #decoder{}),
- fun (O) -> json_decode(O, State) end.
-
-%% @spec decode(iolist()) -> json_term()
-%% @doc Decode the given iolist to Erlang terms.
-decode(S) ->
- json_decode(S, #decoder{}).
-
-%% Internal API
-
-parse_encoder_options([], State) ->
- State;
-parse_encoder_options([{handler, Handler} | Rest], State) ->
- parse_encoder_options(Rest, State#encoder{handler=Handler});
-parse_encoder_options([{utf8, Switch} | Rest], State) ->
- parse_encoder_options(Rest, State#encoder{utf8=Switch}).
-
-parse_decoder_options([], State) ->
- State;
-parse_decoder_options([{object_hook, Hook} | Rest], State) ->
- parse_decoder_options(Rest, State#decoder{object_hook=Hook}).
-
-json_encode(true, _State) ->
- <<"true">>;
-json_encode(false, _State) ->
- <<"false">>;
-json_encode(null, _State) ->
- <<"null">>;
-json_encode(I, _State) when is_integer(I) ->
- integer_to_list(I);
-json_encode(F, _State) when is_float(F) ->
- mochinum:digits(F);
-json_encode(S, State) when is_binary(S); is_atom(S) ->
- json_encode_string(S, State);
-json_encode([{K, _}|_] = Props, State) when (K =/= struct andalso
- K =/= array andalso
- K =/= json) ->
- json_encode_proplist(Props, State);
-json_encode({struct, Props}, State) when is_list(Props) ->
- json_encode_proplist(Props, State);
-json_encode(Array, State) when is_list(Array) ->
- json_encode_array(Array, State);
-json_encode({array, Array}, State) when is_list(Array) ->
- json_encode_array(Array, State);
-json_encode({json, IoList}, _State) ->
- IoList;
-json_encode(Bad, #encoder{handler=null}) ->
- exit({json_encode, {bad_term, Bad}});
-json_encode(Bad, State=#encoder{handler=Handler}) ->
- json_encode(Handler(Bad), State).
-
-json_encode_array([], _State) ->
- <<"[]">>;
-json_encode_array(L, State) ->
- F = fun (O, Acc) ->
- [$,, json_encode(O, State) | Acc]
- end,
- [$, | Acc1] = lists:foldl(F, "[", L),
- lists:reverse([$\] | Acc1]).
-
-json_encode_proplist([], _State) ->
- <<"{}">>;
-json_encode_proplist(Props, State) ->
- F = fun ({K, V}, Acc) ->
- KS = json_encode_string(K, State),
- VS = json_encode(V, State),
- [$,, VS, $:, KS | Acc]
- end,
- [$, | Acc1] = lists:foldl(F, "{", Props),
- lists:reverse([$\} | Acc1]).
-
-json_encode_string(A, State) when is_atom(A) ->
- L = atom_to_list(A),
- case json_string_is_safe(L) of
- true ->
- [?Q, L, ?Q];
- false ->
- json_encode_string_unicode(xmerl_ucs:from_utf8(L), State, [?Q])
- end;
-json_encode_string(B, State) when is_binary(B) ->
- case json_bin_is_safe(B) of
- true ->
- [?Q, B, ?Q];
- false ->
- json_encode_string_unicode(xmerl_ucs:from_utf8(B), State, [?Q])
- end;
-json_encode_string(I, _State) when is_integer(I) ->
- [?Q, integer_to_list(I), ?Q];
-json_encode_string(L, State) when is_list(L) ->
- case json_string_is_safe(L) of
- true ->
- [?Q, L, ?Q];
- false ->
- json_encode_string_unicode(L, State, [?Q])
- end.
-
-json_string_is_safe([]) ->
- true;
-json_string_is_safe([C | Rest]) ->
- case C of
- ?Q ->
- false;
- $\\ ->
- false;
- $\b ->
- false;
- $\f ->
- false;
- $\n ->
- false;
- $\r ->
- false;
- $\t ->
- false;
- C when C >= 0, C < $\s; C >= 16#7f, C =< 16#10FFFF ->
- false;
- C when C < 16#7f ->
- json_string_is_safe(Rest);
- _ ->
- false
- end.
-
-json_bin_is_safe(<<>>) ->
- true;
-json_bin_is_safe(<<C, Rest/binary>>) ->
- case C of
- ?Q ->
- false;
- $\\ ->
- false;
- $\b ->
- false;
- $\f ->
- false;
- $\n ->
- false;
- $\r ->
- false;
- $\t ->
- false;
- C when C >= 0, C < $\s; C >= 16#7f ->
- false;
- C when C < 16#7f ->
- json_bin_is_safe(Rest)
- end.
-
-json_encode_string_unicode([], _State, Acc) ->
- lists:reverse([$\" | Acc]);
-json_encode_string_unicode([C | Cs], State, Acc) ->
- Acc1 = case C of
- ?Q ->
- [?Q, $\\ | Acc];
- %% Escaping solidus is only useful when trying to protect
- %% against "</script>" injection attacks which are only
- %% possible when JSON is inserted into a HTML document
- %% in-line. mochijson2 does not protect you from this, so
- %% if you do insert directly into HTML then you need to
- %% uncomment the following case or escape the output of encode.
- %%
- %% $/ ->
- %% [$/, $\\ | Acc];
- %%
- $\\ ->
- [$\\, $\\ | Acc];
- $\b ->
- [$b, $\\ | Acc];
- $\f ->
- [$f, $\\ | Acc];
- $\n ->
- [$n, $\\ | Acc];
- $\r ->
- [$r, $\\ | Acc];
- $\t ->
- [$t, $\\ | Acc];
- C when C >= 0, C < $\s ->
- [unihex(C) | Acc];
- C when C >= 16#7f, C =< 16#10FFFF, State#encoder.utf8 ->
- [xmerl_ucs:to_utf8(C) | Acc];
- C when C >= 16#7f, C =< 16#10FFFF, not State#encoder.utf8 ->
- [unihex(C) | Acc];
- C when C < 16#7f ->
- [C | Acc];
- _ ->
- exit({json_encode, {bad_char, C}})
- end,
- json_encode_string_unicode(Cs, State, Acc1).
-
-hexdigit(C) when C >= 0, C =< 9 ->
- C + $0;
-hexdigit(C) when C =< 15 ->
- C + $a - 10.
-
-unihex(C) when C < 16#10000 ->
- <<D3:4, D2:4, D1:4, D0:4>> = <<C:16>>,
- Digits = [hexdigit(D) || D <- [D3, D2, D1, D0]],
- [$\\, $u | Digits];
-unihex(C) when C =< 16#10FFFF ->
- N = C - 16#10000,
- S1 = 16#d800 bor ((N bsr 10) band 16#3ff),
- S2 = 16#dc00 bor (N band 16#3ff),
- [unihex(S1), unihex(S2)].
-
-json_decode(L, S) when is_list(L) ->
- json_decode(iolist_to_binary(L), S);
-json_decode(B, S) ->
- {Res, S1} = decode1(B, S),
- {eof, _} = tokenize(B, S1#decoder{state=trim}),
- Res.
-
-decode1(B, S=#decoder{state=null}) ->
- case tokenize(B, S#decoder{state=any}) of
- {{const, C}, S1} ->
- {C, S1};
- {start_array, S1} ->
- decode_array(B, S1);
- {start_object, S1} ->
- decode_object(B, S1)
- end.
-
-make_object(V, #decoder{object_hook=null}) ->
- V;
-make_object(V, #decoder{object_hook=Hook}) ->
- Hook(V).
-
-decode_object(B, S) ->
- decode_object(B, S#decoder{state=key}, []).
-
-decode_object(B, S=#decoder{state=key}, Acc) ->
- case tokenize(B, S) of
- {end_object, S1} ->
- V = make_object({struct, lists:reverse(Acc)}, S1),
- {V, S1#decoder{state=null}};
- {{const, K}, S1} ->
- {colon, S2} = tokenize(B, S1),
- {V, S3} = decode1(B, S2#decoder{state=null}),
- decode_object(B, S3#decoder{state=comma}, [{K, V} | Acc])
- end;
-decode_object(B, S=#decoder{state=comma}, Acc) ->
- case tokenize(B, S) of
- {end_object, S1} ->
- V = make_object({struct, lists:reverse(Acc)}, S1),
- {V, S1#decoder{state=null}};
- {comma, S1} ->
- decode_object(B, S1#decoder{state=key}, Acc)
- end.
-
-decode_array(B, S) ->
- decode_array(B, S#decoder{state=any}, []).
-
-decode_array(B, S=#decoder{state=any}, Acc) ->
- case tokenize(B, S) of
- {end_array, S1} ->
- {lists:reverse(Acc), S1#decoder{state=null}};
- {start_array, S1} ->
- {Array, S2} = decode_array(B, S1),
- decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
- {start_object, S1} ->
- {Array, S2} = decode_object(B, S1),
- decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
- {{const, Const}, S1} ->
- decode_array(B, S1#decoder{state=comma}, [Const | Acc])
- end;
-decode_array(B, S=#decoder{state=comma}, Acc) ->
- case tokenize(B, S) of
- {end_array, S1} ->
- {lists:reverse(Acc), S1#decoder{state=null}};
- {comma, S1} ->
- decode_array(B, S1#decoder{state=any}, Acc)
- end.
-
-tokenize_string(B, S=#decoder{offset=O}) ->
- case tokenize_string_fast(B, O) of
- {escape, O1} ->
- Length = O1 - O,
- S1 = ?ADV_COL(S, Length),
- <<_:O/binary, Head:Length/binary, _/binary>> = B,
- tokenize_string(B, S1, lists:reverse(binary_to_list(Head)));
- O1 ->
- Length = O1 - O,
- <<_:O/binary, String:Length/binary, ?Q, _/binary>> = B,
- {{const, String}, ?ADV_COL(S, Length + 1)}
- end.
-
-tokenize_string_fast(B, O) ->
- case B of
- <<_:O/binary, ?Q, _/binary>> ->
- O;
- <<_:O/binary, $\\, _/binary>> ->
- {escape, O};
- <<_:O/binary, C1, _/binary>> when C1 < 128 ->
- tokenize_string_fast(B, 1 + O);
- <<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
- C2 >= 128, C2 =< 191 ->
- tokenize_string_fast(B, 2 + O);
- <<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
- C2 >= 128, C2 =< 191,
- C3 >= 128, C3 =< 191 ->
- tokenize_string_fast(B, 3 + O);
- <<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
- C2 >= 128, C2 =< 191,
- C3 >= 128, C3 =< 191,
- C4 >= 128, C4 =< 191 ->
- tokenize_string_fast(B, 4 + O);
- _ ->
- throw(invalid_utf8)
- end.
-
-tokenize_string(B, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, ?Q, _/binary>> ->
- {{const, iolist_to_binary(lists:reverse(Acc))}, ?INC_COL(S)};
- <<_:O/binary, "\\\"", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$\" | Acc]);
- <<_:O/binary, "\\\\", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$\\ | Acc]);
- <<_:O/binary, "\\/", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$/ | Acc]);
- <<_:O/binary, "\\b", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$\b | Acc]);
- <<_:O/binary, "\\f", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$\f | Acc]);
- <<_:O/binary, "\\n", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$\n | Acc]);
- <<_:O/binary, "\\r", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$\r | Acc]);
- <<_:O/binary, "\\t", _/binary>> ->
- tokenize_string(B, ?ADV_COL(S, 2), [$\t | Acc]);
- <<_:O/binary, "\\u", C3, C2, C1, C0, Rest/binary>> ->
- C = erlang:list_to_integer([C3, C2, C1, C0], 16),
- if C > 16#D7FF, C < 16#DC00 ->
- %% coalesce UTF-16 surrogate pair
- <<"\\u", D3, D2, D1, D0, _/binary>> = Rest,
- D = erlang:list_to_integer([D3,D2,D1,D0], 16),
- [CodePoint] = xmerl_ucs:from_utf16be(<<C:16/big-unsigned-integer,
- D:16/big-unsigned-integer>>),
- Acc1 = lists:reverse(xmerl_ucs:to_utf8(CodePoint), Acc),
- tokenize_string(B, ?ADV_COL(S, 12), Acc1);
- true ->
- Acc1 = lists:reverse(xmerl_ucs:to_utf8(C), Acc),
- tokenize_string(B, ?ADV_COL(S, 6), Acc1)
- end;
- <<_:O/binary, C1, _/binary>> when C1 < 128 ->
- tokenize_string(B, ?INC_CHAR(S, C1), [C1 | Acc]);
- <<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
- C2 >= 128, C2 =< 191 ->
- tokenize_string(B, ?ADV_COL(S, 2), [C2, C1 | Acc]);
- <<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
- C2 >= 128, C2 =< 191,
- C3 >= 128, C3 =< 191 ->
- tokenize_string(B, ?ADV_COL(S, 3), [C3, C2, C1 | Acc]);
- <<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
- C2 >= 128, C2 =< 191,
- C3 >= 128, C3 =< 191,
- C4 >= 128, C4 =< 191 ->
- tokenize_string(B, ?ADV_COL(S, 4), [C4, C3, C2, C1 | Acc]);
- _ ->
- throw(invalid_utf8)
- end.
-
-tokenize_number(B, S) ->
- case tokenize_number(B, sign, S, []) of
- {{int, Int}, S1} ->
- {{const, list_to_integer(Int)}, S1};
- {{float, Float}, S1} ->
- {{const, list_to_float(Float)}, S1}
- end.
-
-tokenize_number(B, sign, S=#decoder{offset=O}, []) ->
- case B of
- <<_:O/binary, $-, _/binary>> ->
- tokenize_number(B, int, ?INC_COL(S), [$-]);
- _ ->
- tokenize_number(B, int, S, [])
- end;
-tokenize_number(B, int, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, $0, _/binary>> ->
- tokenize_number(B, frac, ?INC_COL(S), [$0 | Acc]);
- <<_:O/binary, C, _/binary>> when C >= $1 andalso C =< $9 ->
- tokenize_number(B, int1, ?INC_COL(S), [C | Acc])
- end;
-tokenize_number(B, int1, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
- tokenize_number(B, int1, ?INC_COL(S), [C | Acc]);
- _ ->
- tokenize_number(B, frac, S, Acc)
- end;
-tokenize_number(B, frac, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, $., C, _/binary>> when C >= $0, C =< $9 ->
- tokenize_number(B, frac1, ?ADV_COL(S, 2), [C, $. | Acc]);
- <<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
- tokenize_number(B, esign, ?INC_COL(S), [$e, $0, $. | Acc]);
- _ ->
- {{int, lists:reverse(Acc)}, S}
- end;
-tokenize_number(B, frac1, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
- tokenize_number(B, frac1, ?INC_COL(S), [C | Acc]);
- <<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
- tokenize_number(B, esign, ?INC_COL(S), [$e | Acc]);
- _ ->
- {{float, lists:reverse(Acc)}, S}
- end;
-tokenize_number(B, esign, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, C, _/binary>> when C =:= $- orelse C=:= $+ ->
- tokenize_number(B, eint, ?INC_COL(S), [C | Acc]);
- _ ->
- tokenize_number(B, eint, S, Acc)
- end;
-tokenize_number(B, eint, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
- tokenize_number(B, eint1, ?INC_COL(S), [C | Acc])
- end;
-tokenize_number(B, eint1, S=#decoder{offset=O}, Acc) ->
- case B of
- <<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
- tokenize_number(B, eint1, ?INC_COL(S), [C | Acc]);
- _ ->
- {{float, lists:reverse(Acc)}, S}
- end.
-
-tokenize(B, S=#decoder{offset=O}) ->
- case B of
- <<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
- tokenize(B, ?INC_CHAR(S, C));
- <<_:O/binary, "{", _/binary>> ->
- {start_object, ?INC_COL(S)};
- <<_:O/binary, "}", _/binary>> ->
- {end_object, ?INC_COL(S)};
- <<_:O/binary, "[", _/binary>> ->
- {start_array, ?INC_COL(S)};
- <<_:O/binary, "]", _/binary>> ->
- {end_array, ?INC_COL(S)};
- <<_:O/binary, ",", _/binary>> ->
- {comma, ?INC_COL(S)};
- <<_:O/binary, ":", _/binary>> ->
- {colon, ?INC_COL(S)};
- <<_:O/binary, "null", _/binary>> ->
- {{const, null}, ?ADV_COL(S, 4)};
- <<_:O/binary, "true", _/binary>> ->
- {{const, true}, ?ADV_COL(S, 4)};
- <<_:O/binary, "false", _/binary>> ->
- {{const, false}, ?ADV_COL(S, 5)};
- <<_:O/binary, "\"", _/binary>> ->
- tokenize_string(B, ?INC_COL(S));
- <<_:O/binary, C, _/binary>> when (C >= $0 andalso C =< $9)
- orelse C =:= $- ->
- tokenize_number(B, S);
- <<_:O/binary>> ->
- trim = S#decoder.state,
- {eof, S}
- end.
-%%
-%% Tests
-%%
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
-
-%% testing constructs borrowed from the Yaws JSON implementation.
-
-%% Create an object from a list of Key/Value pairs.
-
-obj_new() ->
- {struct, []}.
-
-is_obj({struct, Props}) ->
- F = fun ({K, _}) when is_binary(K) -> true end,
- lists:all(F, Props).
-
-obj_from_list(Props) ->
- Obj = {struct, Props},
- ?assert(is_obj(Obj)),
- Obj.
-
-%% Test for equivalence of Erlang terms.
-%% Due to arbitrary order of construction, equivalent objects might
-%% compare unequal as erlang terms, so we need to carefully recurse
-%% through aggregates (tuples and objects).
-
-equiv({struct, Props1}, {struct, Props2}) ->
- equiv_object(Props1, Props2);
-equiv(L1, L2) when is_list(L1), is_list(L2) ->
- equiv_list(L1, L2);
-equiv(N1, N2) when is_number(N1), is_number(N2) -> N1 == N2;
-equiv(B1, B2) when is_binary(B1), is_binary(B2) -> B1 == B2;
-equiv(A, A) when A =:= true orelse A =:= false orelse A =:= null -> true.
-
-%% Object representation and traversal order is unknown.
-%% Use the sledgehammer and sort property lists.
-
-equiv_object(Props1, Props2) ->
- L1 = lists:keysort(1, Props1),
- L2 = lists:keysort(1, Props2),
- Pairs = lists:zip(L1, L2),
- true = lists:all(fun({{K1, V1}, {K2, V2}}) ->
- equiv(K1, K2) and equiv(V1, V2)
- end, Pairs).
-
-%% Recursively compare tuple elements for equivalence.
-
-equiv_list([], []) ->
- true;
-equiv_list([V1 | L1], [V2 | L2]) ->
- equiv(V1, V2) andalso equiv_list(L1, L2).
-
-decode_test() ->
- [1199344435545.0, 1] = decode(<<"[1199344435545.0,1]">>),
- <<16#F0,16#9D,16#9C,16#95>> = decode([34,"\\ud835","\\udf15",34]).
-
-e2j_vec_test() ->
- test_one(e2j_test_vec(utf8), 1).
-
-test_one([], _N) ->
- %% io:format("~p tests passed~n", [N-1]),
- ok;
-test_one([{E, J} | Rest], N) ->
- %% io:format("[~p] ~p ~p~n", [N, E, J]),
- true = equiv(E, decode(J)),
- true = equiv(E, decode(encode(E))),
- test_one(Rest, 1+N).
-
-e2j_test_vec(utf8) ->
- [
- {1, "1"},
- {3.1416, "3.14160"}, %% text representation may truncate, trail zeroes
- {-1, "-1"},
- {-3.1416, "-3.14160"},
- {12.0e10, "1.20000e+11"},
- {1.234E+10, "1.23400e+10"},
- {-1.234E-10, "-1.23400e-10"},
- {10.0, "1.0e+01"},
- {123.456, "1.23456E+2"},
- {10.0, "1e1"},
- {<<"foo">>, "\"foo\""},
- {<<"foo", 5, "bar">>, "\"foo\\u0005bar\""},
- {<<"">>, "\"\""},
- {<<"\n\n\n">>, "\"\\n\\n\\n\""},
- {<<"\" \b\f\r\n\t\"">>, "\"\\\" \\b\\f\\r\\n\\t\\\"\""},
- {obj_new(), "{}"},
- {obj_from_list([{<<"foo">>, <<"bar">>}]), "{\"foo\":\"bar\"}"},
- {obj_from_list([{<<"foo">>, <<"bar">>}, {<<"baz">>, 123}]),
- "{\"foo\":\"bar\",\"baz\":123}"},
- {[], "[]"},
- {[[]], "[[]]"},
- {[1, <<"foo">>], "[1,\"foo\"]"},
-
- %% json array in a json object
- {obj_from_list([{<<"foo">>, [123]}]),
- "{\"foo\":[123]}"},
-
- %% json object in a json object
- {obj_from_list([{<<"foo">>, obj_from_list([{<<"bar">>, true}])}]),
- "{\"foo\":{\"bar\":true}}"},
-
- %% fold evaluation order
- {obj_from_list([{<<"foo">>, []},
- {<<"bar">>, obj_from_list([{<<"baz">>, true}])},
- {<<"alice">>, <<"bob">>}]),
- "{\"foo\":[],\"bar\":{\"baz\":true},\"alice\":\"bob\"}"},
-
- %% json object in a json array
- {[-123, <<"foo">>, obj_from_list([{<<"bar">>, []}]), null],
- "[-123,\"foo\",{\"bar\":[]},null]"}
- ].
-
-%% test utf8 encoding
-encoder_utf8_test() ->
- %% safe conversion case (default)
- [34,"\\u0001","\\u0442","\\u0435","\\u0441","\\u0442",34] =
- encode(<<1,"\321\202\320\265\321\201\321\202">>),
-
- %% raw utf8 output (optional)
- Enc = mochijson2:encoder([{utf8, true}]),
- [34,"\\u0001",[209,130],[208,181],[209,129],[209,130],34] =
- Enc(<<1,"\321\202\320\265\321\201\321\202">>).
-
-input_validation_test() ->
- Good = [
- {16#00A3, <<?Q, 16#C2, 16#A3, ?Q>>}, %% pound
- {16#20AC, <<?Q, 16#E2, 16#82, 16#AC, ?Q>>}, %% euro
- {16#10196, <<?Q, 16#F0, 16#90, 16#86, 16#96, ?Q>>} %% denarius
- ],
- lists:foreach(fun({CodePoint, UTF8}) ->
- Expect = list_to_binary(xmerl_ucs:to_utf8(CodePoint)),
- Expect = decode(UTF8)
- end, Good),
-
- Bad = [
- %% 2nd, 3rd, or 4th byte of a multi-byte sequence w/o leading byte
- <<?Q, 16#80, ?Q>>,
- %% missing continuations, last byte in each should be 80-BF
- <<?Q, 16#C2, 16#7F, ?Q>>,
- <<?Q, 16#E0, 16#80,16#7F, ?Q>>,
- <<?Q, 16#F0, 16#80, 16#80, 16#7F, ?Q>>,
- %% we don't support code points > 10FFFF per RFC 3629
- <<?Q, 16#F5, 16#80, 16#80, 16#80, ?Q>>,
- %% escape characters trigger a different code path
- <<?Q, $\\, $\n, 16#80, ?Q>>
- ],
- lists:foreach(
- fun(X) ->
- ok = try decode(X) catch invalid_utf8 -> ok end,
- %% could be {ucs,{bad_utf8_character_code}} or
- %% {json_encode,{bad_char,_}}
- {'EXIT', _} = (catch encode(X))
- end, Bad).
-
-inline_json_test() ->
- ?assertEqual(<<"\"iodata iodata\"">>,
- iolist_to_binary(
- encode({json, [<<"\"iodata">>, " iodata\""]}))),
- ?assertEqual({struct, [{<<"key">>, <<"iodata iodata">>}]},
- decode(
- encode({struct,
- [{key, {json, [<<"\"iodata">>, " iodata\""]}}]}))),
- ok.
-
-big_unicode_test() ->
- UTF8Seq = list_to_binary(xmerl_ucs:to_utf8(16#0001d120)),
- ?assertEqual(
- <<"\"\\ud834\\udd20\"">>,
- iolist_to_binary(encode(UTF8Seq))),
- ?assertEqual(
- UTF8Seq,
- decode(iolist_to_binary(encode(UTF8Seq)))),
- ok.
-
-custom_decoder_test() ->
- ?assertEqual(
- {struct, [{<<"key">>, <<"value">>}]},
- (decoder([]))("{\"key\": \"value\"}")),
- F = fun ({struct, [{<<"key">>, <<"value">>}]}) -> win end,
- ?assertEqual(
- win,
- (decoder([{object_hook, F}]))("{\"key\": \"value\"}")),
- ok.
-
-atom_test() ->
- %% JSON native atoms
- [begin
- ?assertEqual(A, decode(atom_to_list(A))),
- ?assertEqual(iolist_to_binary(atom_to_list(A)),
- iolist_to_binary(encode(A)))
- end || A <- [true, false, null]],
- %% Atom to string
- ?assertEqual(
- <<"\"foo\"">>,
- iolist_to_binary(encode(foo))),
- ?assertEqual(
- <<"\"\\ud834\\udd20\"">>,
- iolist_to_binary(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))),
- ok.
-
-key_encode_test() ->
- %% Some forms are accepted as keys that would not be strings in other
- %% cases
- ?assertEqual(
- <<"{\"foo\":1}">>,
- iolist_to_binary(encode({struct, [{foo, 1}]}))),
- ?assertEqual(
- <<"{\"foo\":1}">>,
- iolist_to_binary(encode({struct, [{<<"foo">>, 1}]}))),
- ?assertEqual(
- <<"{\"foo\":1}">>,
- iolist_to_binary(encode({struct, [{"foo", 1}]}))),
- ?assertEqual(
- <<"{\"foo\":1}">>,
- iolist_to_binary(encode([{foo, 1}]))),
- ?assertEqual(
- <<"{\"foo\":1}">>,
- iolist_to_binary(encode([{<<"foo">>, 1}]))),
- ?assertEqual(
- <<"{\"foo\":1}">>,
- iolist_to_binary(encode([{"foo", 1}]))),
- ?assertEqual(
- <<"{\"\\ud834\\udd20\":1}">>,
- iolist_to_binary(
- encode({struct, [{[16#0001d120], 1}]}))),
- ?assertEqual(
- <<"{\"1\":1}">>,
- iolist_to_binary(encode({struct, [{1, 1}]}))),
- ok.
-
-unsafe_chars_test() ->
- Chars = "\"\\\b\f\n\r\t",
- [begin
- ?assertEqual(false, json_string_is_safe([C])),
- ?assertEqual(false, json_bin_is_safe(<<C>>)),
- ?assertEqual(<<C>>, decode(encode(<<C>>)))
- end || C <- Chars],
- ?assertEqual(
- false,
- json_string_is_safe([16#0001d120])),
- ?assertEqual(
- false,
- json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8(16#0001d120)))),
- ?assertEqual(
- [16#0001d120],
- xmerl_ucs:from_utf8(
- binary_to_list(
- decode(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))))),
- ?assertEqual(
- false,
- json_string_is_safe([16#110000])),
- ?assertEqual(
- false,
- json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8([16#110000])))),
- %% solidus can be escaped but isn't unsafe by default
- ?assertEqual(
- <<"/">>,
- decode(<<"\"\\/\"">>)),
- ok.
-
-int_test() ->
- ?assertEqual(0, decode("0")),
- ?assertEqual(1, decode("1")),
- ?assertEqual(11, decode("11")),
- ok.
-
-large_int_test() ->
- ?assertEqual(<<"-2147483649214748364921474836492147483649">>,
- iolist_to_binary(encode(-2147483649214748364921474836492147483649))),
- ?assertEqual(<<"2147483649214748364921474836492147483649">>,
- iolist_to_binary(encode(2147483649214748364921474836492147483649))),
- ok.
-
-float_test() ->
- ?assertEqual(<<"-2147483649.0">>, iolist_to_binary(encode(-2147483649.0))),
- ?assertEqual(<<"2147483648.0">>, iolist_to_binary(encode(2147483648.0))),
- ok.
-
-handler_test() ->
- ?assertEqual(
- {'EXIT',{json_encode,{bad_term,{}}}},
- catch encode({})),
- F = fun ({}) -> [] end,
- ?assertEqual(
- <<"[]">>,
- iolist_to_binary((encoder([{handler, F}]))({}))),
- ok.
-
--endif.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/ejson/src/mochinum.erl
----------------------------------------------------------------------
diff --git a/src/ejson/src/mochinum.erl b/src/ejson/src/mochinum.erl
deleted file mode 100644
index c52b15c..0000000
--- a/src/ejson/src/mochinum.erl
+++ /dev/null
@@ -1,354 +0,0 @@
-%% @copyright 2007 Mochi Media, Inc.
-%% @author Bob Ippolito <bo...@mochimedia.com>
-
-%% @doc Useful numeric algorithms for floats that cover some deficiencies
-%% in the math module. More interesting is digits/1, which implements
-%% the algorithm from:
-%% http://www.cs.indiana.edu/~burger/fp/index.html
-%% See also "Printing Floating-Point Numbers Quickly and Accurately"
-%% in Proceedings of the SIGPLAN '96 Conference on Programming Language
-%% Design and Implementation.
-
--module(mochinum).
--author("Bob Ippolito <bo...@mochimedia.com>").
--export([digits/1, frexp/1, int_pow/2, int_ceil/1]).
-
-%% IEEE 754 Float exponent bias
--define(FLOAT_BIAS, 1022).
--define(MIN_EXP, -1074).
--define(BIG_POW, 4503599627370496).
-
-%% External API
-
-%% @spec digits(number()) -> string()
-%% @doc Returns a string that accurately represents the given integer or float
-%% using a conservative amount of digits. Great for generating
-%% human-readable output, or compact ASCII serializations for floats.
-digits(N) when is_integer(N) ->
- integer_to_list(N);
-digits(0.0) ->
- "0.0";
-digits(Float) ->
- {Frac1, Exp1} = frexp_int(Float),
- [Place0 | Digits0] = digits1(Float, Exp1, Frac1),
- {Place, Digits} = transform_digits(Place0, Digits0),
- R = insert_decimal(Place, Digits),
- case Float < 0 of
- true ->
- [$- | R];
- _ ->
- R
- end.
-
-%% @spec frexp(F::float()) -> {Frac::float(), Exp::float()}
-%% @doc Return the fractional and exponent part of an IEEE 754 double,
-%% equivalent to the libc function of the same name.
-%% F = Frac * pow(2, Exp).
-frexp(F) ->
- frexp1(unpack(F)).
-
-%% @spec int_pow(X::integer(), N::integer()) -> Y::integer()
-%% @doc Moderately efficient way to exponentiate integers.
-%% int_pow(10, 2) = 100.
-int_pow(_X, 0) ->
- 1;
-int_pow(X, N) when N > 0 ->
- int_pow(X, N, 1).
-
-%% @spec int_ceil(F::float()) -> integer()
-%% @doc Return the ceiling of F as an integer. The ceiling is defined as
-%% F when F == trunc(F);
-%% trunc(F) when F < 0;
-%% trunc(F) + 1 when F > 0.
-int_ceil(X) ->
- T = trunc(X),
- case (X - T) of
- Pos when Pos > 0 -> T + 1;
- _ -> T
- end.
-
-
-%% Internal API
-
-int_pow(X, N, R) when N < 2 ->
- R * X;
-int_pow(X, N, R) ->
- int_pow(X * X, N bsr 1, case N band 1 of 1 -> R * X; 0 -> R end).
-
-insert_decimal(0, S) ->
- "0." ++ S;
-insert_decimal(Place, S) when Place > 0 ->
- L = length(S),
- case Place - L of
- 0 ->
- S ++ ".0";
- N when N < 0 ->
- {S0, S1} = lists:split(L + N, S),
- S0 ++ "." ++ S1;
- N when N < 6 ->
- %% More places than digits
- S ++ lists:duplicate(N, $0) ++ ".0";
- _ ->
- insert_decimal_exp(Place, S)
- end;
-insert_decimal(Place, S) when Place > -6 ->
- "0." ++ lists:duplicate(abs(Place), $0) ++ S;
-insert_decimal(Place, S) ->
- insert_decimal_exp(Place, S).
-
-insert_decimal_exp(Place, S) ->
- [C | S0] = S,
- S1 = case S0 of
- [] ->
- "0";
- _ ->
- S0
- end,
- Exp = case Place < 0 of
- true ->
- "e-";
- false ->
- "e+"
- end,
- [C] ++ "." ++ S1 ++ Exp ++ integer_to_list(abs(Place - 1)).
-
-
-digits1(Float, Exp, Frac) ->
- Round = ((Frac band 1) =:= 0),
- case Exp >= 0 of
- true ->
- BExp = 1 bsl Exp,
- case (Frac =/= ?BIG_POW) of
- true ->
- scale((Frac * BExp * 2), 2, BExp, BExp,
- Round, Round, Float);
- false ->
- scale((Frac * BExp * 4), 4, (BExp * 2), BExp,
- Round, Round, Float)
- end;
- false ->
- case (Exp =:= ?MIN_EXP) orelse (Frac =/= ?BIG_POW) of
- true ->
- scale((Frac * 2), 1 bsl (1 - Exp), 1, 1,
- Round, Round, Float);
- false ->
- scale((Frac * 4), 1 bsl (2 - Exp), 2, 1,
- Round, Round, Float)
- end
- end.
-
-scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) ->
- Est = int_ceil(math:log10(abs(Float)) - 1.0e-10),
- %% Note that the scheme implementation uses a 326 element look-up table
- %% for int_pow(10, N) where we do not.
- case Est >= 0 of
- true ->
- fixup(R, S * int_pow(10, Est), MPlus, MMinus, Est,
- LowOk, HighOk);
- false ->
- Scale = int_pow(10, -Est),
- fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est,
- LowOk, HighOk)
- end.
-
-fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) ->
- TooLow = case HighOk of
- true ->
- (R + MPlus) >= S;
- false ->
- (R + MPlus) > S
- end,
- case TooLow of
- true ->
- [(K + 1) | generate(R, S, MPlus, MMinus, LowOk, HighOk)];
- false ->
- [K | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)]
- end.
-
-generate(R0, S, MPlus, MMinus, LowOk, HighOk) ->
- D = R0 div S,
- R = R0 rem S,
- TC1 = case LowOk of
- true ->
- R =< MMinus;
- false ->
- R < MMinus
- end,
- TC2 = case HighOk of
- true ->
- (R + MPlus) >= S;
- false ->
- (R + MPlus) > S
- end,
- case TC1 of
- false ->
- case TC2 of
- false ->
- [D | generate(R * 10, S, MPlus * 10, MMinus * 10,
- LowOk, HighOk)];
- true ->
- [D + 1]
- end;
- true ->
- case TC2 of
- false ->
- [D];
- true ->
- case R * 2 < S of
- true ->
- [D];
- false ->
- [D + 1]
- end
- end
- end.
-
-unpack(Float) ->
- <<Sign:1, Exp:11, Frac:52>> = <<Float:64/float>>,
- {Sign, Exp, Frac}.
-
-frexp1({_Sign, 0, 0}) ->
- {0.0, 0};
-frexp1({Sign, 0, Frac}) ->
- Exp = log2floor(Frac),
- <<Frac1:64/float>> = <<Sign:1, ?FLOAT_BIAS:11, (Frac-1):52>>,
- {Frac1, -(?FLOAT_BIAS) - 52 + Exp};
-frexp1({Sign, Exp, Frac}) ->
- <<Frac1:64/float>> = <<Sign:1, ?FLOAT_BIAS:11, Frac:52>>,
- {Frac1, Exp - ?FLOAT_BIAS}.
-
-log2floor(Int) ->
- log2floor(Int, 0).
-
-log2floor(0, N) ->
- N;
-log2floor(Int, N) ->
- log2floor(Int bsr 1, 1 + N).
-
-
-transform_digits(Place, [0 | Rest]) ->
- transform_digits(Place, Rest);
-transform_digits(Place, Digits) ->
- {Place, [$0 + D || D <- Digits]}.
-
-
-frexp_int(F) ->
- case unpack(F) of
- {_Sign, 0, Frac} ->
- {Frac, ?MIN_EXP};
- {_Sign, Exp, Frac} ->
- {Frac + (1 bsl 52), Exp - 53 - ?FLOAT_BIAS}
- end.
-
-%%
-%% Tests
-%%
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
-int_ceil_test() ->
- ?assertEqual(1, int_ceil(0.0001)),
- ?assertEqual(0, int_ceil(0.0)),
- ?assertEqual(1, int_ceil(0.99)),
- ?assertEqual(1, int_ceil(1.0)),
- ?assertEqual(-1, int_ceil(-1.5)),
- ?assertEqual(-2, int_ceil(-2.0)),
- ok.
-
-int_pow_test() ->
- ?assertEqual(1, int_pow(1, 1)),
- ?assertEqual(1, int_pow(1, 0)),
- ?assertEqual(1, int_pow(10, 0)),
- ?assertEqual(10, int_pow(10, 1)),
- ?assertEqual(100, int_pow(10, 2)),
- ?assertEqual(1000, int_pow(10, 3)),
- ok.
-
-digits_test() ->
- ?assertEqual("0",
- digits(0)),
- ?assertEqual("0.0",
- digits(0.0)),
- ?assertEqual("1.0",
- digits(1.0)),
- ?assertEqual("-1.0",
- digits(-1.0)),
- ?assertEqual("0.1",
- digits(0.1)),
- ?assertEqual("0.01",
- digits(0.01)),
- ?assertEqual("0.001",
- digits(0.001)),
- ?assertEqual("1.0e+6",
- digits(1000000.0)),
- ?assertEqual("0.5",
- digits(0.5)),
- ?assertEqual("4503599627370496.0",
- digits(4503599627370496.0)),
- %% small denormalized number
- %% 4.94065645841246544177e-324 =:= 5.0e-324
- <<SmallDenorm/float>> = <<0,0,0,0,0,0,0,1>>,
- ?assertEqual("5.0e-324",
- digits(SmallDenorm)),
- ?assertEqual(SmallDenorm,
- list_to_float(digits(SmallDenorm))),
- %% large denormalized number
- %% 2.22507385850720088902e-308
- <<BigDenorm/float>> = <<0,15,255,255,255,255,255,255>>,
- ?assertEqual("2.225073858507201e-308",
- digits(BigDenorm)),
- ?assertEqual(BigDenorm,
- list_to_float(digits(BigDenorm))),
- %% small normalized number
- %% 2.22507385850720138309e-308
- <<SmallNorm/float>> = <<0,16,0,0,0,0,0,0>>,
- ?assertEqual("2.2250738585072014e-308",
- digits(SmallNorm)),
- ?assertEqual(SmallNorm,
- list_to_float(digits(SmallNorm))),
- %% large normalized number
- %% 1.79769313486231570815e+308
- <<LargeNorm/float>> = <<127,239,255,255,255,255,255,255>>,
- ?assertEqual("1.7976931348623157e+308",
- digits(LargeNorm)),
- ?assertEqual(LargeNorm,
- list_to_float(digits(LargeNorm))),
- %% issue #10 - mochinum:frexp(math:pow(2, -1074)).
- ?assertEqual("5.0e-324",
- digits(math:pow(2, -1074))),
- ok.
-
-frexp_test() ->
- %% zero
- ?assertEqual({0.0, 0}, frexp(0.0)),
- %% one
- ?assertEqual({0.5, 1}, frexp(1.0)),
- %% negative one
- ?assertEqual({-0.5, 1}, frexp(-1.0)),
- %% small denormalized number
- %% 4.94065645841246544177e-324
- <<SmallDenorm/float>> = <<0,0,0,0,0,0,0,1>>,
- ?assertEqual({0.5, -1073}, frexp(SmallDenorm)),
- %% large denormalized number
- %% 2.22507385850720088902e-308
- <<BigDenorm/float>> = <<0,15,255,255,255,255,255,255>>,
- ?assertEqual(
- {0.99999999999999978, -1022},
- frexp(BigDenorm)),
- %% small normalized number
- %% 2.22507385850720138309e-308
- <<SmallNorm/float>> = <<0,16,0,0,0,0,0,0>>,
- ?assertEqual({0.5, -1021}, frexp(SmallNorm)),
- %% large normalized number
- %% 1.79769313486231570815e+308
- <<LargeNorm/float>> = <<127,239,255,255,255,255,255,255>>,
- ?assertEqual(
- {0.99999999999999989, 1024},
- frexp(LargeNorm)),
- %% issue #10 - mochinum:frexp(math:pow(2, -1074)).
- ?assertEqual(
- {0.5, -1073},
- frexp(math:pow(2, -1074))),
- ok.
-
--endif.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/.gitignore
----------------------------------------------------------------------
diff --git a/src/jiffy/.gitignore b/src/jiffy/.gitignore
new file mode 100644
index 0000000..67903ef
--- /dev/null
+++ b/src/jiffy/.gitignore
@@ -0,0 +1,7 @@
+.jiffy.dev
+*.app
+*.beam
+*.o
+*.so
+.eunit
+deps
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/LICENSE
----------------------------------------------------------------------
diff --git a/src/jiffy/LICENSE b/src/jiffy/LICENSE
new file mode 100644
index 0000000..6d5c254
--- /dev/null
+++ b/src/jiffy/LICENSE
@@ -0,0 +1,90 @@
+jiffy
+=====
+
+Files: c_src/* src/* test/*.t
+
+Copyright 2011 Paul J. Davis <pa...@gmail.com>
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+Etap
+====
+
+Files: test/etap.erl
+
+Copyright (c) 2008-2009 Nick Gerakines <ni...@gerakines.net>
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+Yajl Test Cases
+===============
+
+Files: test/cases/*.json
+
+Copyright 2010, Lloyd Hilaiel.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+ 3. Neither the name of Lloyd Hilaiel nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/Makefile
----------------------------------------------------------------------
diff --git a/src/jiffy/Makefile b/src/jiffy/Makefile
new file mode 100644
index 0000000..7227ce4
--- /dev/null
+++ b/src/jiffy/Makefile
@@ -0,0 +1,47 @@
+REBAR?=./rebar
+
+
+all: build
+
+
+clean:
+ $(REBAR) clean
+ rm -rf logs
+ rm -rf .eunit
+ rm -f test/*.beam
+
+
+distclean: clean
+ git clean -fxd
+
+
+devmarker:
+ touch .jiffy.dev
+
+
+depends: devmarker
+ @if test ! -d ./deps/proper; then \
+ $(REBAR) get-deps; \
+ fi
+
+
+build: depends
+ $(REBAR) compile
+
+
+etap: test/etap.beam test/util.beam
+ prove test/*.t
+
+
+eunit:
+ $(REBAR) eunit skip_deps=true
+
+
+check: build etap eunit
+
+
+%.beam: %.erl
+ erlc -o test/ $<
+
+
+.PHONY: all clean distclean depends build etap eunit check
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/README.md
----------------------------------------------------------------------
diff --git a/src/jiffy/README.md b/src/jiffy/README.md
new file mode 100644
index 0000000..efb5300
--- /dev/null
+++ b/src/jiffy/README.md
@@ -0,0 +1,58 @@
+Jiffy - JSON NIFs for Erlang
+============================
+
+A JSON parser as a NIF. This is a complete rewrite of the work I did
+in EEP0018 that was based on Yajl. This new version is a hand crafted
+state machine that does its best to be as quick and efficient as
+possible while not placing any constraints on the parsed JSON.
+
+Usage
+-----
+
+Jiffy is a simple API. The only thing that might catch you off guard
+is that the return type of jiffy:encode/1 is an iolist even though it
+returns a binary most of the time.
+
+A quick note on unicode. Jiffy only understands utf-8 in binaries. End
+of story. Also, there is a jiffy:encode/2 that takes a list of options
+for encoding. Currently the only supported option is `uescape`.
+
+Errors are raised as exceptions.
+
+ Eshell V5.8.2 (abort with ^G)
+ 1> jiffy:decode(<<"{\"foo\": \"bar\"}">>).
+ {[{<<"foo">>,<<"bar">>}]}
+ 2> Doc = {[{foo, [<<"bing">>, 2.3, true]}]}.
+ {[{foo,[<<"bing">>,2.3,true]}]}
+ 3> jiffy:encode(Doc).
+ <<"{\"foo\":[\"bing\",2.3,true]}">>
+
+
+Data Format
+-----------
+
+ Erlang JSON Erlang
+ ==========================================================================
+
+ null -> null -> null
+ true -> true -> true
+ false -> false -> false
+ "hi" -> [104, 105] -> [104, 105]
+ <<"hi">> -> "hi" -> <<"hi">>
+ hi -> "hi" -> <<"hi">>
+ 1 -> 1 -> 1
+ 1.25 -> 1.25 -> 1.25
+ [] -> [] -> []
+ [true, 1.0] -> [true, 1.0] -> [true, 1.0]
+ {[]} -> {} -> {[]}
+ {[{foo, bar}]} -> {"foo": "bar"} -> {[{<<"foo">>, <<"bar">>}]}
+ {[{<<"foo">>, <<"bar">>}]} -> {"foo": "bar"} -> {[{<<"foo">>, <<"bar">>}]}
+
+Improvements over EEP0018
+-------------------------
+
+Jiffy should be in all ways an improvemnt over EEP0018. It no longer
+imposes limits on the nesting depth. It is capable of encoding and
+decoding large numbers and it does quite a bit more checking for validity
+of valid UTF-8 in strings.
+
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/decoder.c
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/decoder.c b/src/jiffy/c_src/decoder.c
new file mode 100644
index 0000000..fc892da
--- /dev/null
+++ b/src/jiffy/c_src/decoder.c
@@ -0,0 +1,914 @@
+// This file is part of Jiffy released under the MIT license.
+// See the LICENSE file for more information.
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "erl_nif.h"
+#include "jiffy.h"
+
+#define U(c) ((unsigned char) (c))
+#define ERROR(i, msg) make_error(st, env, msg)
+
+#define STACK_SIZE_INC 64
+#define NUM_BUF_LEN 32
+
+#if WINDOWS || WIN32
+#define snprintf _snprintf
+#endif
+
+enum {
+ st_value=0,
+ st_object,
+ st_array,
+ st_key,
+ st_colon,
+ st_comma,
+ st_done,
+ st_invalid
+} JsonState;
+
+enum {
+ nst_init=0,
+ nst_sign,
+ nst_mantissa,
+ nst_frac0,
+ nst_frac1,
+ nst_frac,
+ nst_esign,
+ nst_edigit
+} JsonNumState;
+
+typedef struct {
+ ErlNifEnv* env;
+ jiffy_st* atoms;
+
+ ERL_NIF_TERM arg;
+ ErlNifBinary bin;
+
+ int is_partial;
+
+ char* p;
+ unsigned char* u;
+ int i;
+ int len;
+
+ char* st_data;
+ int st_size;
+ int st_top;
+} Decoder;
+
+void
+dec_init(Decoder* d, ErlNifEnv* env, ERL_NIF_TERM arg, ErlNifBinary* bin)
+{
+ int i;
+
+ d->env = env;
+ d->atoms = enif_priv_data(env);
+ d->arg = arg;
+
+ d->is_partial = 0;
+
+ d->p = (char*) bin->data;
+ d->u = bin->data;
+ d->len = bin->size;
+ d->i = 0;
+
+ d->st_data = (char*) enif_alloc(STACK_SIZE_INC * sizeof(char));
+ d->st_size = STACK_SIZE_INC;
+ d->st_top = 0;
+
+ for(i = 0; i < d->st_size; i++) {
+ d->st_data[i] = st_invalid;
+ }
+
+ d->st_data[0] = st_value;
+ d->st_top++;
+}
+
+void
+dec_destroy(Decoder* d)
+{
+ if(d->st_data != NULL) {
+ enif_free(d->st_data);
+ }
+}
+
+ERL_NIF_TERM
+dec_error(Decoder* d, const char* atom)
+{
+ ERL_NIF_TERM pos = enif_make_int(d->env, d->i+1);
+ ERL_NIF_TERM msg = make_atom(d->env, atom);
+ ERL_NIF_TERM ret = enif_make_tuple2(d->env, pos, msg);
+ return enif_make_tuple2(d->env, d->atoms->atom_error, ret);
+}
+
+char
+dec_curr(Decoder* d)
+{
+ return d->st_data[d->st_top-1];
+}
+
+int
+dec_top(Decoder* d)
+{
+ return d->st_top;
+}
+
+void
+dec_push(Decoder* d, char val)
+{
+ char* tmp;
+ int new_sz;
+ int i;
+
+ if(d->st_top >= d->st_size) {
+ new_sz = d->st_size + STACK_SIZE_INC;
+ tmp = (char*) enif_alloc(new_sz * sizeof(char));
+ memcpy(tmp, d->st_data, d->st_size * sizeof(char));
+ enif_free(d->st_data);
+ d->st_data = tmp;
+ d->st_size = new_sz;
+ for(i = d->st_top; i < d->st_size; i++) {
+ d->st_data[i] = st_invalid;
+ }
+ }
+
+ d->st_data[d->st_top++] = val;
+}
+
+void
+dec_pop(Decoder* d, char val)
+{
+ assert(d->st_data[d->st_top-1] == val && "popped invalid state.");
+ d->st_data[d->st_top-1] = st_invalid;
+ d->st_top--;
+}
+
+int
+dec_string(Decoder* d, ERL_NIF_TERM* value)
+{
+ int has_escape = 0;
+ int num_escapes = 0;
+ int st;
+ int ulen;
+ int ui;
+ int hi;
+ int lo;
+ char* chrbuf;
+ int chrpos;
+
+ if(d->p[d->i] != '\"') {
+ return 0;
+ }
+ d->i++;
+
+ st = d->i;
+
+ while(d->i < d->len) {
+ if(d->u[d->i] < 0x20) {
+ return 0;
+ } else if(d->p[d->i] == '\"') {
+ d->i++;
+ goto parse;
+ } else if(d->p[d->i] == '\\') {
+ if(d->i+1 >= d->len) {
+ return 0;
+ }
+ has_escape = 1;
+ num_escapes += 1;
+ d->i++;
+ switch(d->p[d->i]) {
+ case '\"':
+ case '\\':
+ case '/':
+ case 'b':
+ case 'f':
+ case 'n':
+ case 'r':
+ case 't':
+ d->i++;
+ break;
+ case 'u':
+ hi = 0;
+ lo = 0;
+ d->i++;
+ if(d->i + 4 >= d->len) {
+ return 0;
+ }
+ hi = int_from_hex(&(d->u[d->i]));
+ if(hi < 0) {
+ return 0;
+ }
+ d->i += 4;
+ if(hi >= 0xD800 && hi < 0xDC00) {
+ if(d->i + 6 >= d->len) {
+ return 0;
+ }
+ if(d->p[d->i++] != '\\') {
+ return 0;
+ } else if(d->p[d->i++] != 'u') {
+ return 0;
+ }
+ lo = int_from_hex(&(d->u[d->i]));
+ if(lo < 0) {
+ return 0;
+ }
+ hi = unicode_from_pair(hi, lo);
+ if(hi < 0) {
+ return 0;
+ }
+ }
+ hi = utf8_len(hi);
+ if(hi < 0) {
+ return 0;
+ }
+ if(lo == 0) {
+ num_escapes += 5 - hi;
+ } else {
+ num_escapes += 11 - hi;
+ }
+ break;
+ default:
+ return 0;
+ }
+ } else if(d->u[d->i] < 0x80) {
+ d->i++;
+ } else {
+ ulen = utf8_validate(&(d->u[d->i]), d->len - d->i);
+ if(ulen < 0) {
+ return 0;
+ }
+ d->i += ulen;
+ }
+ }
+
+ // The goto above ensures that we only
+ // hit this when a string is not terminated
+ // correctly.
+ return 0;
+
+parse:
+ if(!has_escape) {
+ *value = enif_make_sub_binary(d->env, d->arg, st, (d->i - st - 1));
+ return 1;
+ }
+
+ hi = 0;
+ lo = 0;
+
+ ulen = (d->i - 1) - st - num_escapes;
+ chrbuf = (char*) enif_make_new_binary(d->env, ulen, value);
+ chrpos = 0;
+ ui = st;
+ while(ui < d->i - 1) {
+ if(d->p[ui] != '\\') {
+ chrbuf[chrpos++] = d->p[ui++];
+ continue;
+ }
+ ui++;
+ switch(d->p[ui]) {
+ case '\"':
+ case '\\':
+ case '/':
+ chrbuf[chrpos++] = d->p[ui];
+ ui++;
+ break;
+ case 'b':
+ chrbuf[chrpos++] = '\b';
+ ui++;
+ break;
+ case 'f':
+ chrbuf[chrpos++] = '\f';
+ ui++;
+ break;
+ case 'n':
+ chrbuf[chrpos++] = '\n';
+ ui++;
+ break;
+ case 'r':
+ chrbuf[chrpos++] = '\r';
+ ui++;
+ break;
+ case 't':
+ chrbuf[chrpos++] = '\t';
+ ui++;
+ break;
+ case 'u':
+ ui++;
+ hi = int_from_hex(&(d->u[ui]));
+ if(hi < 0) {
+ return 0;
+ }
+ if(hi >= 0xD800 && hi < 0xDC00) {
+ lo = int_from_hex(&(d->u[ui+6]));
+ if(lo < 0) {
+ return 0;
+ }
+ hi = unicode_from_pair(hi, lo);
+ ui += 10;
+ } else {
+ ui += 4;
+ }
+ hi = unicode_to_utf8(hi, (unsigned char*) chrbuf+chrpos);
+ if(hi < 0) {
+ return 0;
+ }
+ chrpos += hi;
+ break;
+ default:
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+int
+dec_number(Decoder* d, ERL_NIF_TERM* value)
+{
+ ERL_NIF_TERM num_type = d->atoms->atom_error;
+ char state = nst_init;
+ char nbuf[NUM_BUF_LEN];
+ int st = d->i;
+ int has_frac = 0;
+ int has_exp = 0;
+ double dval;
+ long lval;
+
+ while(d->i < d->len) {
+ switch(state) {
+ case nst_init:
+ switch(d->p[d->i]) {
+ case '-':
+ state = nst_sign;
+ d->i++;
+ break;
+ case '0':
+ state = nst_frac0;
+ d->i++;
+ break;
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ state = nst_mantissa;
+ d->i++;
+ break;
+ default:
+ return 0;
+ }
+ break;
+
+ case nst_sign:
+ switch(d->p[d->i]) {
+ case '0':
+ state = nst_frac0;
+ d->i++;
+ break;
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ state = nst_mantissa;
+ d->i++;
+ break;
+ default:
+ return 0;
+ }
+ break;
+
+ case nst_mantissa:
+ switch(d->p[d->i]) {
+ case '.':
+ state = nst_frac1;
+ d->i++;
+ break;
+ case 'e':
+ case 'E':
+ state = nst_esign;
+ d->i++;
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ d->i++;
+ break;
+ default:
+ goto parse;
+ }
+ break;
+
+ case nst_frac0:
+ switch(d->p[d->i]) {
+ case '.':
+ state = nst_frac1;
+ d->i++;
+ break;
+ case 'e':
+ case 'E':
+ state = nst_esign;
+ d->i++;
+ break;
+ default:
+ goto parse;
+ }
+ break;
+
+ case nst_frac1:
+ has_frac = 1;
+ switch(d->p[d->i]) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ state = nst_frac;
+ d->i++;
+ break;
+ default:
+ goto parse;
+ }
+ break;
+
+ case nst_frac:
+ switch(d->p[d->i]) {
+ case 'e':
+ case 'E':
+ state = nst_esign;
+ d->i++;
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ d->i++;
+ break;
+ default:
+ goto parse;
+ }
+ break;
+
+ case nst_esign:
+ has_exp = 1;
+ switch(d->p[d->i]) {
+ case '-':
+ case '+':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ state = nst_edigit;
+ d->i++;
+ break;
+ default:
+ return 0;
+ }
+ break;
+
+ case nst_edigit:
+ switch(d->p[d->i]) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ d->i++;
+ break;
+ default:
+ goto parse;
+ }
+ break;
+
+ default:
+ return 0;
+ }
+ }
+
+parse:
+
+ switch(state) {
+ case nst_init:
+ case nst_sign:
+ case nst_frac1:
+ case nst_esign:
+ return 0;
+ default:
+ break;
+ }
+
+ errno = 0;
+
+ if(d->i - st < NUM_BUF_LEN) {
+ memset(nbuf, 0, NUM_BUF_LEN);
+ memcpy(nbuf, &(d->p[st]), d->i - st);
+
+ if(has_frac || has_exp) {
+ dval = strtod(nbuf, NULL);
+ if(errno != ERANGE) {
+ *value = enif_make_double(d->env, dval);
+ return 1;
+ }
+ } else {
+ lval = strtol(nbuf, NULL, 10);
+ if(errno != ERANGE) {
+ *value = enif_make_int64(d->env, lval);
+ return 1;
+ }
+ }
+ }
+
+ 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;
+ }
+
+ d->is_partial = 1;
+ *value = enif_make_sub_binary(d->env, d->arg, st, d->i - st);
+ *value = enif_make_tuple2(d->env, num_type, *value);
+ return 1;
+}
+
+ERL_NIF_TERM
+make_object(ErlNifEnv* env, ERL_NIF_TERM pairs)
+{
+ ERL_NIF_TERM ret = enif_make_list(env, 0);
+ ERL_NIF_TERM key, val;
+
+ while(enif_get_list_cell(env, pairs, &val, &pairs)) {
+ if(!enif_get_list_cell(env, pairs, &key, &pairs)) {
+ assert(0 == 1 && "Unbalanced object pairs.");
+ }
+ val = enif_make_tuple2(env, key, val);
+ ret = enif_make_list_cell(env, val, ret);
+ }
+
+ return enif_make_tuple1(env, ret);
+}
+
+ERL_NIF_TERM
+make_array(ErlNifEnv* env, ERL_NIF_TERM list)
+{
+ ERL_NIF_TERM ret = enif_make_list(env, 0);
+ ERL_NIF_TERM item;
+
+ while(enif_get_list_cell(env, list, &item, &list)) {
+ ret = enif_make_list_cell(env, item, ret);
+ }
+
+ return ret;
+}
+
+ERL_NIF_TERM
+decode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{
+ Decoder dec;
+ Decoder* d = &dec;
+
+ ErlNifBinary bin;
+
+ ERL_NIF_TERM objs = enif_make_list(env, 0);
+ ERL_NIF_TERM curr = enif_make_list(env, 0);
+ ERL_NIF_TERM val;
+ ERL_NIF_TERM ret;
+
+ if(argc != 1) {
+ return enif_make_badarg(env);
+ } else if(!enif_inspect_binary(env, argv[0], &bin)) {
+ return enif_make_badarg(env);
+ }
+
+ dec_init(d, env, argv[0], &bin);
+
+ //fprintf(stderr, "Parsing:\r\n");
+ while(d->i < bin.size) {
+ //fprintf(stderr, "state: %d\r\n", dec_curr(d));
+ switch(dec_curr(d)) {
+ case st_value:
+ switch(d->p[d->i]) {
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ d->i++;
+ break;
+ case 'n':
+ if(d->i + 3 >= d->len) {
+ ret = dec_error(d, "invalid_literal");
+ goto done;
+ }
+ if(memcmp(&(d->p[d->i]), "null", 4) != 0) {
+ ret = dec_error(d, "invalid_literal");
+ goto done;
+ }
+ val = d->atoms->atom_null;
+ dec_pop(d, st_value);
+ d->i += 4;
+ break;
+ case 't':
+ if(d->i + 3 >= d->len) {
+ ret = dec_error(d, "invalid_literal");
+ goto done;
+ }
+ if(memcmp(&(d->p[d->i]), "true", 4) != 0) {
+ ret = dec_error(d, "invalid_literal");
+ goto done;
+ }
+ val = d->atoms->atom_true;
+ dec_pop(d, st_value);
+ d->i += 4;
+ break;
+ case 'f':
+ if(d->i + 4 >= bin.size) {
+ ret = dec_error(d, "invalid_literal");
+ goto done;
+ }
+ if(memcmp(&(d->p[d->i]), "false", 5) != 0) {
+ ret = dec_error(d, "invalid_literal");
+ goto done;
+ }
+ val = d->atoms->atom_false;
+ dec_pop(d, st_value);
+ d->i += 5;
+ break;
+ case '\"':
+ if(!dec_string(d, &val)) {
+ ret = dec_error(d, "invalid_string");
+ goto done;
+ }
+ dec_pop(d, st_value);
+ break;
+ case '-':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if(!dec_number(d, &val)) {
+ ret = dec_error(d, "invalid_number");
+ goto done;
+ }
+ dec_pop(d, st_value);
+ break;
+ case '{':
+ dec_push(d, st_object);
+ dec_push(d, st_key);
+ objs = enif_make_list_cell(env, curr, objs);
+ curr = enif_make_list(env, 0);
+ d->i++;
+ break;
+ case '[':
+ dec_push(d, st_array);
+ dec_push(d, st_value);
+ objs = enif_make_list_cell(env, curr, objs);
+ curr = enif_make_list(env, 0);
+ d->i++;
+ break;
+ case ']':
+ if(!enif_is_empty_list(env, curr)) {
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ dec_pop(d, st_value);
+ if(dec_curr(d) != st_array) {
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ dec_pop(d, st_array);
+ dec_pop(d, st_value);
+ val = curr; // curr is []
+ if(!enif_get_list_cell(env, objs, &curr, &objs)) {
+ ret = dec_error(d, "internal_error");
+ goto done;
+ }
+ d->i++;
+ break;
+ default:
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ if(dec_top(d) == 0) {
+ dec_push(d, st_done);
+ } else if(dec_curr(d) != st_value && dec_curr(d) != st_key) {
+ dec_push(d, st_comma);
+ curr = enif_make_list_cell(env, val, curr);
+ }
+ break;
+
+ case st_key:
+ switch(d->p[d->i]) {
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ d->i++;
+ break;
+ case '\"':
+ if(!dec_string(d, &val)) {
+ ret = dec_error(d, "invalid_string");
+ goto done;
+ }
+ dec_pop(d, st_key);
+ dec_push(d, st_colon);
+ curr = enif_make_list_cell(env, val, curr);
+ break;
+ case '}':
+ if(!enif_is_empty_list(env, curr)) {
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ dec_pop(d, st_key);
+ dec_pop(d, st_object);
+ dec_pop(d, st_value);
+ val = enif_make_tuple1(env, curr);
+ if(!enif_get_list_cell(env, objs, &curr, &objs)) {
+ ret = dec_error(d, "internal_error");
+ goto done;
+ }
+ if(dec_top(d) == 0) {
+ dec_push(d, st_done);
+ } else {
+ dec_push(d, st_comma);
+ curr = enif_make_list_cell(env, val, curr);
+ }
+ d->i++;
+ break;
+ default:
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ break;
+
+ case st_colon:
+ switch(d->p[d->i]) {
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ d->i++;
+ break;
+ case ':':
+ dec_pop(d, st_colon);
+ dec_push(d, st_value);
+ d->i++;
+ break;
+ default:
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ break;
+
+ case st_comma:
+ switch(d->p[d->i]) {
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ d->i++;
+ break;
+ case ',':
+ dec_pop(d, st_comma);
+ switch(dec_curr(d)) {
+ case st_object:
+ dec_push(d, st_key);
+ break;
+ case st_array:
+ dec_push(d, st_value);
+ break;
+ default:
+ ret = dec_error(d, "internal_error");
+ goto done;
+ }
+ d->i++;
+ break;
+ case '}':
+ dec_pop(d, st_comma);
+ if(dec_curr(d) != st_object) {
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ dec_pop(d, st_object);
+ dec_pop(d, st_value);
+ val = make_object(env, curr);
+ if(!enif_get_list_cell(env, objs, &curr, &objs)) {
+ ret = dec_error(d, "internal_error");
+ goto done;
+ }
+ if(dec_top(d) > 0) {
+ dec_push(d, st_comma);
+ curr = enif_make_list_cell(env, val, curr);
+ } else {
+ dec_push(d, st_done);
+ }
+ d->i++;
+ break;
+ case ']':
+ dec_pop(d, st_comma);
+ if(dec_curr(d) != st_array) {
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ dec_pop(d, st_array);
+ dec_pop(d, st_value);
+ val = make_array(env, curr);
+ if(!enif_get_list_cell(env, objs, &curr, &objs)) {
+ ret = dec_error(d, "internal_error");
+ goto done;
+ }
+ if(dec_top(d) > 0) {
+ dec_push(d, st_comma);
+ curr = enif_make_list_cell(env, val, curr);
+ } else {
+ dec_push(d, st_done);
+ }
+ d->i++;
+ break;
+ default:
+ ret = dec_error(d, "invalid_json");
+ goto done;
+ }
+ break;
+
+ case st_done:
+ switch(d->p[d->i]) {
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ d->i++;
+ break;
+ default:
+ ret = dec_error(d, "invalid_trailing_data");
+ goto done;
+ }
+ break;
+
+ default:
+ ret = dec_error(d, "invalid_internal_state");
+ goto done;
+ }
+ }
+
+ if(dec_curr(d) != st_done) {
+ ret = dec_error(d, "truncated_json");
+ } else if(d->is_partial) {
+ ret = enif_make_tuple2(env, d->atoms->atom_partial, val);
+ } else {
+ ret = val;
+ }
+
+done:
+ dec_destroy(d);
+
+ return ret;
+}
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/AUTHORS
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/AUTHORS b/src/jiffy/c_src/double-conversion/AUTHORS
new file mode 100644
index 0000000..ff2a5f4
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/AUTHORS
@@ -0,0 +1,12 @@
+# Below is a list of people and organizations that have contributed
+# to the double-conversion project. Names should be added to the
+# list like so:
+#
+# Name/Organization <email address>
+
+Google Inc.
+Mozilla Foundation
+
+Jeff Muizelaar <jm...@mozilla.com>
+Mike Hommey <mh...@mozilla.com>
+Martin Olsson <mn...@minimum.se>
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/COPYING
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/COPYING b/src/jiffy/c_src/double-conversion/COPYING
new file mode 100644
index 0000000..933718a
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/COPYING
@@ -0,0 +1,26 @@
+Copyright 2006-2011, the V8 project authors. All rights reserved.
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/DOWNLOADED
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/DOWNLOADED b/src/jiffy/c_src/double-conversion/DOWNLOADED
new file mode 100644
index 0000000..64724d8
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/DOWNLOADED
@@ -0,0 +1,3 @@
+Downloaded: 2013-02-24
+
+https://double-conversion.googlecode.com/files/double-conversion-1.1.1.tar.gz
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/LICENSE
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/LICENSE b/src/jiffy/c_src/double-conversion/LICENSE
new file mode 100644
index 0000000..933718a
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/LICENSE
@@ -0,0 +1,26 @@
+Copyright 2006-2011, the V8 project authors. All rights reserved.
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/2e6092e4/src/jiffy/c_src/double-conversion/README
----------------------------------------------------------------------
diff --git a/src/jiffy/c_src/double-conversion/README b/src/jiffy/c_src/double-conversion/README
new file mode 100644
index 0000000..f186b42
--- /dev/null
+++ b/src/jiffy/c_src/double-conversion/README
@@ -0,0 +1,11 @@
+http://code.google.com/p/double-conversion
+
+This project (double-conversion) provides binary-decimal and decimal-binary
+routines for IEEE doubles.
+
+The library consists of efficient conversion routines that have been extracted
+from the V8 JavaScript engine. The code has been refactored and improved so that
+it can be used more easily in other projects.
+
+There is extensive documentation in src/double-conversion.h. Other examples can
+be found in test/cctest/test-conversions.cc.