-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.erl
69 lines (62 loc) · 2.28 KB
/
cmd.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
-module(cmd).
-include("logging.hrl").
-export([parse/1, make/1, flat/1, toBin/2]).
%Por cada comando indico el tipo de sus argumentos
%%Comandos del anillo
info("SERVER") -> [int,ip,int];
info("WORK") -> [int];
info("SETPRV") -> [ip,int];
info("OKPRV") -> [];
info("OKWORK") -> [];
info("IMNXT") -> [];
info("ANNOUNCE") -> [];
info("RING") -> [int, int, string, term];
%%Comandos del cliente
info("CON") -> [];%OJO
info("LSD") -> [];
info("STAT") -> [string];
info("DEL") -> [string];
info("CRE") -> [string];
info("OPN") -> [string];
info("WRT") -> [string, int, string, int, binary];
%es como WRT pero se proporciona un offset, la pos. donde escribir
info("WRT2") -> [string, int, string, int, string, int, binary];
info("REA") -> [string, int, string, int];
%es como REA pero se proporciona un offset, la pos. donde leer
info("REA2") -> [string, int, string, int, string, int];
info("MV") -> [string, string];
info("CLO") -> [string, int];
info("BYE") -> [].
fromBin(B, binary) -> B;
fromBin(B, string) -> binary_to_list(B);
fromBin(B, int) -> list_to_integer(binary_to_list(B));
fromBin(B, ip) -> {ok, Ip}=inet_parse:address(binary_to_list(B)), Ip;
fromBin(B, term) -> binary_to_term(B).
toBin(X, binary) when is_binary(X) -> X;
toBin(X, string) when is_list(X) -> list_to_binary(X);
toBin(X, int) -> list_to_binary(io_lib:format("~p", [X]));
toBin(X, ip) -> list_to_binary(inet_parse:ntoa(X));
toBin(X, term) -> term_to_binary(X).
make([H],[HT], Acc) -> [Acc, toBin(H, HT)];
make([H|T], [HT|TT], Acc) -> make(T, TT, [Acc, toBin(H, HT),<<" ">>]).
make([H|T]) -> make([H|T], [string|info(H)], <<>>).
parse(<<>>, [], Acc) -> Acc;
parse(B, [H], Acc) -> Acc++[fromBin(B, H)];
parse(B, [H|T], Acc) ->
{P,_}=binary:match(B, <<" ">>),
parse(binary:part(B, P+1, byte_size(B)-P-1), T, Acc++[fromBin(binary:part(B, 0, P), H)]).
parse(B) ->
try
case binary:match(B, <<" ">>) of
{P,_} ->
Name=binary_to_list(binary:part(B, 0, P)),
parse(binary:part(B, P+1, byte_size(B)-P-1), info(Name), [Name]);
nomatch ->
Name=binary_to_list(B),
case info(Name) of [] -> [Name]; _ -> erlang:error(badarg) end
end
catch _:_ -> {error, B}
end.
flat(M) ->
F = fun(A, B) -> <<A/binary, B/binary>> end,
lists:foldr(F, <<>>, lists:flatten(M)).