Commit 291c7b0f authored by Andrew Mayorov's avatar Andrew Mayorov

Add some useful shell utils, mostly Erlang-specific

parent 2e512059
#!/usr/bin/env escript
%%
%%! -noshell +pc unicode
main(["-h"]) ->
usage();
main(["--help"]) ->
usage();
main([From, To | MaybeNumber]) ->
BaseFrom = erlang:list_to_integer(From),
BaseTo = erlang:list_to_integer(To),
Number = erlang:list_to_binary(read_number(MaybeNumber)),
ok = convert(Number, BaseFrom, BaseTo),
erlang:halt();
main(_) ->
_ = usage(),
erlang:halt(127).
convert(Number, BaseFrom, 256) ->
file:write(standard_io, binary:encode_unsigned(parse_int_base(Number, BaseFrom)));
convert(Number, BaseFrom, BaseTo) ->
io:format("~s~n", [format_int_base(parse_int_base(Number, BaseFrom), BaseTo)]).
read_number([Number]) ->
Number;
read_number([]) ->
string:trim(re:replace(read())).
usage() ->
io:format(
"Arbitrary base integer conversions.~n"
"~n"
"Usage: basewhat <from> <to> [<number>]~n"
).
%%
-define(BLK_SIZE, 16384).
read() ->
ok = io:setopts(standard_io, [binary]),
read(<<>>).
read(Acc) ->
case file:read(standard_io, ?BLK_SIZE) of
{ok, Data} ->
read(<<Acc/bytes, Data/bytes>>);
eof ->
Acc
end.
%%
-spec format_int_base(Integer :: integer(), Base :: integer()) -> binary().
format_int_base(I, Base) when is_integer(I), is_integer(Base), Base >= 2, Base =< 62 ->
R = list_to_binary(format_int_base(abs(I), Base, [])),
if
I > 0 -> R;
I == 0 -> <<$0>>;
I < 0 -> <<$-, R/binary>>
end;
format_int_base(I, Base) ->
error(badarg, [I, Base]).
format_int_base(0, _Base, R0) ->
R0;
format_int_base(I0, Base, R0) ->
D = I0 rem Base,
I1 = I0 div Base,
R1 = if
D >= 36 -> [D - 36 + $a | R0];
D >= 10 -> [D - 10 + $A | R0];
true -> [D + $0 | R0]
end,
format_int_base(I1, Base, R1).
-spec parse_int_base(binary(), Base :: integer()) -> integer().
parse_int_base(<<$-, Bin/binary>>, Base) when byte_size(Bin) > 0 ->
-parse_int_base(Bin, Base);
parse_int_base(Bin, Base) when byte_size(Bin) > 0, is_integer(Base), Base >= 2, Base =< 62 ->
parse_int_base(Bin, Base, 0);
parse_int_base(Bin, Base) ->
error(badarg, [Bin, Base]).
parse_int_base(<<>>, _Base, R) ->
R;
parse_int_base(<<D, Bin/binary>>, Base, R0) ->
parse_int_base(Bin, Base, R0 * Base + if
D >= $a -> D - $a + 36;
D >= $A -> D - $A + 10;
true -> D - $0
end).
#!/usr/bin/env escript
%%
%%! -noshell +pc unicode
-define(BLK_SIZE, 16384).
main([Help]) when Help == "-h"; Help == "--help" ->
io:format(
"Print Erlang External Term Format in human consumable representation.~n"
"~n"
"Usage: cat <...> | etfpr~n"
);
main([]) ->
Bin = read(),
io:format("~0tp~n", [erlang:binary_to_term(Bin)]),
erlang:halt(0).
read() ->
ok = io:setopts(standard_io, [binary]),
read(<<>>).
read(Acc) ->
case file:read(standard_io, ?BLK_SIZE) of
{ok, Data} ->
read(<<Acc/bytes, Data/bytes>>);
eof ->
Acc
end.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment