Skip to content

Commit

Permalink
Add normalize_path/1 function to mochiweb_util.
Browse files Browse the repository at this point in the history
Function removes duplicate slashes from a string supplied as a first function
argument.

Signed-off-by: Oleg Nemanov <lego12239@yandex.ru>
  • Loading branch information
lego12239 committed Apr 27, 2016
1 parent 0ca0375 commit 3c9b72a
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/mochiweb_util.erl
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
-export([safe_relative_path/1, partition/2]).
-export([parse_qvalues/1, pick_accepted_encodings/3]).
-export([make_io/1]).
-export([normalize_path/1]).

-define(PERCENT, 37). % $\%
-define(FULLSTOP, 46). % $\.
Expand Down Expand Up @@ -586,6 +587,19 @@ make_io(Integer) when is_integer(Integer) ->
make_io(Io) when is_list(Io); is_binary(Io) ->
Io.

%% @spec normalize_path(string()) -> string()
%% @doc Remove duplicate slashes from an uri path ("//foo///bar////" becomes
%% "/foo/bar/").
normalize_path(Path) ->
normalize_path(Path, []).

normalize_path([], Acc) ->
lists:reverse(Acc);
normalize_path("/" ++ Path, "/" ++ _ = Acc) ->
normalize_path(Path, Acc);
normalize_path([C|Path], Acc) ->
normalize_path(Path, [C|Acc]).

%%
%% Tests
%%
Expand Down Expand Up @@ -990,4 +1004,35 @@ pick_accepted_encodings_test() ->
),
ok.

normalize_path_test() ->
"" = normalize_path(""),
"/" = normalize_path("/"),
"/" = normalize_path("//"),
"/" = normalize_path("///"),
"foo" = normalize_path("foo"),
"/foo" = normalize_path("/foo"),
"/foo" = normalize_path("//foo"),
"/foo" = normalize_path("///foo"),
"foo/" = normalize_path("foo/"),
"foo/" = normalize_path("foo//"),
"foo/" = normalize_path("foo///"),
"foo/bar" = normalize_path("foo/bar"),
"foo/bar" = normalize_path("foo//bar"),
"foo/bar" = normalize_path("foo///bar"),
"foo/bar" = normalize_path("foo////bar"),
"/foo/bar" = normalize_path("/foo/bar"),
"/foo/bar" = normalize_path("/foo////bar"),
"/foo/bar" = normalize_path("////foo/bar"),
"/foo/bar" = normalize_path("////foo///bar"),
"/foo/bar" = normalize_path("////foo////bar"),
"/foo/bar/" = normalize_path("/foo/bar/"),
"/foo/bar/" = normalize_path("////foo/bar/"),
"/foo/bar/" = normalize_path("/foo////bar/"),
"/foo/bar/" = normalize_path("/foo/bar////"),
"/foo/bar/" = normalize_path("///foo////bar/"),
"/foo/bar/" = normalize_path("////foo/bar////"),
"/foo/bar/" = normalize_path("/foo///bar////"),
"/foo/bar/" = normalize_path("////foo///bar////"),
ok.

-endif.

0 comments on commit 3c9b72a

Please sign in to comment.