1% Licensed under the Apache License, Version 2.0 (the "License"); you may not
2% use this file except in compliance with the License. You may obtain a copy of
3% the License at
4%
5% http://www.apache.org/licenses/LICENSE-2.0
6%
7% Unless required by applicable law or agreed to in writing, software
8% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10% License for the specific language governing permissions and limitations under
11% the License.
12
13-module(mango_json).
14
15
16-export([
17    min/0,
18    max/0,
19    cmp/2,
20    cmp_raw/2,
21    type/1,
22    special/1,
23    to_binary/1
24]).
25
26
27-define(MIN_VAL, mango_json_min).
28-define(MAX_VAL, mango_json_max).
29
30
31min() ->
32    ?MIN_VAL.
33
34
35max() ->
36    ?MAX_VAL.
37
38
39cmp(?MIN_VAL, ?MIN_VAL) ->
40    0;
41cmp(?MIN_VAL, _) ->
42    -1;
43cmp(_, ?MIN_VAL) ->
44    1;
45cmp(?MAX_VAL, ?MAX_VAL) ->
46    0;
47cmp(?MAX_VAL, _) ->
48    1;
49cmp(_, ?MAX_VAL) ->
50    -1;
51cmp(A, B) ->
52    couch_ejson_compare:less(A, B).
53
54
55cmp_raw(?MIN_VAL, ?MIN_VAL) ->
56    0;
57cmp_raw(?MIN_VAL, _) ->
58    -1;
59cmp_raw(_, ?MIN_VAL) ->
60    1;
61cmp_raw(?MAX_VAL, ?MAX_VAL) ->
62    0;
63cmp_raw(?MAX_VAL, _) ->
64    1;
65cmp_raw(_, ?MAX_VAL) ->
66    -1;
67cmp_raw(A, B) ->
68    case A < B of
69        true ->
70            -1;
71        false ->
72            case A > B of
73                true ->
74                    1;
75                false ->
76                    0
77            end
78    end.
79
80
81type(null) ->
82    <<"null">>;
83type(Bool) when is_boolean(Bool) ->
84    <<"boolean">>;
85type(Num) when is_number(Num) ->
86    <<"number">>;
87type(Str) when is_binary(Str) ->
88    <<"string">>;
89type({Props}) when is_list(Props) ->
90    <<"object">>;
91type(Vals) when is_list(Vals) ->
92    <<"array">>.
93
94
95special(?MIN_VAL) ->
96    true;
97special(?MAX_VAL) ->
98    true;
99special(_) ->
100    false.
101
102
103to_binary({Props}) ->
104    Pred = fun({Key, Value}) ->
105        {to_binary(Key), to_binary(Value)}
106    end,
107    {lists:map(Pred, Props)};
108to_binary(Data) when is_list(Data) ->
109    [to_binary(D) || D <- Data];
110to_binary(null) ->
111    null;
112to_binary(true) ->
113    true;
114to_binary(false) ->
115    false;
116to_binary(Data) when is_atom(Data) ->
117    list_to_binary(atom_to_list(Data));
118to_binary(Data) when is_number(Data) ->
119    Data;
120to_binary(Data) when is_binary(Data) ->
121    Data.