file_sorter(3erl)
π file_sorter(3erl) β Erlang Module Definition π
Part 1 of 2, bestie. Buckle up. π
β¨ NAME β¨
file_sorter β File sorter. Thatβs literally it, thatβs the name. π
π¦ DESCRIPTION π¦
Okay so this module is the whole file-sorting bestie. It has functions for sorting terms on files, merging already sorted files, and checking files for sortedness. No cap. πΈ
Chunks containing binary terms are read from a sequence of files, sorted internally in memory, and written on temporary files β which are then merged, producing one sorted file as output. Merging is provided as an optimization; it is faster when the files are already sorted, but it always works to sort instead of merge. π«Ά
On a file, a term is represented by a header and a binary. Two options define the format of terms on files:
{header, HeaderLength}βHeaderLengthdetermines the number of bytes preceding each binary and containing the length of the binary in bytes. Defaults to4. The order of the header bytes is defined as follows: ifBis a binary containing a header only, sizeSizeof the binary is calculated as<<Size:HeaderLength/unit:8>> = B.{format, Format}β OptionFormatdetermines the function that is applied to binaries to create the terms to be sorted. Defaults tobinary_term, which is equivalent tofun binary_to_term/1. Valuebinaryis equivalent tofun(X) -> X end, which means that the binaries are sorted as they are. This is the fastest format. IfFormatisterm,io:read/2is called to read terms. In that case, only the default value of optionheaderis allowed.
Option format also determines what is written to the sorted output file: if Format is term, then io:format/3 is called to write each term, otherwise the binary prefixed by a header is written. Notice that the binary written is the same binary that was read; the results of applying function Format are thrown away when the terms have been sorted. Reading and writing terms using the io module is much slower than reading and writing binaries. π
ποΈ Other options are:
{order, Order}β The default is to sort terms in ascending order, but that can be changed by valuedescendingor by specifying an ordering functionFun. An ordering function is antisymmetric, transitive, and total.Fun(A, B)is to returntrueifAcomes beforeBin the ordering, otherwisefalse. An example of a typical ordering function is less than or equal to,=</2. Using an ordering function slows down the sort considerably. Functionskeysort,keymergeandkeycheckdo not accept ordering functions.{unique, boolean()}β When sorting or merging files, only the first of a sequence of terms that compare equal (==) is output if this option is set totrue. Defaults tofalse, which implies that all terms that compare equal are output. When checking files for sortedness, a check that no pair of consecutive terms compares equal is done if this option is set totrue.{tmpdir, TempDirectory}β The directory where temporary files are put can be chosen explicitly. The default, implied by value"", is to put temporary files on the same directory as the sorted output file. If output is a function (see below), the directory returned byfile:get_cwd()is used instead. The names of temporary files are derived from the Erlang nodename (node()), the process identifier of the current Erlang emulator (os:getpid()), and a unique integer (erlang:unique_integer([positive])). A typical name isfs_mynode@myhost_1763_4711.17, where17is a sequence number. Existing files are overwritten. Temporary files are deleted unless some uncaught EXIT signal occurs.{compressed, boolean()}β Temporary files and the output file can be compressed. Defaultsfalse, which implies that written files are not compressed. Regardless of the value of optioncompressed, compressed files can always be read. Notice that reading and writing compressed files are significantly slower than reading and writing uncompressed files.{size, Size}β By default about512*1024bytes read from files are sorted internally. This option is rarely needed.{no_files, NoFiles}β By default 16 files are merged at a time. This option is rarely needed.
π§ Input functions, bestie
As an alternative to sorting files, a function of one argument can be specified as input. When called with argument read, the function is assumed to return either of the following:
end_of_inputor{end_of_input, Value}}when there is no more input (Valueis explained below).{Objects, Fun}, whereObjectsis a list of binaries or terms depending on the format, andFunis a new input function.
Any other value is immediately returned as value of the current call to sort or keysort. Each input function is called exactly once. If an error occurs, the last function is called with argument close, the reply of which is ignored.
π Output functions, also bestie
A function of one argument can be specified as output. The results of sorting or merging the input is collected in a non-empty sequence of variable length lists of binaries or terms depending on the format. The output function is called with one list at a time, and is assumed to return a new output function. Any other return value is immediately returned as value of the current call to the sort or merge function. Each output function is called exactly once. When some output function has been applied to all of the results or an error occurs, the last function is called with argument close, and the reply is returned as value of the current call to the sort or merge function.
If a function is specified as input and the last input function returns {end_of_input, Value}, the function specified as output is called with argument {value, Value}. This makes it easy to initiate the sequence of output functions with a value calculated by the input functions. β¨
π Example time: disk log sorting
As an example, consider sorting the terms on a disk log file. A function that reads chunks from the disk log and returns a list of binaries is used as input. The results are collected in a list of terms.
sort(Log) ->
{ok, _} = disk_log:open([{name,Log}, {mode,read_only}]),
Input = input(Log, start),
Output = output([]),
Reply = file_sorter:sort(Input, Output, {format,term}),
ok = disk_log:close(Log),
Reply.
input(Log, Cont) ->
fun(close) ->
ok;
(read) ->
case disk_log:chunk(Log, Cont) of
{error, Reason} ->
{error, Reason};
{Cont2, Terms} ->
{Terms, input(Log, Cont2)};
{Cont2, Terms, _Badbytes} ->
{Terms, input(Log, Cont2)};
eof ->
end_of_input
end
end.
output(L) ->
fun(close) ->
lists:append(lists:reverse(L));
(Terms) ->
output([Terms | L])
end.
For more examples of functions as input and output, see the end of the file_sorter module; the term format is implemented with functions. π¦
π Reason values when things go wrong
The possible values of Reason returned when an error occurs are:
bad_object,{bad_object, FileName}β Applying the format function failed for some binary, or the key(s) could not be extracted from some term.{bad_term, FileName}βio:read/2failed to read some term.{file_error, FileName, file:posix()}β For an explanation offile:posix(), seefile(3erl).{premature_eof, FileName}β End-of-file was encountered inside some binary term.
π DATA TYPES π
file_name() = file:name()
file_names() = [file:name()]
i_command() = read | close
i_reply() =
end_of_input |
{end_of_input, value()} |
{[object()], infun()} |
input_reply()
infun() = fun((i_command()) -> i_reply())
input() = file_names() | infun()
input_reply() = term()
o_command() = {value, value()} | [object()] | close
o_reply() = outfun() | output_reply()
object() = term() | binary()
outfun() = fun((o_command()) -> o_reply())
output() = file_name() | outfun()
output_reply() = term()
value() = term()
options() = [option()] | option()
option() =
{compressed, boolean()} |
{header, header_length()} |
{format, format()} |
{no_files, no_files()} |
{order, order()} |
{size, size()} |
{tmpdir, tmp_directory()} |
{unique, boolean()}
format() = binary_term | term | binary | format_fun()
format_fun() = fun((binary()) -> term())
header_length() = integer() >= 1
key_pos() = integer() >= 1 | [integer() >= 1]
no_files() = integer() >= 1
order() = ascending | descending | order_fun()
order_fun() = fun((term(), term()) -> boolean())
size() = integer() >= 0
tmp_directory() = [] | file:name()
reason() =
bad_object |
{bad_object, file_name()} |
{bad_term, file_name()} |
{file_error,
file_name(),
file:posix() | badarg | system_limit} |
{premature_eof, file_name()}
β¨ EXPORTS β¨
π«Ά check(FileName) -> Reply
π«Ά check(FileNames, Options) -> Reply
Types:
FileNames = file_names()
Options = options()
Reply = {ok, [Result]} | {error, reason()}
Result = {FileName, TermPosition, term()}
FileName = file_name()
TermPosition = integer() >= 1
Checks your files for sortedness, bestie. And if a file isn't sorted? It doesn't just vibe-check it and move on β it hands you back the first element that's out of order. The first term sitting on a file is at position 1, so like, positions start at one, not zero, ok? π
check(FileName) is literally just check([FileName], []). Same thing, shorter to type. Slay.
π keycheck(KeyPos, FileName) -> Reply
π keycheck(KeyPos, FileNames, Options) -> Reply
Types:
KeyPos = key_pos()
FileNames = file_names()
Options = options()
Reply = {ok, [Result]} | {error, reason()}
Result = {FileName, TermPosition, term()}
FileName = file_name()
TermPosition = integer() >= 1
Same sortedness check as check, but you get to point at which key you care about. If a file's not sorted, it returns the first out-of-order element. First term on a file = position 1. No cap. π
keycheck(KeyPos, FileName) is equivalent to keycheck(KeyPos, [FileName], []). Iconic shortcut behavior.
π§ keymerge(KeyPos, FileNames, Output) -> Reply
π§ keymerge(KeyPos, FileNames, Output, Options) -> Reply
Types:
KeyPos = key_pos()
FileNames = file_names()
Output = output()
Options = options()
Reply = ok | {error, reason()} | output_reply()
Merges tuples living on files. Heads up though β each input file is assumed to already be sorted on the key(s) you named. It's not gonna check for you, it trusts you. π«Ά
keymerge(KeyPos, FileNames, Output) is equivalent to keymerge(KeyPos, FileNames, Output, []).
π keysort(KeyPos, FileName) -> Reply
Types:
KeyPos = key_pos()
FileName = file_name()
Reply = ok | {error, reason()} | input_reply() | output_reply()
Sorts tuples on files. Literally that's it, that's the whole thing.
keysort(N, FileName) is equivalent to keysort(N, [FileName], FileName).
π keysort(KeyPos, Input, Output) -> Reply
π keysort(KeyPos, Input, Output, Options) -> Reply
Types:
KeyPos = key_pos()
Input = input()
Output = output()
Options = options()
Reply = ok | {error, reason()} | input_reply() | output_reply()
Sorts tuples on files, and the sort happens on the element(s) mentioned in KeyPos. Now here's the cute part: if two tuples compare equal (==) on one element, it moves on and compares the next element according to KeyPos. So it keeps going down the list until it finds a tiebreaker. And the sort is stable β meaning equal elements keep their original relative order. Main character energy, honestly. π
keysort(N, Input, Output) is equivalent to keysort(N, Input, Output, []).
π¦ merge(FileNames, Output) -> Reply
π¦ merge(FileNames, Output, Options) -> Reply
Types:
FileNames = file_names()
Output = output()
Options = options()
Reply = ok | {error, reason()} | output_reply()
Merges terms on files. Same deal as keymerge β every input file is assumed to be sorted already. You said it, not me. π
merge(FileNames, Output) is equivalent to merge(FileNames, Output, []).
πΈ sort(FileName) -> Reply
Types:
FileName = file_name()
Reply = ok | {error, reason()} | input_reply() | output_reply()
Sorts terms on files. Short king. π
sort(FileName) is equivalent to sort([FileName], FileName).
πΈ sort(Input, Output) -> Reply
πΈ sort(Input, Output, Options) -> Reply
Types:
Input = input()
Output = output()
Options = options()
Reply = ok | {error, reason()} | input_reply() | output_reply()
Sorts terms on files. That's the whole description, and honestly? Sometimes less is more. β¨
sort(Input, Output) is equivalent to sort(Input, Output, []).
ngl bestie, a lot of these takeOptionsand a lot of them just default to[]when you don't pass any. It's giving "the fourth argument is optional and everyone knows it." π«Ά
Okay that's the whole exports list, we ate and left no crumbs π
β this page came to you from Ericsson AB, running stdlib 4.3.1.3, filed under file_sorter(3erl). Go sort something, bestie. π
π¦ where this page comes from
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms