nitro_conv.erl 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. -module(nitro_conv).
  2. % N2Z Formatter: JSON, BERT
  3. % author Maxim Sokhatsky
  4. -include_lib("nitro/include/nitro.hrl").
  5. -compile([export_all, nowarn_export_all]). % todo export
  6. % JOIN
  7. join([],_) -> [];
  8. join([Item], _Delim) -> [Item];
  9. join([Item|Items], Delim) -> [Item, Delim | join(Items,Delim)].
  10. f(S) -> f(S, []).
  11. f(S, Args) -> lists:flatten(io_lib:format(S, Args)).
  12. replace([], _, _) -> [];
  13. replace(String, S1, S2) when erlang:is_list(String), erlang:is_list(S1), erlang:is_list(S2) ->
  14. Length = erlang:length(S1),
  15. case string:substr(String, 1, Length) of
  16. S1 ->
  17. S2 ++ replace(string:substr(String, Length + 1), S1, S2);
  18. _ ->
  19. [erlang:hd(String)|replace(erlang:tl(String), S1, S2)]
  20. end.
  21. coalesce({_, Y}) -> Y;
  22. coalesce(false) -> undefined;
  23. coalesce([]) -> undefined;
  24. coalesce([H]) -> H;
  25. coalesce([undefined|T]) -> coalesce(T);
  26. coalesce([[]|T]) -> coalesce(T);
  27. coalesce([H|_]) -> H.
  28. indexof(Key, Fields) -> indexof(Key, Fields, 2).
  29. indexof(_Key, [], _N) -> undefined;
  30. indexof(Key, [Key|_T], N) -> N;
  31. indexof(Key, [_|T], N) -> indexof(Key, T, N + 1).
  32. config(App, Key, Default) ->
  33. application:get_env(App,Key,Default).
  34. os_env(Key) -> os_env(Key, "").
  35. os_env(Key, Default) ->
  36. case os:getenv(Key) of
  37. false -> Default;
  38. V -> V
  39. end.
  40. % base64 encode/decode
  41. pickle(Data) ->
  42. base64:encode(erlang:term_to_binary({Data, os:timestamp()}, [compressed])).
  43. depickle(PickledData) ->
  44. try
  45. {Data, _PickleTime} = erlang:binary_to_term(base64:decode(nitro:to_binary(PickledData))),
  46. Data
  47. catch _:_ ->
  48. undefined
  49. end.