Skip to content

Instantly share code, notes, and snippets.

@soranoba
Last active February 26, 2016 17:05
Show Gist options
  • Save soranoba/dd6f249d8949462438ee to your computer and use it in GitHub Desktop.
Save soranoba/dd6f249d8949462438ee to your computer and use it in GitHub Desktop.
split_iolist
1> c(s).
{ok,s}
2> s:s(1, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{<<"a">>,[<<"bc">>,"def",["ghi"]|<<"jkl">>]}
3> s:s(2, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{<<"ab">>,[<<"c">>,"def",["ghi"]|<<"jkl">>]}
4> s:s(3, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{<<"abc">>,["def",["ghi"]|<<"jkl">>]}
5> s:s(4, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,100],["ef",["ghi"]|<<"jkl">>]}
6> s:s(5, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"de"],["f",["ghi"]|<<"jkl">>]}
7> s:s(6, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def"],[["ghi"]|<<"jkl">>]}
8> s:s(7, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def",103],[["hi"]|<<"jkl">>]}
9> s:s(8, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def","gh"],[["i"]|<<"jkl">>]}
10> s:s(9, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def",["ghi"]],<<"jkl">>}
11> s:s(10, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def",["ghi"],<<"j">>],<<"kl">>}
12> s:s(11, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def",["ghi"],<<"jk">>],<<"l">>}
13> s:s(12, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def",["ghi"],<<"jkl">>],<<>>}
14> s:s(13, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[<<"abc">>,"def",["ghi"],<<"jkl">>],<<>>}
15> s:s(0, [<<"abc">>, "def", ["ghi"] | <<"jkl">>]).
{[],[<<"abc">>,"def",["ghi"]|<<"jkl">>]}
16> s:s(3, <<"abcde">>).
{<<"abc">>,<<"de">>}
17> s:s(5, <<"abcde">>).
{<<"abcde">>,<<>>}
-module(s).
-compile(export_all).
s(Pos, Data) ->
s(Pos, Data, []).
s(Pos, Post, [Acc]) when Pos =< 0 ->
{Acc, Post};
s(Pos, Post, Acc) when Pos =< 0 ->
{lists:reverse(Acc), Post};
s(Pos, [H | T], Acc) when is_integer(H) ->
s(Pos - 1, T, [H | Acc]);
s(Pos, Data, Acc) when is_binary(Data) ->
case byte_size(Data) > Pos of
true -> s(0, binary:part(Data, Pos, byte_size(Data) - Pos), [binary:part(Data, 0, Pos) | Acc]);
false -> s(0, <<>>, [Data | Acc])
end;
s(Pos, [H | T], Acc) ->
HSize = iolist_size(H),
case Pos >= HSize of
true -> s(Pos - HSize, T, [H | Acc]);
false ->
{Pre, Post} = s(Pos, H),
s(0, [Post | T], [Pre | Acc])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment