herd_simple_formats.erl 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. -module(herd_simple_formats).
  2. -export([get_date/1, get_time/1, get_datetime/1, get_ip/1]).
  3. %%% module API
  4. -spec get_date(string()) -> calendar:date() | error.
  5. get_date(Str) ->
  6. case to_int_list(Str, "-") of
  7. [Y, M, D] when Y >= 0
  8. andalso M >= 1 andalso M =< 12
  9. andalso D >= 1 andalso D =< 31 ->
  10. {Y, M, D};
  11. _ -> error
  12. end.
  13. -spec get_time(string()) -> calendar:time() | error.
  14. get_time(Str) ->
  15. case to_int_list(Str, ":") of
  16. [H, M, S] when H >= 0 andalso H =< 24
  17. andalso M >= 0 andalso M < 60
  18. andalso S >= 0 andalso S < 60 ->
  19. {H, M, S};
  20. _ -> error
  21. end.
  22. -spec get_datetime(string()) -> calendar:datetime() | error.
  23. get_datetime(Str) ->
  24. case string:tokens(Str, " ") of
  25. [DStr, TStr | _] ->
  26. case {get_date(DStr), get_time(TStr)} of
  27. {error, _} -> error;
  28. {_, error} -> error;
  29. DT -> DT
  30. end;
  31. _ -> error
  32. end.
  33. -spec get_ip(string()) -> {byte(), byte(), byte(), byte()} | error.
  34. get_ip(Str) ->
  35. Ints = lists:filter(
  36. fun(N) when is_integer(N) andalso N >= 0 andalso N =< 255 -> true;
  37. (_) -> false
  38. end, to_int_list(Str, ".")),
  39. case Ints of
  40. [N1, N2, N3, N4] -> {N1, N2, N3, N4};
  41. _ -> error
  42. end.
  43. %% inner functions
  44. -spec to_int_list(string(), string()) -> [integer()].
  45. to_int_list(Str, Delimeter) ->
  46. lists:filtermap(
  47. fun(S) ->
  48. case string:to_integer(S) of
  49. {error, _} -> false;
  50. {N, _} -> {true, N}
  51. end
  52. end,
  53. string:tokens(Str, Delimeter)).