├── README.md ├── rebar.config └── src ├── ipfs.app.src ├── ipfs.erl ├── jsone.erl ├── jsone_decode.erl └── jsone_encode.erl /README.md: -------------------------------------------------------------------------------- 1 | # IPFS API wrapper library in Erlang 2 | 3 | ![](https://ipfs.io/ipfs/QmQJ68PFMDdAsgCZvA1UVzzn18asVcf7HVvCDgpjiSCAse) 4 | 5 | ## Install 6 | 7 | Simply clone this repo. 8 | 9 | ## Quickstart 10 | 11 | ``` 12 | %% Add Enpoint /api/v0/add 13 | Method: ipfs:add("ip-address", "port", "fullpathFile", "nameFile.extension"). 14 | > ipfs:add("127.0.0.1", "5001", "test.txt", "test.txt"). 15 | {[{<<"Name">>,<<"test.txt">>}, 16 | {<<"Hash">>, 17 | <<"QmYAVSgbjdw1hb96aFev6inrnqYntJLboeg8mumBvuamMe">>}]} 18 | 19 | %% Cat Enpoint /api/v0/cat 20 | Method: ipfs:add("ip-address", "port", "hash"). 21 | > ipfs:cat("127.0.0.1", "5001", "QmYAVSgbjdw1hb96aFev6inrnqYntJLboeg8mumBvuamMe"). 22 | "Hello World" 23 | 24 | %% Cat Enpoint /api/v0/ls 25 | Method: ipfs:ls("ip-address", "port", "hash"). 26 | > ipfs:ls("127.0.0.1", "5001", "QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w"). 27 | {[{<<"Objects">>, 28 | [{[{<<"Hash">>, 29 | <<"QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w">>}, 30 | {<<"Links">>, 31 | [{[{<<"Name">>,<<"index.html">>}, 32 | {<<"Hash">>, 33 | <<"QmYftndCvcEiuSZRX7njywX2AGSeHY2ASa7VryCq1mKwEw">>}, 34 | {<<"Size">>,1700}, 35 | {<<"Type">>,2}]}, 36 | {[{<<"Name">>,<<"static">>}, 37 | {<<"Hash">>, 38 | <<"QmdtWFiasJeh2ymW3TD2cLHYxn1ryTuWoNpwieFyJriGTS">>}, 39 | {<<"Size">>,2428803}, 40 | {<<"Type">>,1}]}]}]}]}]} 41 | 42 | %% Size Enpoint /api/v0/size 43 | Method: ipfs:ls("ip-address", "port", "hash"). 44 | > ipfs:size("127.0.0.1", "5001", "QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w"). 45 | {[{<<"Hash">>, 46 | <<"QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w">>}, 47 | {<<"NumLinks">>,2}, 48 | {<<"BlockSize">>,108}, 49 | {<<"LinksSize">>,106}, 50 | {<<"DataSize">>,2}, 51 | {<<"CumulativeSize">>,2430611}]} 52 | ``` 53 | 54 | ## License 55 | 56 | The MIT License (MIT) 57 | 58 | Copyright (c) 2017 Hendry Rodriguez 59 | 60 | 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: 61 | 62 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 63 | 64 | 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. 65 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {erl_opts, [debug_info, warnings_as_errors]}. -------------------------------------------------------------------------------- /src/ipfs.app.src: -------------------------------------------------------------------------------- 1 | {application, erlang-ipfs-api, [ 2 | {description, "Erlang Client Library of Ipfs."}, 3 | {vsn, "0.1.0"}, 4 | {registered, []}, 5 | {applications, [kernel, stdlib]}, 6 | {mod, { ipfs, []}}, 7 | {maintainers, ["Hendry Rodriguez"]}, 8 | {links, [{"GitHub", "https://github.com/hendry19901990/erlang-ipfs-api"}]}, 9 | {files, [ 10 | "README.md", 11 | "rebar.config", 12 | "src", 13 | "test" 14 | ]} 15 | ]}. -------------------------------------------------------------------------------- /src/ipfs.erl: -------------------------------------------------------------------------------- 1 | %%% @doc ipfs module 2 | %%% @private 3 | %%% @end 4 | %%% 5 | %%% Copyright (c) 2017, Hendry Rodriguez 6 | %%% 7 | %%% The MIT License 8 | %%% 9 | %%% Permission is hereby granted, free of charge, to any person obtaining a copy 10 | %%% of this software and associated documentation files (the "Software"), to deal 11 | %%% in the Software without restriction, including without limitation the rights 12 | %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | %%% copies of the Software, and to permit persons to whom the Software is 14 | %%% furnished to do so, subject to the following conditions: 15 | %%% 16 | %%% The above copyright notice and this permission notice shall be included in 17 | %%% all copies or substantial portions of the Software. 18 | %%% 19 | %%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | %%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | %%% THE SOFTWARE. 26 | %%% 27 | %%%--------------------------------------------------------------------------------------- 28 | -module(ipfs). 29 | -compile(export_all). 30 | -import(string,[len/1]). 31 | -define(BOUNDARY, "------------e897glvjfEoq"). 32 | 33 | 34 | add(IP, PORT, PathFile, FileName)-> 35 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/add", 36 | {ok, Cont} = file:read_file(PathFile), 37 | Data = binary_to_list(Cont), 38 | Boundary = ?BOUNDARY, 39 | Body = format_multipart_formdata(Boundary, [{ FileName, Data}]), 40 | ContentType = lists:concat(["multipart/form-data; boundary=", Boundary]), 41 | Headers = [{"Content-Length", integer_to_list(length(Body))}], 42 | request(post, {URL, Headers, ContentType, Body}). 43 | 44 | 45 | cat(IP, PORT, HASH) -> 46 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/cat?arg=" ++ HASH, 47 | inets:start(), 48 | ssl:start(), 49 | R = httpc:request(get, {URL, []}, [{ssl,[{verify,0}]}], []), 50 | {_, {_, _, R1}} = R, 51 | R1. 52 | 53 | 54 | ls(IP, PORT, HASH) -> 55 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/ls/" ++ HASH, 56 | request(get, {URL, []}). 57 | 58 | 59 | size(IP, PORT, HASH) -> 60 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/object/stat/" ++ HASH, 61 | request(get, {URL, []}). 62 | 63 | 64 | pinAdd(IP, PORT, HASH) -> 65 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/pin/add/" ++ HASH, 66 | request(get, {URL, []}). 67 | 68 | 69 | id(IP, PORT, ID) -> 70 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/id", 71 | case len(ID) of 72 | 0 -> 73 | request(get, {URL, []}); 74 | _ -> 75 | P = URL ++ "/" ++ ID, 76 | request(get, {P, []}) 77 | end. 78 | id(IP, PORT) -> 79 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/id", 80 | request(get, {URL, []}). 81 | 82 | 83 | version(IP, PORT) -> 84 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/version", 85 | request(get, {URL, []}). 86 | 87 | 88 | bitswap_ledger(IP, PORT, HASH) -> 89 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/bitswap/ledger?arg=" ++ HASH, 90 | request(get, {URL, []}). 91 | 92 | bitswap_stat(IP, PORT) -> 93 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/bitswap/stat", 94 | request(get, {URL, []}). 95 | 96 | bitswap_unwant(IP, PORT, HASH) -> 97 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/bitswap/unwant?arg=" ++ HASH, 98 | request(get, {URL, []}). 99 | 100 | bitswap_wantlist(IP, PORT, HASH) -> 101 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/bitswap/wantlist?peer=" ++ HASH, 102 | request(get, {URL, []}). 103 | 104 | 105 | block_get(IP, PORT, HASH) -> 106 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/block/get?arg=" ++ HASH, 107 | request(get, {URL, []}). 108 | 109 | block_put(IP, PORT, PathFile, FileName)-> 110 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/block/put?format=v0&mhtype=sha2-256&mhlen=-1", 111 | {ok, Cont} = file:read_file(PathFile), 112 | Data = binary_to_list(Cont), 113 | Boundary = ?BOUNDARY, 114 | Body = format_multipart_formdata(Boundary, [{ FileName, Data}]), 115 | ContentType = lists:concat(["multipart/form-data; boundary=", Boundary]), 116 | Headers = [{"Content-Length", integer_to_list(length(Body))}], 117 | request(post, {URL, Headers, ContentType, Body}). 118 | 119 | block_rm(IP, PORT, HASH) -> 120 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/block/rm?arg=" ++ HASH ++ "&force=false&quiet=false", 121 | request(get, {URL, []}). 122 | 123 | block_stat(IP, PORT, HASH) -> 124 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/block/stat?arg=" ++ HASH, 125 | request(get, {URL, []}). 126 | 127 | 128 | bootstrap_add_default(IP, PORT) -> 129 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/bootstrap/add/default", 130 | request(get, {URL, []}). 131 | 132 | bootstrap_list(IP, PORT) -> 133 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/bootstrap/list", 134 | request(get, {URL, []}). 135 | 136 | bootstrap_rm_all(IP, PORT) -> 137 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/bootstrap/rm/all", 138 | request(get, {URL, []}). 139 | 140 | 141 | commands(IP, PORT) -> 142 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/commands?flags=false", 143 | request(get, {URL, []}). 144 | 145 | 146 | dag_get(IP, PORT, Key) -> 147 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dag/get?arg=" ++ Key, 148 | request(get, {URL, []}). 149 | 150 | dag_put(IP, PORT, PathFile, FileName)-> 151 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dag/put?format=cbor&input-enc=json", 152 | {ok, Cont} = file:read_file(PathFile), 153 | Data = binary_to_list(Cont), 154 | Boundary = ?BOUNDARY, 155 | Body = format_multipart_formdata(Boundary, [{ FileName, Data}]), 156 | ContentType = lists:concat(["multipart/form-data; boundary=", Boundary]), 157 | Headers = [{"Content-Length", integer_to_list(length(Body))}], 158 | request(post, {URL, Headers, ContentType, Body}). 159 | 160 | 161 | dht_findpeer(IP, PORT, Peerid) -> 162 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dht/findpeer?arg=" ++ Peerid ++ "&verbose=false", 163 | request(get, {URL, []}). 164 | 165 | dht_findprovs(IP, PORT, Key) -> 166 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dht/findprovs?arg=" ++ Key ++ "&verbose=false", 167 | request(get, {URL, []}). 168 | 169 | dht_get(IP, PORT, Key) -> 170 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dht/get?arg=" ++ Key ++ "&verbose=false", 171 | request(get, {URL, []}). 172 | 173 | dht_provide(IP, PORT, Key) -> 174 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dht/provide?arg=" ++ Key ++ "&verbose=false&recursive=false", 175 | request(get, {URL, []}). 176 | 177 | dht_put(IP, PORT, Key, Value) -> 178 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dht/put?arg=" ++ Key ++ "&arg=" ++ Value ++ "&verbose=false", 179 | request(get, {URL, []}). 180 | 181 | dht_query(IP, PORT, Peerid) -> 182 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/dht/query?arg=" ++ Peerid ++ "&verbose=false", 183 | request(get, {URL, []}). 184 | 185 | 186 | diag_cmds_clear(IP, PORT) -> 187 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/diag/cmds/clear", 188 | request(get, {URL, []}). 189 | 190 | diag_cmds_settime(IP, PORT, Time) -> 191 | URL = "http://" ++ IP ++ ":" ++ PORT ++ "/api/v0/diag/cmds/set-time?arg=" ++ Time, 192 | request(get, {URL, []}). 193 | 194 | 195 | format_multipart_formdata(Boundary, Files) -> 196 | FileParts = lists:map(fun({FileName, FileContent}) -> 197 | [lists:concat(["--", Boundary]), 198 | lists:concat(["Content-Disposition: file; name=\"","path","\"; filename=\"",FileName,"\""]), 199 | lists:concat(["Content-Type: ", "application/octet-stream"]), 200 | "", 201 | FileContent] 202 | end, Files), 203 | FileParts2 = lists:append(FileParts), 204 | EndingParts = [lists:concat(["--", Boundary, "--"]), ""], 205 | Parts = lists:append([ FileParts2, EndingParts]), 206 | string:join(Parts, "\r\n"). 207 | 208 | request(Method, Request) -> 209 | inets:start(), 210 | ssl:start(), 211 | R = httpc:request(Method, Request, [{ssl,[{verify,0}]}], []), 212 | response(R). 213 | 214 | response(Response) -> 215 | {I1, _} = Response, 216 | case I1 of 217 | ok -> {_, {_, _, R1}} = Response, 218 | B1 = binary:list_to_bin([R1]), 219 | Resp = jsone:decode(B1, [{object_format, tuple}]), 220 | Resp; 221 | _ -> error 222 | end. 223 | -------------------------------------------------------------------------------- /src/jsone.erl: -------------------------------------------------------------------------------- 1 | %%% @doc JSON decoding/encoding module 2 | %%% @end 3 | %%% 4 | %%% Copyright (c) 2017, Hendry Rodriguez 5 | %%% 6 | %%% The MIT License 7 | %%% 8 | %%% Permission is hereby granted, free of charge, to any person obtaining a copy 9 | %%% of this software and associated documentation files (the "Software"), to deal 10 | %%% in the Software without restriction, including without limitation the rights 11 | %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | %%% copies of the Software, and to permit persons to whom the Software is 13 | %%% furnished to do so, subject to the following conditions: 14 | %%% 15 | %%% The above copyright notice and this permission notice shall be included in 16 | %%% all copies or substantial portions of the Software. 17 | %%% 18 | %%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | %%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | %%% THE SOFTWARE. 25 | %%% 26 | %%%--------------------------------------------------------------------------------------- 27 | -module(jsone). 28 | 29 | %%-------------------------------------------------------------------------------- 30 | %% Exported API 31 | %%-------------------------------------------------------------------------------- 32 | -export([ 33 | decode/1, decode/2, 34 | try_decode/1, try_decode/2, 35 | encode/1, encode/2, 36 | try_encode/1, try_encode/2 37 | ]). 38 | 39 | -export_type([ 40 | json_value/0, 41 | json_boolean/0, 42 | json_number/0, 43 | json_string/0, 44 | json_array/0, 45 | json_object/0, 46 | json_object_members/0, 47 | json_term/0, 48 | json_object_format_tuple/0, 49 | json_object_format_proplist/0, 50 | json_object_format_map/0, 51 | json_scalar/0, 52 | 53 | encode_option/0, 54 | decode_option/0, 55 | float_format_option/0, 56 | datetime_encode_format/0, datetime_format/0, 57 | timezone/0, utc_offset_seconds/0, stack_item/0 58 | ]). 59 | 60 | %%-------------------------------------------------------------------------------- 61 | %% Types & Macros 62 | %%-------------------------------------------------------------------------------- 63 | -type json_value() :: json_number() | json_string() | json_array() | json_object() | json_boolean() | null | json_term(). 64 | -type json_boolean() :: boolean(). 65 | -type json_number() :: number(). 66 | -type json_string() :: binary() | atom() | calendar:datetime(). % NOTE: `decode/1' always returns `binary()' value 67 | -type json_array() :: [json_value()]. 68 | -type json_object() :: json_object_format_tuple() 69 | | json_object_format_proplist() 70 | | json_object_format_map(). 71 | -type json_object_members() :: [{json_string(), json_value()}]. 72 | -type json_term() :: {{json, iolist()}} | {{json_utf8, unicode:chardata()}}. 73 | %% `json_term()' allows inline already encoded JSON value. `json' variant 74 | %% expects byte encoded utf8 data values as list members. `json_utf8' expect 75 | %% Unicode code points as list members. Binaries are copied "as is" in both 76 | %% variants except `json_utf8' will check if binary contain valid `UTF-8' 77 | %% encoded data. In short, `json' uses `erlang:iolist_to_binary/1' and 78 | %% `json_utf8' uses `unicode:chardata_to_binary/1' for encoding. 79 | %% 80 | %% A simple example is worth a thousand words. 81 | %% 82 | %% ``` 83 | %% 1> S = "hélo". 84 | %% "hélo" 85 | %% 2> shell:strings(false). 86 | %% true 87 | %% 3> S. 88 | %% [104,233,108,111] 89 | %% 4> B = jsone:encode({{json, S}}). % invalid UTF-8 90 | %% <<104,233,108,111>> 91 | %% 5> B2 = jsone:encode({{json_utf8, S}}). % valid UTF-8 92 | %% <<104,195,169,108,111>> 93 | %% 6> jsone:encode({{json, B}}). 94 | %% <<104,233,108,111>> 95 | %% 7> jsone:encode({{json_utf8, B}}). 96 | %% ** exception error: {invalid_json_utf8,<<104>>,<<233,108,111>>} 97 | %% in function jsone_encode:value/4 98 | %% called as jsone_encode:value({json_utf8,<<104,233,108,111>>}, 99 | %% [],<<>>, 100 | %% {encode_opt_v2,false, 101 | %% [{scientific,20}], 102 | %% {iso8601,0}, 103 | %% string,0,0}) 104 | %% in call from jsone:encode/2 (/home/hynek/work/altworx/jsone/_build/default/lib/jsone/src/jsone.erl, line 302) 105 | %% 8> jsone:encode({{json_utf8, B2}}). 106 | %% <<104,195,169,108,111>> 107 | %% 9> shell:strings(true). 108 | %% false 109 | %% 10> jsone:encode({{json_utf8, B2}}). 110 | %% <<"hélo"/utf8>> 111 | %% 11> jsone:encode({{json, binary_to_list(B2)}}). % UTF-8 encoded list leads to valid UTF-8 112 | %% <<"hélo"/utf8>> 113 | %% ''' 114 | %% 115 | -type json_object_format_tuple() :: {json_object_members()}. 116 | -type json_object_format_proplist() :: [{}] | json_object_members(). 117 | 118 | -ifdef('NO_MAP_TYPE'). 119 | -opaque json_object_format_map() :: json_object_format_proplist(). 120 | %% `maps' is not supported in this erts version 121 | -else. 122 | -type json_object_format_map() :: map(). 123 | -endif. 124 | 125 | -type json_scalar() :: json_boolean() | json_number() | json_string(). 126 | 127 | -type float_format_option() :: {scientific, Decimals :: 0..249} 128 | | {decimals, Decimals :: 0..253} 129 | | compact. 130 | %% `scientific':
131 | %% - The float will be formatted using scientific notation with `Decimals' digits of precision.
132 | %% 133 | %% `decimals':
134 | %% - The encoded string will contain at most `Decimals' number of digits past the decimal point.
135 | %% - If `compact' is provided the trailing zeros at the end of the string are truncated.
136 | %% 137 | %% For more details, see erlang:flaot_to_list/2. 138 | %% 139 | %% ``` 140 | %% > jsone:encode(1.23). 141 | %% <<"1.22999999999999998224e+00">> 142 | %% 143 | %% > jsone:encode(1.23, [{float_format, [{scientific, 4}]}]). 144 | %% <"1.2300e+00">> 145 | %% 146 | %% > jsone:encode(1.23, [{float_format, [{scientific, 1}]}]). 147 | %% <<"1.2e+00">> 148 | %% 149 | %% > jsone:encode(1.23, [{float_format, [{decimals, 4}]}]). 150 | %% <<"1.2300">> 151 | %% 152 | %% > jsone:encode(1.23, [{float_format, [{decimals, 4}, compact]}]). 153 | %% <<"1.23">> 154 | %% ''' 155 | 156 | -type datetime_encode_format() :: Format::datetime_format() 157 | | {Format::datetime_format(), TimeZone::timezone()}. 158 | %% Datetime encoding format. 159 | %% 160 | %% The default value of `TimeZone' is `utc'. 161 | %% 162 | %% ``` 163 | %% % 164 | %% % Universal Time 165 | %% % 166 | %% > jsone:encode({{2000, 3, 10}, {10, 3, 58}}, [{datetime_format, iso8601}]). 167 | %% <<"\"2000-03-10T10:03:58Z\"">> 168 | %% 169 | %% % 170 | %% % Local Time (JST) 171 | %% % 172 | %% > jsone:encode({{2000, 3, 10}, {10, 3, 58}}, [{datetime_format, {iso8601, local}}]). 173 | %% <<"\"2000-03-10T10:03:58+09:00\"">> 174 | %% 175 | %% % 176 | %% % Explicit TimeZone Offset 177 | %% % 178 | %% > jsone:encode({{2000, 3, 10}, {10, 3, 58}}, [{datetime_format, {iso8601, -2*60*60}}]). 179 | %% <<"\"2000-03-10T10:03:58-02:00\"">> 180 | %% ''' 181 | 182 | -type datetime_format() :: iso8601. 183 | -type timezone() :: utc | local | utc_offset_seconds(). 184 | -type utc_offset_seconds() :: -86399..86399. 185 | 186 | -type encode_option() :: native_utf8 187 | | canonical_form 188 | | {float_format, [float_format_option()]} 189 | | {datetime_format, datetime_encode_format()} 190 | | {object_key_type, string | scalar | value} 191 | | {space, non_neg_integer()} 192 | | {indent, non_neg_integer()} 193 | | undefined_as_null. 194 | %% `native_utf8':
195 | %% - Encodes UTF-8 characters as a human-readable(non-escaped) string
196 | %% 197 | %% `canonical_form':
198 | %% - produce a canonical form of a JSON document
199 | %% 200 | %% `{float_format, Optoins}': 201 | %% - Encodes a `float()` value in the format which specified by `Options'
202 | %% - default: `[{scientific, 20}]'
203 | %% 204 | %% `{datetime_format, Format}`: 205 | %% - Encodes a `calendar:datetime()` value in the format which specified by `Format'
206 | %% - default: `{iso8601, utc}'
207 | %% 208 | %% `object_key_type': 209 | %% - Allowable object key type
210 | %% - `string': Only string values are allowed (i.e. `json_string()' type)
211 | %% - `scalar': In addition to `string', following values are allowed: nulls, booleans, numerics (i.e. `json_scalar()' type)
212 | %% - `value': Any json compatible values are allowed (i.e. `json_value()' type)
213 | %% - default: `string'
214 | %% - NOTE: If `scalar' or `value' option is specified, non `json_string()' key will be automatically converted to a `binary()' value (e.g. `1' => `<<"1">>', `#{}' => `<<"{}">>')
215 | %% 216 | %% `{space, N}':
217 | %% - Inserts `N' spaces after every commna and colon
218 | %% - default: `0'
219 | %% 220 | %% `{indent, N}':
221 | %% - Inserts a newline and `N' spaces for each level of indentation
222 | %% - default: `0'
223 | %% 224 | %% `undefined_as_null':
225 | %% - Encodes atom `undefined' as null value
226 | 227 | -type decode_option() :: {object_format, tuple | proplist | map} 228 | | {allow_ctrl_chars, boolean()} 229 | | {'keys', 'binary' | 'atom' | 'existing_atom' | 'attempt_atom'}. 230 | %% `object_format':
231 | %% - Decoded JSON object format
232 | %% - `tuple': An object is decoded as `{[]}' if it is empty, otherwise `{[{Key, Value}]}'.
233 | %% - `proplist': An object is decoded as `[{}]' if it is empty, otherwise `[{Key, Value}]'.
234 | %% - `map': An object is decoded as `#{}' if it is empty, otherwise `#{Key => Value}'.
235 | %% - default: `map' if OTP version is OTP-17 or more, `tuple' otherwise
236 | %% 237 | %% `allow_ctrl_chars':
238 | %% - If the value is `true', strings which contain ununescaped control characters will be regarded as a legal JSON string
239 | %% - default: `false'
240 | %% 241 | %% `keys':
242 | %% Defines way how object keys are decoded. The default value is `binary'. 243 | %% The option is compatible with `labels' option in `jsx'.
244 | %% - `binary': The key is left as a string which is encoded as binary. It's default 245 | %% and backward compatible behaviour.
246 | %% - `atom': The key is converted to an atom. Results in `badarg' if Key value 247 | %% regarded as UTF-8 is not a valid atom.
248 | %% - `existing_atom': Returns existing atom. Any key value which is not 249 | %% existing atom raises `badarg' exception.
250 | %% - `attempt_atom': Returns existing atom as `existing_atom' but returns a 251 | %% binary string if fails find one. 252 | 253 | 254 | -type stack_item() :: {Module :: module(), 255 | Function :: atom(), 256 | Arity :: arity() | (Args :: [term()]), 257 | Location :: [{file, Filename :: string()} | 258 | {line, Line :: pos_integer()}]}. 259 | %% An item in a stack back-trace. 260 | %% 261 | %% Note that the `erlang' module already defines the same `stack_item/0' type, 262 | %% but it is not exported from the module. 263 | %% So, maybe as a temporary measure, we redefine this type for passing full dialyzer analysis. 264 | 265 | %%-------------------------------------------------------------------------------- 266 | %% Exported Functions 267 | %%-------------------------------------------------------------------------------- 268 | %% @equiv decode(Json, []) 269 | -spec decode(binary()) -> json_value(). 270 | decode(Json) -> 271 | decode(Json, []). 272 | 273 | %% @doc Decodes an erlang term from json text (a utf8 encoded binary) 274 | %% 275 | %% Raises an error exception if input is not valid json 276 | %% 277 | %% ``` 278 | %% > jsone:decode(<<"1">>, []). 279 | %% 1 280 | %% 281 | %% > jsone:decode(<<"wrong json">>, []). 282 | %% ** exception error: bad argument 283 | %% in function jsone_decode:number_integer_part/4 284 | %% called as jsone_decode:number_integer_part(<<"wrong json">>,1,[],<<>>) 285 | %% in call from jsone:decode/1 (src/jsone.erl, line 71) 286 | %% ''' 287 | -spec decode(binary(), [decode_option()]) -> json_value(). 288 | decode(Json, Options) -> 289 | try 290 | {ok, Value, _} = try_decode(Json, Options), 291 | Value 292 | catch 293 | error:{badmatch, {error, {Reason, [StackItem]}}} -> 294 | erlang:raise(error, Reason, [StackItem | erlang:get_stacktrace()]) 295 | end. 296 | 297 | %% @equiv try_decode(Json, []) 298 | -spec try_decode(binary()) -> {ok, json_value(), Remainings::binary()} | {error, {Reason::term(), [stack_item()]}}. 299 | try_decode(Json) -> 300 | try_decode(Json, []). 301 | 302 | %% @doc Decodes an erlang term from json text (a utf8 encoded binary) 303 | %% 304 | %% ``` 305 | %% > jsone:try_decode(<<"[1,2,3] \"next value\"">>, []). 306 | %% {ok,[1,2,3],<<" \"next value\"">>} 307 | %% 308 | %% > jsone:try_decode(<<"wrong json">>, []). 309 | %% {error,{badarg,[{jsone_decode,number_integer_part, 310 | %% [<<"wrong json">>,1,[],<<>>], 311 | %% [{line,208}]}]}} 312 | %% ''' 313 | -spec try_decode(binary(), [decode_option()]) -> {ok, json_value(), Remainings::binary()} | {error, {Reason::term(), [stack_item()]}}. 314 | try_decode(Json, Options) -> 315 | jsone_decode:decode(Json, Options). 316 | 317 | %% @equiv encode(JsonValue, []) 318 | -spec encode(json_value()) -> binary(). 319 | encode(JsonValue) -> 320 | encode(JsonValue, []). 321 | 322 | %% @doc Encodes an erlang term into json text (a utf8 encoded binary) 323 | %% 324 | %% Raises an error exception if input is not an instance of type `json_value()' 325 | %% 326 | %% ``` 327 | %% > jsone:encode([1, null, 2]). 328 | %% <<"[1,null,2]">> 329 | %% 330 | %% > jsone:encode([1, self(), 2]). % A pid is not a json value 331 | %% ** exception error: bad argument 332 | %% in function jsone_encode:value/3 333 | %% called as jsone_encode:value(<0,34,0>,[{array_values,[2]}],<<"[1,">>) 334 | %% in call from jsone:encode/1 (src/jsone.erl, line 97) 335 | %% ''' 336 | -spec encode(json_value(), [encode_option()]) -> binary(). 337 | encode(JsonValue, Options) -> 338 | try 339 | {ok, Binary} = try_encode(JsonValue, Options), 340 | Binary 341 | catch 342 | error:{badmatch, {error, {Reason, [StackItem]}}} -> 343 | erlang:raise(error, Reason, [StackItem | erlang:get_stacktrace()]) 344 | end. 345 | 346 | %% @equiv try_encode(JsonValue, []) 347 | -spec try_encode(json_value()) -> {ok, binary()} | {error, {Reason::term(), [stack_item()]}}. 348 | try_encode(JsonValue) -> 349 | try_encode(JsonValue, []). 350 | 351 | %% @doc Encodes an erlang term into json text (a utf8 encoded binary) 352 | %% 353 | %% ``` 354 | %% > jsone:try_encode([1, null, 2]). 355 | %% {ok,<<"[1,null,2]">>} 356 | %% 357 | %% > jsone:try_encode([1, hoge, 2]). % 'hoge' atom is not a json value 358 | %% {error,{badarg,[{jsone_encode,value, 359 | %% [hoge,[{array_values,[2]}],<<"[1,">>], 360 | %% [{line,86}]}]}} 361 | %% ''' 362 | -spec try_encode(json_value(), [encode_option()]) -> {ok, binary()} | {error, {Reason::term(), [stack_item()]}}. 363 | try_encode(JsonValue, Options) -> 364 | jsone_encode:encode(JsonValue, Options). -------------------------------------------------------------------------------- /src/jsone_decode.erl: -------------------------------------------------------------------------------- 1 | %%% @doc JSON decoding module 2 | %%% @private 3 | %%% @end 4 | %%% 5 | %%% Copyright (c) 2017, Hendry Rodriguez 6 | %%% 7 | %%% The MIT License 8 | %%% 9 | %%% Permission is hereby granted, free of charge, to any person obtaining a copy 10 | %%% of this software and associated documentation files (the "Software"), to deal 11 | %%% in the Software without restriction, including without limitation the rights 12 | %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | %%% copies of the Software, and to permit persons to whom the Software is 14 | %%% furnished to do so, subject to the following conditions: 15 | %%% 16 | %%% The above copyright notice and this permission notice shall be included in 17 | %%% all copies or substantial portions of the Software. 18 | %%% 19 | %%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | %%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | %%% THE SOFTWARE. 26 | %%% 27 | %%%--------------------------------------------------------------------------------------- 28 | -module(jsone_decode). 29 | 30 | -ifdef(ENABLE_HIPE). 31 | -compile([native, {hipe, [o3]}]). 32 | -endif. 33 | 34 | %%-------------------------------------------------------------------------------- 35 | %% Exported API 36 | %%-------------------------------------------------------------------------------- 37 | -export([decode/1, decode/2]). 38 | 39 | %%-------------------------------------------------------------------------------- 40 | %% Macros & Records & Types 41 | %%-------------------------------------------------------------------------------- 42 | -define(ERROR(Function, Args), {error, {badarg, [{?MODULE, Function, Args, [{line, ?LINE}]}]}}). 43 | 44 | -ifdef('NO_MAP_TYPE'). 45 | -define(DEFAULT_OBJECT_FORMAT, tuple). 46 | -define(LIST_TO_MAP(X), error({this_erts_does_not_support_maps, X})). 47 | -else. 48 | -define(DEFAULT_OBJECT_FORMAT, map). 49 | -define(LIST_TO_MAP(X), maps:from_list(X)). 50 | -endif. 51 | 52 | -type next() :: {array_next, [jsone:json_value()]} 53 | | {object_value, jsone:json_object_members()} 54 | | {object_next, jsone:json_string(), jsone:json_object_members()}. 55 | 56 | -type whitespace_next() :: value 57 | | array 58 | | object 59 | | {array_next, [jsone:json_value()]} 60 | | {object_key, jsone:json_object_members()} 61 | | {object_value, jsone:json_string(), jsone:json_object_members()} 62 | | {object_next, jsone:json_object_members()}. 63 | 64 | -type decode_result() :: {ok, jsone:json_value(), Rest::binary()} | {error, {Reason::term(), [jsone:stack_item()]}}. 65 | 66 | -record(decode_opt_v2, 67 | { 68 | object_format=?DEFAULT_OBJECT_FORMAT :: tuple | proplist | map, 69 | allow_ctrl_chars=false :: boolean(), 70 | keys=binary :: 'binary' | 'atom' | 'existing_atom' | 'attempt_atom' 71 | }). 72 | -define(OPT, #decode_opt_v2). 73 | -type opt() :: #decode_opt_v2{}. 74 | 75 | %%-------------------------------------------------------------------------------- 76 | %% Exported Functions 77 | %%-------------------------------------------------------------------------------- 78 | -spec decode(binary()) -> decode_result(). 79 | decode(Json) -> 80 | decode(Json, []). 81 | 82 | -spec decode(binary(), [jsone:decode_option()]) -> decode_result(). 83 | decode(<>, Options) -> 84 | Opt = parse_options(Options), 85 | whitespace(Json, value, [], <<"">>, Opt). 86 | 87 | %%-------------------------------------------------------------------------------- 88 | %% Internal Functions 89 | %%-------------------------------------------------------------------------------- 90 | -spec next(binary(), jsone:json_value(), [next()], binary(), opt()) -> decode_result(). 91 | next(<>, Value, [], _Buf, _Opt) -> 92 | {ok, Value, Bin}; 93 | next(<>, Value, [Next | Nexts], Buf, Opt) -> 94 | case Next of 95 | {array_next, Values} -> whitespace(Bin, {array_next, [Value | Values]}, Nexts, Buf, Opt); 96 | {object_value, Members} -> whitespace(Bin, {object_value, Value, Members}, Nexts, Buf, Opt); 97 | {object_next, Key, Members} -> whitespace(Bin, {object_next, [{Key, Value} | Members]}, Nexts, Buf, Opt) 98 | end. 99 | 100 | -spec whitespace(binary(), whitespace_next(), [next()], binary(), opt()) -> decode_result(). 101 | whitespace(<<$ , Bin/binary>>, Next, Nexts, Buf, Opt) -> whitespace(Bin, Next, Nexts, Buf, Opt); 102 | whitespace(<<$\t, Bin/binary>>, Next, Nexts, Buf, Opt) -> whitespace(Bin, Next, Nexts, Buf, Opt); 103 | whitespace(<<$\r, Bin/binary>>, Next, Nexts, Buf, Opt) -> whitespace(Bin, Next, Nexts, Buf, Opt); 104 | whitespace(<<$\n, Bin/binary>>, Next, Nexts, Buf, Opt) -> whitespace(Bin, Next, Nexts, Buf, Opt); 105 | whitespace(<>, Next, Nexts, Buf, Opt) -> 106 | case Next of 107 | value -> value(Bin, Nexts, Buf, Opt); 108 | array -> array(Bin, Nexts, Buf, Opt); 109 | object -> object(Bin, Nexts, Buf, Opt); 110 | {object_key, Members} -> object_key(Bin, Members, Nexts, Buf, Opt); 111 | {array_next, Values} -> array_next(Bin, Values, Nexts, Buf, Opt); 112 | {object_value, Key, Members} -> object_value(Bin, Key, Members, Nexts, Buf, Opt); 113 | {object_next, Members} -> object_next(Bin, Members, Nexts, Buf, Opt) 114 | end. 115 | 116 | -spec value(binary(), [next()], binary(), opt()) -> decode_result(). 117 | value(<<"false", Bin/binary>>, Nexts, Buf, Opt) -> next(Bin, false, Nexts, Buf, Opt); 118 | value(<<"true", Bin/binary>>, Nexts, Buf, Opt) -> next(Bin, true, Nexts, Buf, Opt); 119 | value(<<"null", Bin/binary>>, Nexts, Buf, Opt) -> next(Bin, null, Nexts, Buf, Opt); 120 | value(<<$[, Bin/binary>>, Nexts, Buf, Opt) -> whitespace(Bin, array, Nexts, Buf, Opt); 121 | value(<<${, Bin/binary>>, Nexts, Buf, Opt) -> whitespace(Bin, object, Nexts, Buf, Opt); 122 | value(<<$", Bin/binary>>, Nexts, Buf, Opt) -> string(Bin, byte_size(Buf), Nexts, Buf, Opt); 123 | value(<>, Nexts, Buf, Opt) -> number(Bin, Nexts, Buf, Opt). 124 | 125 | -spec array(binary(), [next()], binary(), opt()) -> decode_result(). 126 | array(<<$], Bin/binary>>, Nexts, Buf, Opt) -> next(Bin, [], Nexts, Buf, Opt); 127 | array(<>, Nexts, Buf, Opt) -> value(Bin, [{array_next, []} | Nexts], Buf, Opt). 128 | 129 | -spec array_next(binary(), [jsone:json_value()], [next()], binary(), opt()) -> decode_result(). 130 | array_next(<<$], Bin/binary>>, Values, Nexts, Buf, Opt) -> next(Bin, lists:reverse(Values), Nexts, Buf, Opt); 131 | array_next(<<$,, Bin/binary>>, Values, Nexts, Buf, Opt) -> whitespace(Bin, value, [{array_next, Values} | Nexts], Buf, Opt); 132 | array_next(Bin, Values, Nexts, Buf, Opt) -> ?ERROR(array_next, [Bin, Values, Nexts, Buf, Opt]). 133 | 134 | -spec object(binary(), [next()], binary(), opt()) -> decode_result(). 135 | object(<<$}, Bin/binary>>, Nexts, Buf, Opt) -> next(Bin, make_object([], Opt), Nexts, Buf, Opt); 136 | object(<>, Nexts, Buf, Opt) -> object_key(Bin, [], Nexts, Buf, Opt). 137 | 138 | -spec object_key(binary(), jsone:json_object_members(), [next()], binary(), opt()) -> decode_result(). 139 | object_key(<<$", Bin/binary>>, Members, Nexts, Buf, Opt) -> string(Bin, byte_size(Buf), [{object_value, Members} | Nexts], Buf, Opt); 140 | object_key(<>, Members, Nexts, Buf, Opt) -> ?ERROR(object_key, [Bin, Members, Nexts, Buf, Opt]). 141 | 142 | -spec object_value(binary(), jsone:json_string(), jsone:json_object_members(), [next()], binary(), opt()) -> decode_result(). 143 | object_value(<<$:, Bin/binary>>, Key, Members, Nexts, Buf, Opt) -> 144 | whitespace(Bin, value, [{object_next, object_key(Key, Opt), Members} | Nexts], Buf, Opt); 145 | object_value(Bin, Key, Members, Nexts, Buf, Opt) -> ?ERROR(object_value, [Bin, Key, Members, Nexts, Buf, Opt]). 146 | 147 | -compile({inline, [object_key/2]}). 148 | object_key(Key, ?OPT{keys = binary}) -> Key; 149 | object_key(Key, ?OPT{keys = atom}) -> binary_to_atom(Key, utf8); 150 | object_key(Key, ?OPT{keys = existing_atom}) -> binary_to_existing_atom(Key, utf8); 151 | object_key(Key, ?OPT{keys = attempt_atom}) -> 152 | try binary_to_existing_atom(Key, utf8) 153 | catch error:badarg -> Key 154 | end. 155 | 156 | -spec object_next(binary(), jsone:json_object_members(), [next()], binary(), opt()) -> decode_result(). 157 | object_next(<<$}, Bin/binary>>, Members, Nexts, Buf, Opt) -> next(Bin, make_object(Members, Opt), Nexts, Buf, Opt); 158 | object_next(<<$,, Bin/binary>>, Members, Nexts, Buf, Opt) -> whitespace(Bin, {object_key, Members}, Nexts, Buf, Opt); 159 | object_next(Bin, Members, Nexts, Buf, Opt) -> ?ERROR(object_next, [Bin, Members, Nexts, Buf, Opt]). 160 | 161 | -spec string(binary(), non_neg_integer(), [next()], binary(), opt()) -> decode_result(). 162 | string(<>, Start, Nexts, Buf, Opt) -> 163 | string(Bin, Bin, Start, Nexts, Buf, Opt). 164 | 165 | -spec string(binary(), binary(), non_neg_integer(), [next()], binary(), opt()) -> decode_result(). 166 | string(<<$", Bin/binary>>, Base, Start, Nexts, Buf, Opt) -> 167 | Prefix = binary:part(Base, 0, byte_size(Base) - byte_size(Bin) - 1), 168 | case Start =:= byte_size(Buf) of 169 | true -> next(Bin, Prefix, Nexts, Buf, Opt); 170 | false -> 171 | Buf2 = <>, 172 | next(Bin, binary:part(Buf2, Start, byte_size(Buf2) - Start), Nexts, Buf2, Opt) 173 | end; 174 | string(<<$\\, B/binary>>, Base, Start, Nexts, Buf, Opt) -> 175 | Prefix = binary:part(Base, 0, byte_size(Base) - byte_size(B) - 1), 176 | case B of 177 | <<$", Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 178 | <<$/, Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 179 | <<$\\,Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 180 | <<$b, Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 181 | <<$f, Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 182 | <<$n, Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 183 | <<$r, Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 184 | <<$t, Bin/binary>> -> string(Bin, Start, Nexts, <>, Opt); 185 | <<$u, Bin/binary>> -> unicode_string(Bin, Start, Nexts, <>, Opt); 186 | _ -> ?ERROR(string, [<<$\\, B/binary>>, Base, Start, Nexts, Buf, Opt]) 187 | end; 188 | string(<<_, Bin/binary>>, Base, Start, Nexts, Buf, Opt) when Opt?OPT.allow_ctrl_chars -> 189 | string(Bin, Base, Start, Nexts, Buf, Opt); 190 | string(<>, Base, Start, Nexts, Buf, Opt) when 16#20 =< C -> 191 | string(Bin, Base, Start, Nexts, Buf, Opt); 192 | string(Bin, Base, Start, Nexts, Buf, Opt) -> 193 | ?ERROR(string, [Bin, Base, Start, Nexts, Buf, Opt]). 194 | 195 | -spec unicode_string(binary(), non_neg_integer(), [next()], binary(), opt()) -> decode_result(). 196 | unicode_string(<>, Start, Nexts, Buf, Opt) -> 197 | try binary_to_integer(N, 16) of 198 | High when 16#D800 =< High, High =< 16#DBFF -> 199 | %% surrogate pair 200 | case Bin of 201 | <<$\\, $u, N2:4/binary, Bin2/binary>> -> 202 | try binary_to_integer(N2, 16) of 203 | Low when 16#DC00 =< Low, Low =< 16#DFFF -> 204 | <> = <>, 205 | string(Bin2, Start, Nexts, <>, Opt); 206 | _ -> ?ERROR(unicode_string, [<>, Start, Nexts, Buf, Opt]) 207 | catch error:badarg -> ?ERROR(unicode_string, [<>, Start, Nexts, Buf, Opt]) 208 | end; 209 | _ -> ?ERROR(unicode_string, [<>, Start, Nexts, Buf, Opt]) 210 | end; 211 | Unicode when 16#DC00 =< Unicode, Unicode =< 16#DFFF; % second part of surrogate pair (without first part) 212 | 0 > Unicode -> 213 | ?ERROR(unicode_string, [<>, Start, Nexts, Buf, Opt]); 214 | Unicode -> 215 | string(Bin, Start, Nexts, <>, Opt) 216 | catch error:badarg -> ?ERROR(unicode_string, [<>, Start, Nexts, Buf, Opt]) 217 | end; 218 | unicode_string(Bin, Start, Nexts, Buf, Opt) -> 219 | ?ERROR(unicode_string, [Bin, Start, Nexts, Buf, Opt]). 220 | 221 | -spec number(binary(), [next()], binary(), opt()) -> decode_result(). 222 | number(<<$-, Bin/binary>>, Nexts, Buf, Opt) -> number_integer_part(Bin, -1, Nexts, Buf, Opt); 223 | number(<>, Nexts, Buf, Opt) -> number_integer_part(Bin, 1, Nexts, Buf, Opt). 224 | 225 | -spec number_integer_part(binary(), 1|-1, [next()], binary(), opt()) -> decode_result(). 226 | number_integer_part(<<$0, Bin/binary>>, Sign, Nexts, Buf, Opt) -> 227 | number_fraction_part(Bin, Sign, 0, Nexts, Buf, Opt); 228 | number_integer_part(<>, Sign, Nexts, Buf, Opt) when $1 =< C, C =< $9 -> 229 | number_integer_part_rest(Bin, C - $0, Sign, Nexts, Buf, Opt); 230 | number_integer_part(Bin, Sign, Nexts, Buf, Opt) -> 231 | ?ERROR(number_integer_part, [Bin, Sign, Nexts, Buf, Opt]). 232 | 233 | -spec number_integer_part_rest(binary(), non_neg_integer(), 1|-1, [next()], binary(), opt()) -> decode_result(). 234 | number_integer_part_rest(<>, N, Sign, Nexts, Buf, Opt) when $0 =< C, C =< $9 -> 235 | number_integer_part_rest(Bin, N * 10 + C - $0, Sign, Nexts, Buf, Opt); 236 | number_integer_part_rest(<>, N, Sign, Nexts, Buf, Opt) -> 237 | number_fraction_part(Bin, Sign, N, Nexts, Buf, Opt). 238 | 239 | -spec number_fraction_part(binary(), 1|-1, non_neg_integer(), [next()], binary(), opt()) -> decode_result(). 240 | number_fraction_part(<<$., Bin/binary>>, Sign, Int, Nexts, Buf, Opt) -> 241 | number_fraction_part_rest(Bin, Sign, Int, 0, Nexts, Buf, Opt); 242 | number_fraction_part(<>, Sign, Int, Nexts, Buf, Opt) -> 243 | number_exponation_part(Bin, Sign * Int, 0, Nexts, Buf, Opt). 244 | 245 | -spec number_fraction_part_rest(binary(), 1|-1, non_neg_integer(), non_neg_integer(), [next()], binary(), opt()) -> decode_result(). 246 | number_fraction_part_rest(<>, Sign, N, DecimalOffset, Nexts, Buf, Opt) when $0 =< C, C =< $9 -> 247 | number_fraction_part_rest(Bin, Sign, N * 10 + C - $0, DecimalOffset + 1, Nexts, Buf, Opt); 248 | number_fraction_part_rest(<>, Sign, N, DecimalOffset, Nexts, Buf, Opt) when DecimalOffset > 0 -> 249 | number_exponation_part(Bin, Sign * N, DecimalOffset, Nexts, Buf, Opt); 250 | number_fraction_part_rest(Bin, Sign, N, DecimalOffset, Nexts, Buf, Opt) -> 251 | ?ERROR(number_fraction_part_rest, [Bin, Sign, N, DecimalOffset, Nexts, Buf, Opt]). 252 | 253 | -spec number_exponation_part(binary(), integer(), non_neg_integer(), [next()], binary(), opt()) -> decode_result(). 254 | number_exponation_part(<<$e, $+, Bin/binary>>, N, DecimalOffset, Nexts, Buf, Opt) -> 255 | number_exponation_part(Bin, N, DecimalOffset, 1, 0, true, Nexts, Buf, Opt); 256 | number_exponation_part(<<$E, $+, Bin/binary>>, N, DecimalOffset, Nexts, Buf, Opt) -> 257 | number_exponation_part(Bin, N, DecimalOffset, 1, 0, true, Nexts, Buf, Opt); 258 | number_exponation_part(<<$e, $-, Bin/binary>>, N, DecimalOffset, Nexts, Buf, Opt) -> 259 | number_exponation_part(Bin, N, DecimalOffset, -1, 0, true, Nexts, Buf, Opt); 260 | number_exponation_part(<<$E, $-, Bin/binary>>, N, DecimalOffset, Nexts, Buf, Opt) -> 261 | number_exponation_part(Bin, N, DecimalOffset, -1, 0, true, Nexts, Buf, Opt); 262 | number_exponation_part(<<$e, Bin/binary>>, N, DecimalOffset, Nexts, Buf, Opt) -> 263 | number_exponation_part(Bin, N, DecimalOffset, 1, 0, true, Nexts, Buf, Opt); 264 | number_exponation_part(<<$E, Bin/binary>>, N, DecimalOffset, Nexts, Buf, Opt) -> 265 | number_exponation_part(Bin, N, DecimalOffset, 1, 0, true, Nexts, Buf, Opt); 266 | number_exponation_part(<>, N, DecimalOffset, Nexts, Buf, Opt) -> 267 | case DecimalOffset of 268 | 0 -> next(Bin, N, Nexts, Buf, Opt); 269 | _ -> next(Bin, N / math:pow(10, DecimalOffset), Nexts, Buf, Opt) 270 | end. 271 | 272 | -spec number_exponation_part(binary(), integer(), non_neg_integer(), 1|-1, non_neg_integer(), boolean(), [next()], binary(), opt()) -> decode_result(). 273 | number_exponation_part(<>, N, DecimalOffset, ExpSign, Exp, _, Nexts, Buf, Opt) when $0 =< C, C =< $9 -> 274 | number_exponation_part(Bin, N, DecimalOffset, ExpSign, Exp * 10 + C - $0, false, Nexts, Buf, Opt); 275 | number_exponation_part(<>, N, DecimalOffset, ExpSign, Exp, false, Nexts, Buf, Opt) -> 276 | Pos = ExpSign * Exp - DecimalOffset, 277 | try N * math:pow(10, Pos) 278 | of Res -> next(Bin, Res, Nexts, Buf, Opt) 279 | catch error:badarith -> 280 | ?ERROR(number_exponation_part, [Bin, N, DecimalOffset, ExpSign, Exp, false, Nexts, Buf, Opt]) 281 | end; 282 | number_exponation_part(Bin, N, DecimalOffset, ExpSign, Exp, IsFirst, Nexts, Buf, Opt) -> 283 | ?ERROR(number_exponation_part, [Bin, N, DecimalOffset, ExpSign, Exp, IsFirst, Nexts, Buf, Opt]). 284 | 285 | -spec make_object(jsone:json_object_members(), opt()) -> jsone:json_object(). 286 | make_object(Members, ?OPT{object_format = tuple}) -> {lists:reverse(Members)}; 287 | make_object(Members, ?OPT{object_format = map}) -> ?LIST_TO_MAP(Members); 288 | make_object([], _) -> [{}]; 289 | make_object(Members, _) -> lists:reverse(Members). 290 | 291 | -spec parse_options([jsone:decode_option()]) -> opt(). 292 | parse_options(Options) -> 293 | parse_option(Options, ?OPT{}). 294 | 295 | -spec parse_option([jsone:decode_option()], opt()) -> opt(). 296 | parse_option([], Opt) -> Opt; 297 | parse_option([{object_format,F}|T], Opt) when F =:= tuple; F =:= proplist; F =:= map -> 298 | parse_option(T, Opt?OPT{object_format=F}); 299 | parse_option([{allow_ctrl_chars,B}|T], Opt) when is_boolean(B) -> 300 | parse_option(T, Opt?OPT{allow_ctrl_chars=B}); 301 | parse_option([{keys, K}|T], Opt) 302 | when K =:= binary; K =:= atom; K =:= existing_atom; K =:= attempt_atom -> 303 | parse_option(T, Opt?OPT{keys = K}); 304 | parse_option(List, Opt) -> 305 | error(badarg, [List, Opt]). 306 | -------------------------------------------------------------------------------- /src/jsone_encode.erl: -------------------------------------------------------------------------------- 1 | %%% @doc JSON encoding module 2 | %%% @private 3 | %%% @end 4 | %%% 5 | %%% Copyright (c) 2017, Hendry Rodriguez 6 | %%% 7 | %%% The MIT License 8 | %%% 9 | %%% Permission is hereby granted, free of charge, to any person obtaining a copy 10 | %%% of this software and associated documentation files (the "Software"), to deal 11 | %%% in the Software without restriction, including without limitation the rights 12 | %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | %%% copies of the Software, and to permit persons to whom the Software is 14 | %%% furnished to do so, subject to the following conditions: 15 | %%% 16 | %%% The above copyright notice and this permission notice shall be included in 17 | %%% all copies or substantial portions of the Software. 18 | %%% 19 | %%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | %%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | %%% THE SOFTWARE. 26 | %%% 27 | %%%--------------------------------------------------------------------------------------- 28 | -module(jsone_encode). 29 | 30 | -ifdef(ENABLE_HIPE). 31 | -compile([native, {hipe, [o3]}]). 32 | -endif. 33 | 34 | %%-------------------------------------------------------------------------------- 35 | %% Exported API 36 | %%-------------------------------------------------------------------------------- 37 | -export([encode/1, encode/2]). 38 | 39 | %%-------------------------------------------------------------------------------- 40 | %% Macros & Records & Types 41 | %%-------------------------------------------------------------------------------- 42 | -define(ERROR(Function, Args), {error, {badarg, [{?MODULE, Function, Args, [{line, ?LINE}]}]}}). 43 | -define(IS_STR(X), (is_binary(X) orelse is_atom(X))). 44 | -define(IS_UINT(X), (is_integer(X) andalso X >= 0)). 45 | -define(IS_PNUM(X), (is_number(X) andalso X >=0)). 46 | -define(IS_DATETIME(Y,M,D,H,Mi,S), (?IS_UINT(Y) andalso ?IS_UINT(M) andalso ?IS_UINT(D) andalso 47 | ?IS_UINT(H) andalso ?IS_UINT(Mi) andalso 48 | ?IS_PNUM(S))). 49 | 50 | -ifdef('NO_MAP_TYPE'). 51 | -define(IS_MAP(X), is_tuple(X)). 52 | -define(ENCODE_MAP(Value, Nexts, Buf, Opt), ?ERROR(value, [Value, Nexts, Buf, Opt])). 53 | -else. 54 | -define(IS_MAP(X), is_map(X)). 55 | -define(ENCODE_MAP(Value, Nexts, Buf, Opt), object(maps:to_list(Value), Nexts, Buf, Opt)). 56 | -endif. 57 | 58 | -type encode_result() :: {ok, binary()} | {error, {Reason::term(), [jsone:stack_item()]}}. 59 | -type next() :: {array_values, [jsone:json_value()]} 60 | | {object_value, jsone:json_value(), jsone:json_object_members()} 61 | | {object_members, jsone:json_object_members()} 62 | | {char, binary()}. 63 | 64 | -record(encode_opt_v2, { 65 | native_utf8 = false :: boolean(), 66 | canonical_form = false :: boolean(), 67 | float_format = [{scientific, 20}] :: [jsone:float_format_option()], 68 | datetime_format = {iso8601, 0} :: {jsone:datetime_format(), jsone:utc_offset_seconds()}, 69 | object_key_type = string :: string | scalar | value, 70 | space = 0 :: non_neg_integer(), 71 | indent = 0 :: non_neg_integer(), 72 | undefined_as_null = false :: boolean() 73 | }). 74 | -define(OPT, #encode_opt_v2). 75 | -type opt() :: #encode_opt_v2{}. 76 | 77 | %%-------------------------------------------------------------------------------- 78 | %% Exported Functions 79 | %%-------------------------------------------------------------------------------- 80 | -spec encode(jsone:json_value()) -> encode_result(). 81 | encode(Value) -> 82 | encode(Value, []). 83 | 84 | -spec encode(jsone:json_value(), [jsone:encode_option()]) -> encode_result(). 85 | encode(Value, Options) -> 86 | Opt = parse_options(Options), 87 | value(Value, [], <<"">>, Opt). 88 | 89 | %%-------------------------------------------------------------------------------- 90 | %% Internal Functions 91 | %%-------------------------------------------------------------------------------- 92 | -spec next([next()], binary(), opt()) -> encode_result(). 93 | next([], Buf, _) -> {ok, Buf}; 94 | next(Level = [Next | Nexts], Buf, Opt) -> 95 | case Next of 96 | {array_values, Values} -> 97 | case Values of 98 | [] -> array_values(Values, Nexts, Buf, Opt); 99 | _ -> array_values(Values, Nexts, pp_newline_or_space(<>, Level, Opt), Opt) 100 | end; 101 | {object_value, Value, Members} -> 102 | object_value(Value, Members, Nexts, pp_space(<>, Opt), Opt); 103 | {object_members, Members} -> 104 | case Members of 105 | [] -> object_members(Members, Nexts, Buf, Opt); 106 | _ -> object_members(Members, Nexts, pp_newline_or_space(<>, Level, Opt), Opt) 107 | end; 108 | {char, C} -> 109 | next(Nexts, <>, Opt) 110 | end. 111 | 112 | -spec value(jsone:json_value(), [next()], binary(), opt()) -> encode_result(). 113 | value(null, Nexts, Buf, Opt) -> next(Nexts, <>, Opt); 114 | value(undefined, Nexts, Buf, Opt = ?OPT{undefined_as_null = true}) -> next(Nexts, <>, Opt); 115 | value(false, Nexts, Buf, Opt) -> next(Nexts, <>, Opt); 116 | value(true, Nexts, Buf, Opt) -> next(Nexts, <>, Opt); 117 | value({{json, T}}, Nexts, Buf, Opt) -> 118 | try 119 | next(Nexts, <>, Opt) 120 | catch 121 | error:badarg -> 122 | ?ERROR(value, [{json, T}, Nexts, Buf, Opt]) 123 | end; 124 | value({{json_utf8, T}}, Nexts, Buf, Opt) -> 125 | try unicode:characters_to_binary(T) of 126 | {error, OK, Invalid} -> 127 | {error, {{invalid_json_utf8, OK, Invalid}, [{?MODULE, value, [{json_utf8, T}, Nexts, Buf, Opt], [{line, ?LINE}]}]}}; 128 | B when is_binary(B) -> 129 | next(Nexts, <>, Opt) 130 | catch 131 | error:badarg -> 132 | ?ERROR(value, [{json_utf8, T}, Nexts, Buf, Opt]) 133 | end; 134 | value(Value, Nexts, Buf, Opt) when is_integer(Value) -> next(Nexts, <>, Opt); 135 | value(Value, Nexts, Buf, Opt) when is_float(Value) -> next(Nexts, <>, Opt); 136 | value(Value, Nexts, Buf, Opt) when ?IS_STR(Value) -> string(Value, Nexts, Buf, Opt); 137 | value({{_,_,_},{_,_,_}} = Value, Nexts, Buf, Opt) -> datetime(Value, Nexts, Buf, Opt); 138 | value({Value}, Nexts, Buf, Opt) -> object(Value, Nexts, Buf, Opt); 139 | value([{}], Nexts, Buf, Opt) -> object([], Nexts, Buf, Opt); 140 | value([{{_,_,_},{_,_,_}}|_] = Value, Nexts, Buf, Opt)-> array(Value, Nexts, Buf, Opt); 141 | value([{_, _}|_] = Value, Nexts, Buf, Opt) -> object(Value, Nexts, Buf, Opt); 142 | value(Value, Nexts, Buf, Opt) when ?IS_MAP(Value) -> ?ENCODE_MAP(Value, Nexts, Buf, Opt); 143 | value(Value, Nexts, Buf, Opt) when is_list(Value) -> array(Value, Nexts, Buf, Opt); 144 | value(Value, Nexts, Buf, Opt) -> ?ERROR(value, [Value, Nexts, Buf, Opt]). 145 | 146 | -spec string(jsone:json_string(), [next()], binary(), opt()) -> encode_result(). 147 | string(<>, Nexts, Buf, Opt) -> 148 | escape_string(Str, Nexts, <>, Opt); 149 | string(Str, Nexts, Buf, Opt) -> 150 | string(atom_to_binary(Str, utf8), Nexts, Buf, Opt). 151 | 152 | -spec datetime(calendar:datetime(), [next()], binary(), opt()) -> encode_result(). 153 | datetime({{Y,M,D}, {H,Mi,S}}, Nexts, Buf, Opt) when ?IS_DATETIME(Y,M,D,H,Mi,S) -> 154 | {iso8601, Tz} = Opt?OPT.datetime_format, 155 | Str = 156 | [format_year(Y), $-, format2digit(M), $-, format2digit(D), $T, 157 | format2digit(H), $:, format2digit(Mi), $:, format_seconds(S), 158 | format_tz(Tz)], 159 | next(Nexts, <>, Opt); 160 | datetime(Datetime, Nexts, Buf, Opt) -> 161 | ?ERROR(datetime, [Datetime, Nexts, Buf, Opt]). 162 | 163 | -ifndef(NO_DIALYZER_SPEC). 164 | -dialyzer({no_improper_lists, [format_year/1]}). 165 | -endif. 166 | -spec format_year(non_neg_integer()) -> iodata(). 167 | format_year(Y) when Y > 999 -> integer_to_binary(Y); 168 | format_year(Y) -> 169 | B = integer_to_binary(Y), 170 | [lists:duplicate(4-byte_size(B), $0)|B]. 171 | 172 | -spec format2digit(non_neg_integer()) -> iolist(). 173 | format2digit(0) -> "00"; 174 | format2digit(1) -> "01"; 175 | format2digit(2) -> "02"; 176 | format2digit(3) -> "03"; 177 | format2digit(4) -> "04"; 178 | format2digit(5) -> "05"; 179 | format2digit(6) -> "06"; 180 | format2digit(7) -> "07"; 181 | format2digit(8) -> "08"; 182 | format2digit(9) -> "09"; 183 | format2digit(X) -> integer_to_list(X). 184 | 185 | -spec format_seconds(non_neg_integer() | float()) -> iolist(). 186 | format_seconds(S) when is_integer(S) -> format2digit(S); 187 | format_seconds(S) when is_float(S) -> io_lib:format("~6.3.0f", [S]). 188 | 189 | -spec format_tz(integer()) -> byte() | iolist(). 190 | format_tz(0) -> $Z; 191 | format_tz(Tz) when Tz > 0 -> [$+|format_tz_(Tz)]; 192 | format_tz(Tz) -> [$-|format_tz_(-Tz)]. 193 | 194 | -define(SECONDS_PER_MINUTE, 60). 195 | -define(SECONDS_PER_HOUR, 3600). 196 | -spec format_tz_(integer()) -> iolist(). 197 | format_tz_(S) -> 198 | H = S div ?SECONDS_PER_HOUR, 199 | S1 = S rem ?SECONDS_PER_HOUR, 200 | M = S1 div ?SECONDS_PER_MINUTE, 201 | [format2digit(H), $:, format2digit(M)]. 202 | 203 | -spec object_key(jsone:json_value(), [next()], binary(), opt()) -> encode_result(). 204 | object_key(Key, Nexts, Buf, Opt) when ?IS_STR(Key) -> 205 | string(Key, Nexts, Buf, Opt); 206 | object_key(Key, Nexts, Buf, Opt = ?OPT{object_key_type = scalar}) when is_number(Key) -> 207 | value(Key, [{char, $"} | Nexts], <>, Opt); 208 | object_key(Key = {{Y,M,D},{H,Mi,S}}, Nexts, Buf, Opt = ?OPT{object_key_type = Type}) when ?IS_DATETIME(Y,M,D,H,Mi,S), Type =/= string -> 209 | value(Key, Nexts, Buf, Opt); 210 | object_key(Key, Nexts, Buf, Opt = ?OPT{object_key_type = value}) -> 211 | case value(Key, [], <<>>, Opt) of 212 | {error, Reason} -> {error, Reason}; 213 | {ok, BinaryKey} -> string(BinaryKey, Nexts, Buf, Opt) 214 | end; 215 | object_key(Key, Nexts, Buf, Opt) -> 216 | ?ERROR(object_key, [Key, Nexts, Buf, Opt]). 217 | 218 | -define(H8(X), (hex(X)):16). 219 | -define(H16(X), ?H8(X bsr 8), ?H8(X band 16#FF)). 220 | 221 | -ifdef(ENABLE_HIPE). 222 | -define(COPY_UTF8, 223 | escape_string(<<2#110:3, C1:5, C2, Str/binary>>, Nexts, Buf, Opt) -> 224 | escape_string(Str, Nexts, <>, Opt); 225 | escape_string(<<2#1110:4, C1:4, C2:16, Str/binary>>, Nexts, Buf, Opt) -> 226 | escape_string(Str, Nexts, <>, Opt); 227 | escape_string(<<2#11110:5, C1:3, C2:24, Str/binary>>, Nexts, Buf, Opt) -> 228 | escape_string(Str, Nexts, <>, Opt) 229 | ). 230 | -else. 231 | -define(COPY_UTF8, 232 | escape_string(<>, Nexts, Buf, Opt) -> 233 | escape_string(Str, Nexts, <>, Opt) 234 | ). 235 | -endif. 236 | 237 | -spec escape_string(binary(), [next()], binary(), opt()) -> encode_result(). 238 | escape_string(<<"">>, Nexts, Buf, Opt) -> next(Nexts, <>, Opt); 239 | escape_string(<<$", Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 240 | escape_string(<<$\/, Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 241 | escape_string(<<$\\, Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 242 | escape_string(<<$\b, Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 243 | escape_string(<<$\f, Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 244 | escape_string(<<$\n, Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 245 | escape_string(<<$\r, Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 246 | escape_string(<<$\t, Str/binary>>, Nexts, Buf, Opt) -> escape_string(Str, Nexts, <>, Opt); 247 | escape_string(<<0:1, C:7, Str/binary>>, Nexts, Buf, Opt) -> 248 | case C < 16#20 of 249 | true -> escape_string(Str, Nexts, <>, Opt); 250 | false -> escape_string(Str, Nexts, <>, Opt) 251 | end; 252 | escape_string(<>, Nexts, Buf, Opt = ?OPT{native_utf8 = false}) -> 253 | NewBuf = if 254 | Ch =< 16#FFFF -> <>; 255 | true -> 256 | <> = <>, 257 | <> 258 | end, 259 | escape_string(Str, Nexts, NewBuf, Opt); 260 | ?COPY_UTF8; 261 | escape_string(Str, Nexts, Buf, Opt) -> 262 | ?ERROR(escape_string, [Str, Nexts, Buf, Opt]). 263 | 264 | -compile({inline, [hex/1]}). 265 | -spec hex(byte()) -> 0..16#FFFF. 266 | hex(X) -> 267 | element( 268 | X+1, 269 | {16#3030, 16#3031, 16#3032, 16#3033, 16#3034, 16#3035, 16#3036, 16#3037, 270 | 16#3038, 16#3039, 16#3061, 16#3062, 16#3063, 16#3064, 16#3065, 16#3066, 271 | 16#3130, 16#3131, 16#3132, 16#3133, 16#3134, 16#3135, 16#3136, 16#3137, 272 | 16#3138, 16#3139, 16#3161, 16#3162, 16#3163, 16#3164, 16#3165, 16#3166, 273 | 16#3230, 16#3231, 16#3232, 16#3233, 16#3234, 16#3235, 16#3236, 16#3237, 274 | 16#3238, 16#3239, 16#3261, 16#3262, 16#3263, 16#3264, 16#3265, 16#3266, 275 | 16#3330, 16#3331, 16#3332, 16#3333, 16#3334, 16#3335, 16#3336, 16#3337, 276 | 16#3338, 16#3339, 16#3361, 16#3362, 16#3363, 16#3364, 16#3365, 16#3366, 277 | 16#3430, 16#3431, 16#3432, 16#3433, 16#3434, 16#3435, 16#3436, 16#3437, 278 | 16#3438, 16#3439, 16#3461, 16#3462, 16#3463, 16#3464, 16#3465, 16#3466, 279 | 16#3530, 16#3531, 16#3532, 16#3533, 16#3534, 16#3535, 16#3536, 16#3537, 280 | 16#3538, 16#3539, 16#3561, 16#3562, 16#3563, 16#3564, 16#3565, 16#3566, 281 | 16#3630, 16#3631, 16#3632, 16#3633, 16#3634, 16#3635, 16#3636, 16#3637, 282 | 16#3638, 16#3639, 16#3661, 16#3662, 16#3663, 16#3664, 16#3665, 16#3666, 283 | 16#3730, 16#3731, 16#3732, 16#3733, 16#3734, 16#3735, 16#3736, 16#3737, 284 | 16#3738, 16#3739, 16#3761, 16#3762, 16#3763, 16#3764, 16#3765, 16#3766, 285 | 16#3830, 16#3831, 16#3832, 16#3833, 16#3834, 16#3835, 16#3836, 16#3837, 286 | 16#3838, 16#3839, 16#3861, 16#3862, 16#3863, 16#3864, 16#3865, 16#3866, 287 | 16#3930, 16#3931, 16#3932, 16#3933, 16#3934, 16#3935, 16#3936, 16#3937, 288 | 16#3938, 16#3939, 16#3961, 16#3962, 16#3963, 16#3964, 16#3965, 16#3966, 289 | 16#6130, 16#6131, 16#6132, 16#6133, 16#6134, 16#6135, 16#6136, 16#6137, 290 | 16#6138, 16#6139, 16#6161, 16#6162, 16#6163, 16#6164, 16#6165, 16#6166, 291 | 16#6230, 16#6231, 16#6232, 16#6233, 16#6234, 16#6235, 16#6236, 16#6237, 292 | 16#6238, 16#6239, 16#6261, 16#6262, 16#6263, 16#6264, 16#6265, 16#6266, 293 | 16#6330, 16#6331, 16#6332, 16#6333, 16#6334, 16#6335, 16#6336, 16#6337, 294 | 16#6338, 16#6339, 16#6361, 16#6362, 16#6363, 16#6364, 16#6365, 16#6366, 295 | 16#6430, 16#6431, 16#6432, 16#6433, 16#6434, 16#6435, 16#6436, 16#6437, 296 | 16#6438, 16#6439, 16#6461, 16#6462, 16#6463, 16#6464, 16#6465, 16#6466, 297 | 16#6530, 16#6531, 16#6532, 16#6533, 16#6534, 16#6535, 16#6536, 16#6537, 298 | 16#6538, 16#6539, 16#6561, 16#6562, 16#6563, 16#6564, 16#6565, 16#6566, 299 | 16#6630, 16#6631, 16#6632, 16#6633, 16#6634, 16#6635, 16#6636, 16#6637, 300 | 16#6638, 16#6639, 16#6661, 16#6662, 16#6663, 16#6664, 16#6665, 16#6666} 301 | ). 302 | 303 | -spec array(jsone:json_array(), [next()], binary(), opt()) -> encode_result(). 304 | array(List, Nexts, Buf, Opt) -> 305 | array_values(List, Nexts, pp_newline(<>, Nexts, 1, Opt), Opt). 306 | 307 | -spec array_values(jsone:json_array(), [next()], binary(), opt()) -> encode_result(). 308 | array_values([], Nexts, Buf, Opt) -> next(Nexts, <<(pp_newline(Buf, Nexts, Opt))/binary, $]>>, Opt); 309 | array_values([X | Xs], Nexts, Buf, Opt) -> value(X, [{array_values, Xs} | Nexts], Buf, Opt). 310 | 311 | -spec object(jsone:json_object_members(), [next()], binary(), opt()) -> encode_result(). 312 | object(Members, Nexts, Buf, ?OPT{canonical_form = true}=Opt) -> 313 | object_members(lists:sort(Members), Nexts, pp_newline(<>, Nexts, 1, Opt), Opt); 314 | object(Members, Nexts, Buf, Opt) -> 315 | object_members(Members, Nexts, pp_newline(<>, Nexts, 1, Opt), Opt). 316 | 317 | -spec object_members(jsone:json_object_members(), [next()], binary(), opt()) -> encode_result(). 318 | object_members([], Nexts, Buf, Opt) -> next(Nexts, <<(pp_newline(Buf, Nexts, Opt))/binary, $}>>, Opt); 319 | object_members([{Key, Value} | Xs], Nexts, Buf, Opt) -> object_key(Key, [{object_value, Value, Xs} | Nexts], Buf, Opt); 320 | object_members(Arg, Nexts, Buf, Opt) -> ?ERROR(object_members, [Arg, Nexts, Buf, Opt]). 321 | 322 | -spec object_value(jsone:json_value(), jsone:json_object_members(), [next()], binary(), opt()) -> encode_result(). 323 | object_value(Value, Members, Nexts, Buf, Opt) -> 324 | value(Value, [{object_members, Members} | Nexts], Buf, Opt). 325 | 326 | -spec pp_space(binary(), opt()) -> binary(). 327 | pp_space(Buf, Opt) -> padding(Buf, Opt?OPT.space). 328 | 329 | -spec pp_newline(binary(), list(), opt()) -> binary(). 330 | pp_newline(Buf, Level, Opt) -> pp_newline(Buf, Level, 0, Opt). 331 | 332 | -spec pp_newline(binary(), list(), non_neg_integer(), opt()) -> binary(). 333 | pp_newline(Buf, _, _, ?OPT{indent = 0}) -> Buf; 334 | pp_newline(Buf, L, Extra, ?OPT{indent = N}) -> padding(<>, Extra * N + length(L) * N). 335 | 336 | -spec pp_newline_or_space(binary(), list(), opt()) -> binary(). 337 | pp_newline_or_space(Buf, _, Opt = ?OPT{indent = 0}) -> pp_space(Buf, Opt); 338 | pp_newline_or_space(Buf, L, Opt) -> pp_newline(Buf, L, Opt). 339 | 340 | -spec padding(binary(), non_neg_integer()) -> binary(). 341 | padding(Buf, 0) -> Buf; 342 | padding(Buf, 1) -> <>; 343 | padding(Buf, 2) -> <>; 344 | padding(Buf, 3) -> <>; 345 | padding(Buf, 4) -> <>; 346 | padding(Buf, 5) -> <>; 347 | padding(Buf, 6) -> <>; 348 | padding(Buf, 7) -> <>; 349 | padding(Buf, 8) -> <>; 350 | padding(Buf, N) -> padding(<>, N - 9). 351 | 352 | -spec parse_options([jsone:encode_option()]) -> opt(). 353 | parse_options(Options) -> 354 | parse_option(Options, ?OPT{}). 355 | 356 | -spec parse_option([jsone:encode_option()], opt()) -> opt(). 357 | parse_option([], Opt) -> Opt; 358 | parse_option([native_utf8|T], Opt) -> 359 | parse_option(T, Opt?OPT{native_utf8=true}); 360 | parse_option([canonical_form|T], Opt) -> 361 | parse_option(T, Opt?OPT{canonical_form=true}); 362 | parse_option([{float_format, F}|T], Opt) when is_list(F) -> 363 | parse_option(T, Opt?OPT{float_format = F}); 364 | parse_option([{space, N}|T], Opt) when is_integer(N), N >= 0 -> 365 | parse_option(T, Opt?OPT{space = N}); 366 | parse_option([{indent, N}|T], Opt) when is_integer(N), N >= 0 -> 367 | parse_option(T, Opt?OPT{indent = N}); 368 | parse_option([{object_key_type, Type}|T], Opt) when Type =:= string; Type =:= scalar; Type =:= value -> 369 | parse_option(T, Opt?OPT{object_key_type = Type}); 370 | parse_option([{datetime_format, Fmt}|T], Opt) -> 371 | case Fmt of 372 | iso8601 -> parse_option(T, Opt?OPT{datetime_format = {iso8601, 0}}); 373 | {iso8601, utc} -> parse_option(T, Opt?OPT{datetime_format = {iso8601, 0}}); 374 | {iso8601, local} -> parse_option(T, Opt?OPT{datetime_format = {iso8601, local_offset()}}); 375 | {iso8601, N} when -86400 < N, N < 86400 -> parse_option(T, Opt?OPT{datetime_format = {iso8601, N}}); 376 | _ -> error(badarg, [[{datetime_format, Fmt}|T], Opt]) 377 | end; 378 | parse_option([undefined_as_null|T],Opt) -> 379 | parse_option(T, Opt?OPT{undefined_as_null = true}); 380 | parse_option(List, Opt) -> 381 | error(badarg, [List, Opt]). 382 | 383 | -spec local_offset() -> jsone:utc_offset_seconds(). 384 | local_offset() -> 385 | UTC = {{1970, 1, 2}, {0,0,0}}, 386 | Local = calendar:universal_time_to_local_time({{1970, 1, 2}, {0,0,0}}), 387 | calendar:datetime_to_gregorian_seconds(Local) - calendar:datetime_to_gregorian_seconds(UTC). 388 | --------------------------------------------------------------------------------