freebsd-dev/lib/libc/string/strverscmp.3
Aymeric Wibo 05c9a0158f libc: Add strverscmp(3) and versionsort(3)
Add a strverscmp(3) function to libc, a GNU extension I implemented by
reading its glibc manual page. It orders strings following a much more
natural ordering (e.g. "ent1 < ent2 < ent10" as opposed to
"ent1 < ent10 < ent2" with strcmp(3)'s lexicographic ordering).

Also add versionsort(3) for use as scandir(3)'s compar argument.

Update manual page for scandir(3) and add one for strverscmp(3).

Reviewed by:	pstef, gbe, kib
MFC after:	1 week
Differential Revision: https://reviews.freebsd.org/D35807
2022-08-25 03:29:03 +03:00

57 lines
1.5 KiB
Groff

.\" SPDX-License-Identifier: BSD-2-Clause
.\" Copyright (c) 2022 Aymeric Wibo <obiwac@gmail.com>
.Dd July 11, 2022
.Dt STRVERSCMP 3
.Os
.Sh NAME
.Nm strverscmp
.Nd compare strings according to natural order
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In string.h
.Ft int
.Fn strverscmp "const char *s1" "const char *s2"
.Sh DESCRIPTION
The
.Fn strverscmp
function
compares the null-terminated strings
.Fa s1
and
.Fa s2
according to their natural order
and returns an integer greater than, equal to, or less than 0,
depending on whether
.Fa s1
is greater than, equal to, or less than
.Fa s2 .
.Pp
More specifically, this natural order is found by iterating over both
strings until a difference is found.
If the difference is between non-decimal characters,
.Fn strverscmp
acts like
.Xr strcmp 3
(thus, the ordering would be "a", "b", "train").
If a decimal digit is found, the whole number is read and compared
(thus, the ordering would be "9", "10", "420" which is different to lexicographic order,
what
.Xr strcmp 3
would have done).
Numbers with leading zeroes are interpreted as fractional parts (even without a decimal point),
and numbers with more leading zeroes are placed before numbers with fewer leading zeroes
(thus, the ordering would be "000", "00", "01", "010", "09", "0", "1", "9", "10").
.Sh SEE ALSO
.Xr strcmp 3 ,
.Xr versionsort 3
.Sh STANDARDS
The
.Fn strverscmp
function is a GNU extension and conforms to no standard.
.Sh HISTORY
The
.Fn strverscmp
function was added in
.Fx 14.0 .