diff --git a/lib/stdlib/src/binary.erl b/lib/stdlib/src/binary.erl index 8c82faebb367..6231552f851e 100644 --- a/lib/stdlib/src/binary.erl +++ b/lib/stdlib/src/binary.erl @@ -38,7 +38,8 @@ The module is provided according to Erlang Enhancement Proposal (EEP) 31. %% %% Implemented in this module: -export([replace/3, replace/4, - encode_hex/1, encode_hex/2, decode_hex/1]). + encode_hex/1, encode_hex/2, decode_hex/1, + join/2]). -export_type([cp/0]). @@ -934,6 +935,28 @@ unhex(X) -> no, 10, 11, 12, 13, 14, 15, no, no, no, no, no, no, no, no, no %96 }). +-doc """ +Joins a list of binaries together by a specified Separator. +Equivalent to `iolist_to_binary(lists:join(Separator, Binaries))` with binary:join/2 being the faster of the two. + +_Example:_ + +```erlang +1> binary:join([<<"a">>, <<"b">>, <<"c">>], <<", ">>). +<<"a, b, c">> +``` +""". +-doc(#{since => <<"OTP 27.0">>}). +-spec join([binary()], binary()) -> binary(). +join([H], _Separator) -> H; +join([H | T], Separator) -> + join(T, Separator, H). + +-spec join([binary()], binary(), binary()) -> binary(). +join([], _Separator, Acc) -> Acc; +join([H | T], Separator, Acc) -> + join(T, Separator, <>). + badarg_with_cause(Args, Cause) -> erlang:error(badarg, Args, [{error_info, #{module => erl_stdlib_errors, cause => Cause}}]). diff --git a/lib/stdlib/test/binary_module_SUITE.erl b/lib/stdlib/test/binary_module_SUITE.erl index 27eb7de92cf2..f9abc6e0177c 100644 --- a/lib/stdlib/test/binary_module_SUITE.erl +++ b/lib/stdlib/test/binary_module_SUITE.erl @@ -23,7 +23,7 @@ interesting/1,scope_return/1,random_ref_comp/1,random_ref_sr_comp/1, random_ref_fla_comp/1,parts/1, bin_to_list/1, list_to_bin/1, copy/1, referenced/1,guard/1,encode_decode/1,badargs/1,longest_common_trap/1, - check_no_invalid_read_bug/1,error_info/1, hex_encoding/1]). + check_no_invalid_read_bug/1,error_info/1, hex_encoding/1, join/1]). -export([random_number/1, make_unaligned/1]). @@ -38,7 +38,7 @@ all() -> random_ref_comp, parts, bin_to_list, list_to_bin, copy, referenced, guard, encode_decode, badargs, longest_common_trap, check_no_invalid_read_bug, - error_info, hex_encoding]. + error_info, hex_encoding, join]. -define(MASK_ERROR(EXPR),mask_error((catch (EXPR)))). @@ -260,6 +260,9 @@ badargs(Config) when is_list(Config) -> badarg = ?MASK_ERROR(binary:encode_hex([])), badarg = ?MASK_ERROR(binary:encode_hex(#{})), badarg = ?MASK_ERROR(binary:encode_hex(foo)), + + badarg = ?MASK_ERROR(binary:join([<<"a">>], ", ")), + badarg = ?MASK_ERROR(binary:join([], <<",">>)), ok. %% Whitebox test to force special trap conditions in @@ -1581,6 +1584,13 @@ do_hex_roundtrip(Bytes) -> ok end. +%% Test join/2. +join(Config) when is_list(Config) -> + <<"a, b, c">> = binary:join([<<"a">>, <<"b">>, <<"c">>], <<", ">>), + <<"a">> = binary:join([<<"a">>], <<", ">>), + badarg = ?MASK_ERROR(binary:join([<<"a">>], ", ")), + badarg = ?MASK_ERROR(binary:join([], <<",">>)). + %%% %%% Utilities. %%%