Programming Search⌘K

Taskintro

Sort the lines of a file

Also called sort a text file, sort lines in byte order, sort lines by code point, LC_ALL=C sort.

Read a UTF-8 file, split it at each LF, and return its lines sorted by code point, which is the order of the UTF-8 bytes and the order of LC_ALL=C sort.

Task

Read a text file and return its lines in sorted order. This is the job of the sort utility with no options. POSIX says that sort shall "Sort lines of all the named files together and write the result to the specified output."1

The task needs three rules: what a line is, what the order is, and what to do with the lines that are equal. This page uses these rules:

  • A line ends at LF. POSIX defines a line as "A sequence of zero or more non- characters plus a terminating character."2 The LF is not part of the line in the result. A CR before the LF stays in the line, so a file with CRLF line ends gives lines that end in CR.
  • A last line with no LF is a line too. POSIX calls it an incomplete line: "A sequence of one or more non- characters at the end of the file."2 So the file b, LF, a gives two lines, a and b.
  • An empty line is a line. The file that holds only one LF gives one empty line. An empty file gives no lines.
  • The order is the order of the code points. The file is UTF-8, and RFC 3629 says: "The byte-value lexicographic sorting order of UTF-8 strings is the same as if ordered by character numbers."3 So a solution can compare the bytes of the lines, and the result is the order of the code points. If one line is the start of a longer line, the shorter line comes first.
  • Equal lines stay. Duplicate lines all stay in the result. Equal lines have the same bytes, so their order in the result is not important.

This order is the order of LC_ALL=C sort. It is not the order of a dictionary: all the uppercase ASCII letters come before all the lowercase ASCII letters, and 10 comes before 9. If the file does not exist, the solution reports an error.

Solutions

Each solution reads the whole file into memory, splits it at each LF, and sorts the lines. The sort is the sort of the language. The comparison is the part that needs care, because some languages compare strings in UTF-16 code units, and that order is not the order of the code points (see Pitfalls). The steps:

  1. Read all the bytes of the file.
  2. Split the bytes at each LF. If the last part is empty, remove it: it is the part after the LF at the end of the last line, or it is the only part of an empty file.
  3. Sort the lines by their bytes, or by their code points.
  4. Return the lines as strings.
  • Python. open(path, encoding='utf-8', newline='') reads the file as text. With newline='', "universal newlines mode is enabled, but line endings are returned to the caller untranslated",4 so read() keeps each CR. split('\n') splits at LF only. list.sort() sorts the lines, and "Strings (instances of str) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord()) of their characters."5
  • JavaScript and TypeScript (Node.js). readFileSync(path) gives a Buffer. A loop with indexOf(0x0a, start) and subarray cuts it into lines. lines.sort(Buffer.compare) sorts them: Node.js says that Buffer.compare "Compares buf1 to buf2, typically for the purpose of sorting arrays of Buffer instances."6 Then toString('utf8') changes each line to a string. The TypeScript file adds types only.
  • Java. Files.readAllBytes(path) gives the bytes, and Arrays.copyOfRange copies each line to a byte[]. lines.sort(Arrays::compareUnsigned) sorts them. compareUnsigned "Compares two byte arrays lexicographically, numerically treating elements as unsigned."7 A Java byte is signed, and Arrays.compare compares two elements "as if by Byte.compare(byte, byte)", so it puts the bytes above 0x7F before the ASCII bytes.7 new String(line, StandardCharsets.UTF_8) changes each line to a string.
  • C#. File.ReadAllBytes(path) gives the bytes. Array.IndexOf finds each LF, and AsMemory gives each line with no copy. The sort compares a.Span.SequenceCompareTo(b.Span), which "Determines the relative order of two read-only sequences by comparing their elements" with IComparable<T>.CompareTo.8 The elements are byte values, which are unsigned. Encoding.UTF8.GetString changes each line to a string.
  • Go. os.ReadFile(path) gives the bytes, and strings.Split at each LF gives the lines. slices.Sort(lines) sorts them. The Go specification says: "Two string values are compared lexically byte-wise."9
  • Rust. fs::read_to_string(path) reads the file and checks that it is UTF-8. text.split('\n') gives the lines, and sort_unstable sorts them. For str, "Strings are ordered lexicographically by their byte values."10 Equal lines have the same bytes, so an unstable sort gives the same result as a stable sort.
  • C. A loop of fread reads the file into a buffer that grows. The code changes each LF to a NUL, so each line is a C string in the buffer, and keeps a pointer and a length for each line. qsort sorts them with memcmp on the shorter length, and then the shorter line first. memcmp compares bytes "both interpreted as unsigned char".11 sort_lines fills a struct sorted_lines, which the caller frees with sort_lines_free, or it returns -1 and sets errno.
  • C++. A std::istreambuf_iterator<char> reads a binary std::ifstream into a std::string. find('\n', start) cuts it into a std::vector<std::string>, and std::ranges::sort sorts it. std::string compares its chars with std::char_traits<char>, and for char, lt "behaves identically to static_cast<unsigned char>(a) < static_cast<unsigned char>(b)".12 So the order is the order of the bytes, also on a machine where char is signed. The result is a std::expected (C++23), and the errors are cannot_open and read_failed.
  • Bash. LC_ALL=C sort on the file does the work. POSIX says that the comparison "shall be performed using the collating sequence of the current locale",1 so LC_ALL=C selects the POSIX locale, where the order is the order of the bytes (see Pitfalls). The output is the lines, each with an LF at the end. sort adds the LF that a last line does not have: it adds one "to the end of a file ending with an incomplete last line".1

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/.

  • simple: pear, apple, fig gives apple, fig, pear.
  • case: b, B, a, A gives A, B, a, b. The uppercase letters are 0x41 to 0x5A, and the lowercase letters are 0x61 to 0x7A.
  • numbers: 10, 9, 100 gives 10, 100, 9. The lines are text, so 1 comes before 9.
  • empty: an empty file gives [].
  • one-empty-line and empty-lines: the file that holds only one LF gives one empty line, "". In b, an empty line, a and an empty line, the two empty lines come first.
  • duplicates: b, a, b gives a, b, b.
  • no-final-newline: b, LF, a with no LF at the end gives a and b.
  • crlf: b CRLF a CRLF gives a CR and b CR. The CR stays in each line.
  • prefix: ab and a gives a, ab. The shorter line comes first.
  • whitespace: b, space a, tab c gives tab c, space a, b. Tab is 0x09 and space is 0x20, so both come before the letters.
  • non-ascii: é, z, e gives e, z, é. U+00E9 is above U+007A, and its UTF-8 bytes C3 A9 are above the byte 7A.
  • supplementary: U+1F600 and U+FF61 gives U+FF61 first. In UTF-16, U+1F600 is the two code units D83D DE00, and D83D is below FF61, so a sort of UTF-16 code units gives the other order.
  • other-line-breaks: three lines b U+2028 a, b U+001C a and b U+000C a give U+000C first, then U+001C, then U+2028. These characters are not LF, so they do not split a line.

The tests also write a file of 50000 lines b and 50000 lines a, one after the other. The case in cases/errors.jsonl must give the error not-found. The toolchain does not load that file yet, so each test file holds the case by name.

Pitfalls

  • The locale changes the order of sort. POSIX says that sort compares lines "using the collating sequence of the current locale".1 In a locale such as en_US.UTF-8, the order is close to the order of a dictionary, and it is different from one system to the next. In the POSIX locale, the order of the ASCII characters is fixed: "Characters in this list are in the same order" as in ASCII, and "If the listed characters have ASCII encoding, the other characters shall be in ascending order according to their coded character set values".13 So set LC_ALL=C when a program or a test needs the same order on each machine.
  • Numbers sort as text. With no options, sort compares the characters, so 100 comes before 9. The option -n is for numbers: "Restrict the sort key to an initial numeric string".1 The task of this page is the text order:
printf '10\n9\n100\n' | LC_ALL=C sort
echo ---
printf '10\n9\n100\n' | LC_ALL=C sort -n
Output
10
100
9
---
9
10
100
  • UTF-16 order is not code point order. JavaScript, Java and C# keep strings in UTF-16. The default sort of a JavaScript array compares "sequences of UTF-16 code unit values".14 Java String.compareTo "is based on the Unicode value of each character in the strings",15 and a Java char is one UTF-16 code unit. C# string.CompareOrdinal "Compares two String objects by evaluating the numeric values of the corresponding Char objects in each string."16 The two orders are the same for the code points up to U+FFFF. A character above U+FFFF is two code units, a surrogate pair. These code units are from D800 to DFFF, which RFC 3629 reserves "for use with the UTF-16 encoding form (as surrogate pairs)".3 So in UTF-16 order, a character above U+FFFF comes before the characters from U+E000 to U+FFFF. The solutions for these languages compare the UTF-8 bytes:
const lines = ["\u{FF61}", "\u{1F600}"];
const hex = (s) => [...s].map((c) => c.codePointAt(0).toString(16)).join(" ");
console.log([...lines].sort().map(hex));
console.log([...lines].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))).map(hex));
const units = (s) => Array.from({ length: s.length }, (_, i) => s.charCodeAt(i).toString(16)).join(" ");
console.log(lines.map(units));
Output
[ '1f600', 'ff61' ]
[ 'ff61', '1f600' ]
[ 'ff61', 'd83d de00' ]
  • Some functions split at more than LF. Python str.splitlines splits at more characters: "the boundaries are a superset of universal newlines".17 The list includes U+001C, U+000C, U+0085 and U+2028. So a line that holds one of these characters becomes two lines:
text = "b\x1ca\nc\n"
print(text.splitlines())
print(text.split("\n"))
Output
['b', 'a', 'c']
['b\x1ca', 'c', '']

Rust str::lines also changes the lines: "Lines are split at line endings that are either newlines (\n) or sequences of a carriage return followed by a line feed (\r\n)."10 So it removes the CR of a CRLF line end. The Python and Rust solutions use split with LF.

  • The last line. A split at each LF gives one empty string after the LF at the end of the file. If the code keeps it, the result has one empty line too many. If the code removes each empty string, it also removes the empty lines of the file. Remove only the last part, and only if it is empty.
  • Reading the whole file. Each solution keeps the whole file in memory, and a sort needs all the lines before it can return the first one. A file that is larger than the memory needs an external sort, which this page does not cover.

Code

The build runs the native tests of each language in a pinned toolchain.

sort_lines.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

"""Sorts the lines of a text file."""

from os import PathLike


def sort_lines(path: str | PathLike[str]) -> list[str]:
    """Returns the lines of the UTF-8 file at path, sorted by code point.

    A line ends at LF, and the LF is not part of it. A last line with no LF is
    a line too. Raises FileNotFoundError if the file does not exist.
    """
    # newline="" keeps each CR in the text. The split below uses only LF,
    # because str.splitlines also splits at other characters.
    with open(path, encoding="utf-8", newline="") as f:
        lines = f.read().split("\n")
    # After the LF at the end of the last line, split gives one empty string.
    # An empty file gives [""] too, which is no lines.
    if lines[-1] == "":
        lines.pop()
    # str compares by code point, which is the order of the UTF-8 bytes.
    lines.sort()
    return lines
test_sort_lines.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

import pytest

from sort_lines import sort_lines

# name: (the bytes of the file, the result)
CASES = {
    "simple": (b"pear\napple\nfig\n", ["apple", "fig", "pear"]),
    "case": (b"b\nB\na\nA\n", ["A", "B", "a", "b"]),
    "numbers": (b"10\n9\n100\n", ["10", "100", "9"]),
    "empty": (b"", []),
    "one-empty-line": (b"\n", [""]),
    "empty-lines": (b"b\n\na\n\n", ["", "", "a", "b"]),
    "duplicates": (b"b\na\nb\n", ["a", "b", "b"]),
    "no-final-newline": (b"b\na", ["a", "b"]),
    "crlf": (b"b\r\na\r\n", ["a\r", "b\r"]),
    "prefix": (b"ab\na\n", ["a", "ab"]),
    "whitespace": (b"b\n a\n\tc\n", ["\tc", " a", "b"]),
    "non-ascii": ("\u00e9\nz\ne\n".encode(), ["e", "z", "\u00e9"]),
    # U+FF61 is below U+1F600, but its UTF-16 code unit is above 0xD83D.
    "supplementary": ("\U0001f600\n\uff61\n".encode(), ["\uff61", "\U0001f600"]),
    # str.splitlines splits at each of these characters, but they are not LF.
    "other-line-breaks": ("b\u2028a\nb\x1ca\nb\x0ca\n".encode(), ["b\x0ca", "b\x1ca", "b\u2028a"]),
    "many-lines": (b"b\na\n" * 50000, ["a"] * 50000 + ["b"] * 50000),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path, name):
    data, expect = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(data)
    assert sort_lines(path) == expect


def test_not_found(tmp_path):
    with pytest.raises(FileNotFoundError):
        sort_lines(tmp_path / "missing.txt")
sort_lines.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

#include "sort_lines.hpp"

#include <algorithm>
#include <cstddef>
#include <fstream>
#include <iterator>

std::expected<std::vector<std::string>, SortError> sort_lines(const std::filesystem::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        return std::unexpected(SortError::cannot_open);
    }
    const std::string data{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
    if (in.bad()) {
        return std::unexpected(SortError::read_failed);
    }
    std::vector<std::string> lines;
    std::size_t start = 0;
    while (start < data.size()) {
        std::size_t end = data.find('\n', start);
        if (end == std::string::npos) {
            end = data.size();
        }
        lines.emplace_back(data, start, end - start);
        start = end + 1;
    }
    // std::string compares its chars with std::char_traits<char>, which
    // compares them as unsigned char, so the order is the order of the bytes.
    std::ranges::sort(lines);
    return lines;
}
sort_lines.hpp 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.
// since: C++23 (std::expected)

#pragma once

#include <expected>
#include <filesystem>
#include <string>
#include <vector>

enum class SortError { cannot_open, read_failed };

// Returns the lines of the UTF-8 file at path, sorted by their bytes, which is
// the order of the code points. A line ends at LF, and the LF is not part of
// it. A last line with no LF is a line too.
std::expected<std::vector<std::string>, SortError> sort_lines(const std::filesystem::path& path);
test_sort_lines.cpp 76 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

#include <cstdio>
#include <fstream>
#include <string>
#include <vector>

#include "sort_lines.hpp"

namespace {

const std::filesystem::path input = "sort_lines_input.txt";

void write(const std::string& data) {
    std::ofstream out(input, std::ios::binary);
    out.write(data.data(), static_cast<std::streamsize>(data.size()));
}

struct test_case {
    const char* name;
    std::string data;
    std::vector<std::string> want;
};

}  // namespace

int main() {
    std::string many;
    std::vector<std::string> many_want;
    for (int i = 0; i < 50000; i++) {
        many += "b\na\n";
    }
    many_want.insert(many_want.end(), 50000, "a");
    many_want.insert(many_want.end(), 50000, "b");

    const std::vector<test_case> cases = {
        {"simple", "pear\napple\nfig\n", {"apple", "fig", "pear"}},
        {"case", "b\nB\na\nA\n", {"A", "B", "a", "b"}},
        {"numbers", "10\n9\n100\n", {"10", "100", "9"}},
        {"empty", "", {}},
        {"one-empty-line", "\n", {""}},
        {"empty-lines", "b\n\na\n\n", {"", "", "a", "b"}},
        {"duplicates", "b\na\nb\n", {"a", "b", "b"}},
        {"no-final-newline", "b\na", {"a", "b"}},
        {"crlf", "b\r\na\r\n", {"a\r", "b\r"}},
        {"prefix", "ab\na\n", {"a", "ab"}},
        {"whitespace", "b\n a\n\tc\n", {"\tc", " a", "b"}},
        // The UTF-8 bytes of U+00E9 are C3 A9, which are above the byte of z.
        {"non-ascii", "\xc3\xa9\nz\ne\n", {"e", "z", "\xc3\xa9"}},
        // U+FF61 is EF BD A1 and U+1F600 is F0 9F 98 80.
        {"supplementary", "\xf0\x9f\x98\x80\n\xef\xbd\xa1\n", {"\xef\xbd\xa1", "\xf0\x9f\x98\x80"}},
        // U+2028 is E2 80 A8.
        {"other-line-breaks", "b\xe2\x80\xa8" "a\nb\x1c" "a\nb\x0c" "a\n", {"b\x0c" "a", "b\x1c" "a", "b\xe2\x80\xa8" "a"}},
        {"many-lines", many, many_want},
    };
    int failed = 0;
    for (const auto& c : cases) {
        write(c.data);
        auto got = sort_lines(input);
        if (!got || *got != c.want) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            failed++;
        }
    }
    auto missing = sort_lines("no/such/dir/missing.txt");
    if (missing || missing.error() != SortError::cannot_open) {
        std::fprintf(stderr, "case not-found failed\n");
        failed++;
    }
    std::filesystem::remove(input);
    if (failed == 0) {
        std::puts("ok");
    }
    return failed == 0 ? 0 : 1;
}
SortedLines.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/** Sorts the lines of a text file. */
public final class SortedLines {
  private SortedLines() {}

  /**
   * Returns the lines of the UTF-8 file at path, sorted by code point. A line ends at LF, and the
   * LF is not part of it. A last line with no LF is a line too.
   *
   * @throws java.nio.file.NoSuchFileException if the file does not exist
   */
  public static List<String> read(Path path) throws IOException {
    byte[] data = Files.readAllBytes(path);
    List<byte[]> lines = new ArrayList<>();
    int start = 0;
    while (start < data.length) {
      int end = start;
      while (end < data.length && data[end] != '\n') {
        end++;
      }
      lines.add(Arrays.copyOfRange(data, start, end));
      start = end + 1;
    }
    // String.compareTo compares UTF-16 chars, which is not the order of the
    // code points. Arrays.compareUnsigned compares the UTF-8 bytes, which is.
    lines.sort(Arrays::compareUnsigned);
    List<String> result = new ArrayList<>(lines.size());
    for (byte[] line : lines) {
      result.add(new String(line, StandardCharsets.UTF_8));
    }
    return result;
  }
}
SortedLinesTest.java 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class SortedLinesTest {
  @TempDir Path dir;

  private static List<String> aThenB(int n) {
    List<String> lines = new ArrayList<>(Collections.nCopies(n, "a"));
    lines.addAll(Collections.nCopies(n, "b"));
    return lines;
  }

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("simple", "pear\napple\nfig\n", List.of("apple", "fig", "pear")),
        Arguments.of("case", "b\nB\na\nA\n", List.of("A", "B", "a", "b")),
        Arguments.of("numbers", "10\n9\n100\n", List.of("10", "100", "9")),
        Arguments.of("empty", "", List.of()),
        Arguments.of("one-empty-line", "\n", List.of("")),
        Arguments.of("empty-lines", "b\n\na\n\n", List.of("", "", "a", "b")),
        Arguments.of("duplicates", "b\na\nb\n", List.of("a", "b", "b")),
        Arguments.of("no-final-newline", "b\na", List.of("a", "b")),
        Arguments.of("crlf", "b\r\na\r\n", List.of("a\r", "b\r")),
        Arguments.of("prefix", "ab\na\n", List.of("a", "ab")),
        Arguments.of("whitespace", "b\n a\n\tc\n", List.of("\tc", " a", "b")),
        Arguments.of("non-ascii", "\u00e9\nz\ne\n", List.of("e", "z", "\u00e9")),
        // U+FF61 is below U+1F600, but its UTF-16 char is above 0xD83D.
        Arguments.of("supplementary", "\ud83d\ude00\n\uff61\n", List.of("\uff61", "\ud83d\ude00")),
        Arguments.of("other-line-breaks", "b\u2028a\nb\u001ca\nb\fa\n", List.of("b\fa", "b\u001ca", "b\u2028a")),
        Arguments.of("many-lines", "b\na\n".repeat(50000), aThenB(50000)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void read(String name, String text, List<String> want) throws IOException {
    Path path = dir.resolve("input.txt");
    Files.writeString(path, text, StandardCharsets.UTF_8);
    assertEquals(want, SortedLines.read(path), name);
  }

  @Test
  void notFound() {
    assertThrows(NoSuchFileException.class, () -> SortedLines.read(dir.resolve("missing.txt")));
  }
}
sort_lines.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

#include "sort_lines.h"

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// compare orders two lines by their bytes, as unsigned char. If one line is
// the start of the other, the shorter line comes first.
static int compare(const void *a, const void *b) {
    const struct line *x = a;
    const struct line *y = b;
    int c = memcmp(x->text, y->text, x->len < y->len ? x->len : y->len);
    if (c != 0) {
        return c;
    }
    return (x->len > y->len) - (x->len < y->len);
}

// read_all reads the whole stream into a new buffer. The buffer has at least
// one free byte after the data, for a NUL.
static char *read_all(FILE *f, size_t *size) {
    size_t cap = 4096;
    size_t used = 0;
    char *data = malloc(cap);
    if (data == NULL) {
        errno = ENOMEM;
        return NULL;
    }
    for (;;) {
        if (cap - used < 2) {
            char *bigger = cap <= SIZE_MAX / 2 ? realloc(data, cap * 2) : NULL;
            if (bigger == NULL) {
                free(data);
                errno = ENOMEM;
                return NULL;
            }
            data = bigger;
            cap *= 2;
        }
        size_t n = fread(data + used, 1, cap - used - 1, f);
        used += n;
        if (n == 0) {
            break;
        }
    }
    if (ferror(f)) {
        free(data);
        errno = EIO;
        return NULL;
    }
    *size = used;
    return data;
}

int sort_lines(const char *path, struct sorted_lines *out) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    size_t size;
    char *data = read_all(f, &size);
    fclose(f);
    if (data == NULL) {
        return -1;
    }
    // Each LF ends a line. A last line with no LF is one more line.
    size_t count = 0;
    for (size_t i = 0; i < size; i++) {
        count += data[i] == '\n';
    }
    if (size > 0 && data[size - 1] != '\n') {
        count++;
    }
    struct line *lines = NULL;
    if (count > 0) {
        lines = malloc(count * sizeof *lines);
        if (lines == NULL) {
            free(data);
            errno = ENOMEM;
            return -1;
        }
    }
    // Change each LF to a NUL, so that each line is a C string too.
    size_t k = 0;
    size_t start = 0;
    for (size_t i = 0; i < size; i++) {
        if (data[i] == '\n') {
            data[i] = '\0';
            lines[k++] = (struct line){data + start, i - start};
            start = i + 1;
        }
    }
    if (start < size) {
        data[size] = '\0';
        lines[k++] = (struct line){data + start, size - start};
    }
    if (count > 1) {
        qsort(lines, count, sizeof *lines, compare);
    }
    *out = (struct sorted_lines){lines, count, data};
    return 0;
}

void sort_lines_free(struct sorted_lines *s) {
    free(s->lines);
    free(s->data);
    *s = (struct sorted_lines){NULL, 0, NULL};
}
sort_lines.h 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

#ifndef SORT_LINES_H
#define SORT_LINES_H

#include <stddef.h>

struct line {
    const char *text;  // the bytes of the line, with no LF, ended by a NUL
    size_t len;        // the number of bytes, not counting the NUL
};

struct sorted_lines {
    struct line *lines;  // the lines in byte order, or NULL if there are none
    size_t len;          // the number of lines
    char *data;          // the bytes of the file, which the lines point into
};

// sort_lines reads the file at path, splits it into lines at each LF, and
// sorts the lines by their bytes, which for UTF-8 is the order of the code
// points. A last line with no LF is a line too. It fills *out and returns 0.
// Free the result with sort_lines_free. On an error it returns -1 and sets
// errno: the error of fopen, EIO for a read error, or ENOMEM.
int sort_lines(const char *path, struct sorted_lines *out);

// sort_lines_free frees the memory of a result of sort_lines.
void sort_lines_free(struct sorted_lines *s);

#endif
test_sort_lines.c 93 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

#include "sort_lines.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char *path = "sort_lines_input.txt";

static void write_file(const char *data, size_t n) {
    FILE *f = fopen(path, "wb");
    assert(f != NULL);
    assert(fwrite(data, 1, n, f) == n);
    assert(fclose(f) == 0);
}

static void check(const char *name, const char *data, size_t size, const char *const *want, size_t n) {
    write_file(data, size);
    struct sorted_lines got;
    if (sort_lines(path, &got) != 0) {
        fprintf(stderr, "case %s: error %d\n", name, errno);
        exit(1);
    }
    if (got.len != n) {
        fprintf(stderr, "case %s: got %zu lines, want %zu\n", name, got.len, n);
        exit(1);
    }
    for (size_t i = 0; i < n; i++) {
        if (got.lines[i].len != strlen(want[i]) || strcmp(got.lines[i].text, want[i]) != 0) {
            fprintf(stderr, "case %s: line %zu is \"%s\", want \"%s\"\n", name, i, got.lines[i].text, want[i]);
            exit(1);
        }
    }
    sort_lines_free(&got);
}

// sizeof counts the bytes of the literal, but not the final NUL. The lines
// that the case wants come after the data.
#define CASE(name, data, ...)                                                        \
    do {                                                                             \
        static const char *const want[] = {__VA_ARGS__};                             \
        check(name, data, sizeof(data) - 1, want, sizeof want / sizeof want[0]);     \
    } while (0)

int main(void) {
    CASE("simple", "pear\napple\nfig\n", "apple", "fig", "pear");
    CASE("case", "b\nB\na\nA\n", "A", "B", "a", "b");
    CASE("numbers", "10\n9\n100\n", "10", "100", "9");
    check("empty", "", 0, NULL, 0);
    CASE("one-empty-line", "\n", "");
    CASE("empty-lines", "b\n\na\n\n", "", "", "a", "b");
    CASE("duplicates", "b\na\nb\n", "a", "b", "b");
    CASE("no-final-newline", "b\na", "a", "b");
    CASE("crlf", "b\r\na\r\n", "a\r", "b\r");
    CASE("prefix", "ab\na\n", "a", "ab");
    CASE("whitespace", "b\n a\n\tc\n", "\tc", " a", "b");
    // The UTF-8 bytes of U+00E9 are C3 A9, which are above the byte of z.
    CASE("non-ascii", "\xc3\xa9\nz\ne\n", "e", "z", "\xc3\xa9");
    // U+FF61 is EF BD A1 and U+1F600 is F0 9F 98 80.
    CASE("supplementary", "\xf0\x9f\x98\x80\n\xef\xbd\xa1\n", "\xef\xbd\xa1", "\xf0\x9f\x98\x80");
    // U+2028 is E2 80 A8.
    CASE("other-line-breaks", "b\xe2\x80\xa8" "a\nb\x1c" "a\nb\x0c" "a\n", "b\x0c" "a", "b\x1c" "a", "b\xe2\x80\xa8" "a");

    // 50000 lines "b" and 50000 lines "a", one after the other.
    size_t size = 4 * 50000;
    char *data = malloc(size);
    assert(data != NULL);
    for (size_t i = 0; i < size; i += 4) {
        memcpy(data + i, "b\na\n", 4);
    }
    write_file(data, size);
    free(data);
    struct sorted_lines got;
    assert(sort_lines(path, &got) == 0);
    assert(got.len == 100000);
    for (size_t i = 0; i < got.len; i++) {
        assert(strcmp(got.lines[i].text, i < 50000 ? "a" : "b") == 0);
    }
    sort_lines_free(&got);

    errno = 0;
    if (sort_lines("no/such/dir/missing.txt", &got) != -1 || errno != ENOENT) {
        fprintf(stderr, "case not-found: want -1 and ENOENT\n");
        return 1;
    }
    remove(path);
    puts("ok");
    return 0;
}
SortedLines.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

using System.Text;

/// <summary>Sorts the lines of a text file.</summary>
public static class SortedLines
{
    /// <summary>
    /// Returns the lines of the UTF-8 file at path, sorted by code point. A line ends at LF, and
    /// the LF is not part of it. A last line with no LF is a line too.
    /// </summary>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    public static List<string> Read(string path)
    {
        byte[] data = File.ReadAllBytes(path);
        var lines = new List<ReadOnlyMemory<byte>>();
        int start = 0;
        while (start < data.Length)
        {
            int end = Array.IndexOf(data, (byte)'\n', start);
            if (end < 0)
            {
                end = data.Length;
            }
            lines.Add(data.AsMemory(start, end - start));
            start = end + 1;
        }
        // string.CompareOrdinal compares UTF-16 chars, which is not the order of
        // the code points. SequenceCompareTo compares the UTF-8 bytes, which is.
        lines.Sort((a, b) => a.Span.SequenceCompareTo(b.Span));
        return lines.ConvertAll(line => Encoding.UTF8.GetString(line.Span));
    }
}
SortedLinesTests.cs 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

using System.Text;
using Xunit;

public sealed class SortedLinesTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("sort-lines-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private static string[] AThenB(int n) =>
        [.. Enumerable.Repeat("a", n), .. Enumerable.Repeat("b", n)];

    public static TheoryData<string, string, string[]> Cases => new()
    {
        { "simple", "pear\napple\nfig\n", ["apple", "fig", "pear"] },
        { "case", "b\nB\na\nA\n", ["A", "B", "a", "b"] },
        { "numbers", "10\n9\n100\n", ["10", "100", "9"] },
        { "empty", "", [] },
        { "one-empty-line", "\n", [""] },
        { "empty-lines", "b\n\na\n\n", ["", "", "a", "b"] },
        { "duplicates", "b\na\nb\n", ["a", "b", "b"] },
        { "no-final-newline", "b\na", ["a", "b"] },
        { "crlf", "b\r\na\r\n", ["a\r", "b\r"] },
        { "prefix", "ab\na\n", ["a", "ab"] },
        { "whitespace", "b\n a\n\tc\n", ["\tc", " a", "b"] },
        { "non-ascii", "\u00e9\nz\ne\n", ["e", "z", "\u00e9"] },
        // U+FF61 is below U+1F600, but its UTF-16 char is above 0xD83D.
        { "supplementary", "\U0001F600\n\uff61\n", ["\uff61", "\U0001F600"] },
        { "other-line-breaks", "b\u2028a\nb\u001ca\nb\fa\n", ["b\fa", "b\u001ca", "b\u2028a"] },
        { "many-lines", string.Concat(Enumerable.Repeat("b\na\n", 50000)), AThenB(50000) },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Read(string name, string text, string[] want)
    {
        string path = Path.Combine(dir, "input.txt");
        // UTF8Encoding(false) writes no byte order mark.
        File.WriteAllText(path, text, new UTF8Encoding(false));
        Assert.Equal(want, SortedLines.Read(path));
        _ = name;
    }

    [Fact]
    public void NotFound()
    {
        Assert.Throws<FileNotFoundException>(() => SortedLines.Read(Path.Combine(dir, "missing.txt")));
    }
}
sortLines.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

import { readFileSync } from "node:fs";

// Returns the lines of the UTF-8 file at path, sorted by code point. A line
// ends at LF, and the LF is not part of it. A last line with no LF is a line
// too. A missing file throws an error whose code is "ENOENT".
export function sortLines(path) {
  const data = readFileSync(path);
  const lines = [];
  let start = 0;
  while (start < data.length) {
    let end = data.indexOf(0x0a, start);
    if (end === -1) end = data.length;
    lines.push(data.subarray(start, end));
    start = end + 1;
  }
  // The default sort and < compare UTF-16 code units, which is not the order
  // of the code points. Buffer.compare compares the UTF-8 bytes, which is.
  lines.sort(Buffer.compare);
  return lines.map((line) => line.toString("utf8"));
}
sortLines.test.js 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { sortLines } from "./sortLines.js";

// name: [the text of the file, written as UTF-8, the result]
const CASES = {
  simple: ["pear\napple\nfig\n", ["apple", "fig", "pear"]],
  case: ["b\nB\na\nA\n", ["A", "B", "a", "b"]],
  numbers: ["10\n9\n100\n", ["10", "100", "9"]],
  empty: ["", []],
  "one-empty-line": ["\n", [""]],
  "empty-lines": ["b\n\na\n\n", ["", "", "a", "b"]],
  duplicates: ["b\na\nb\n", ["a", "b", "b"]],
  "no-final-newline": ["b\na", ["a", "b"]],
  crlf: ["b\r\na\r\n", ["a\r", "b\r"]],
  prefix: ["ab\na\n", ["a", "ab"]],
  whitespace: ["b\n a\n\tc\n", ["\tc", " a", "b"]],
  "non-ascii": ["\u00e9\nz\ne\n", ["e", "z", "\u00e9"]],
  // U+FF61 is below U+1F600, but its UTF-16 code unit is above 0xD83D.
  supplementary: ["\u{1f600}\n\uff61\n", ["\uff61", "\u{1f600}"]],
  "other-line-breaks": ["b\u2028a\nb\x1ca\nb\x0ca\n", ["b\x0ca", "b\x1ca", "b\u2028a"]],
  "many-lines": ["b\na\n".repeat(50000), [...Array(50000).fill("a"), ...Array(50000).fill("b")]],
};

const dir = mkdtempSync(join(tmpdir(), "sort-lines-"));
after(() => rmSync(dir, { recursive: true, force: true }));

for (const [name, [text, expect]] of Object.entries(CASES)) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(sortLines(path), expect);
  });
}

test("not-found", () => {
  assert.throws(() => sortLines(join(dir, "missing.txt")), { code: "ENOENT" });
});
sortLines.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

import { readFileSync } from "node:fs";

// Returns the lines of the UTF-8 file at path, sorted by code point. A line
// ends at LF, and the LF is not part of it. A last line with no LF is a line
// too. A missing file throws an error whose code is "ENOENT".
export function sortLines(path: string): string[] {
  const data = readFileSync(path);
  const lines: Buffer[] = [];
  let start = 0;
  while (start < data.length) {
    let end = data.indexOf(0x0a, start);
    if (end === -1) end = data.length;
    lines.push(data.subarray(start, end));
    start = end + 1;
  }
  // The default sort and < compare UTF-16 code units, which is not the order
  // of the code points. Buffer.compare compares the UTF-8 bytes, which is.
  lines.sort(Buffer.compare);
  return lines.map((line) => line.toString("utf8"));
}
sortLines.test.ts 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { sortLines } from "./sortLines.ts";

// name: [the text of the file, written as UTF-8, the result]
const CASES: Record<string, [string, string[]]> = {
  simple: ["pear\napple\nfig\n", ["apple", "fig", "pear"]],
  case: ["b\nB\na\nA\n", ["A", "B", "a", "b"]],
  numbers: ["10\n9\n100\n", ["10", "100", "9"]],
  empty: ["", []],
  "one-empty-line": ["\n", [""]],
  "empty-lines": ["b\n\na\n\n", ["", "", "a", "b"]],
  duplicates: ["b\na\nb\n", ["a", "b", "b"]],
  "no-final-newline": ["b\na", ["a", "b"]],
  crlf: ["b\r\na\r\n", ["a\r", "b\r"]],
  prefix: ["ab\na\n", ["a", "ab"]],
  whitespace: ["b\n a\n\tc\n", ["\tc", " a", "b"]],
  "non-ascii": ["\u00e9\nz\ne\n", ["e", "z", "\u00e9"]],
  // U+FF61 is below U+1F600, but its UTF-16 code unit is above 0xD83D.
  supplementary: ["\u{1f600}\n\uff61\n", ["\uff61", "\u{1f600}"]],
  "other-line-breaks": ["b\u2028a\nb\x1ca\nb\x0ca\n", ["b\x0ca", "b\x1ca", "b\u2028a"]],
  "many-lines": ["b\na\n".repeat(50000), [...Array(50000).fill("a"), ...Array(50000).fill("b")]],
};

const dir = mkdtempSync(join(tmpdir(), "sort-lines-"));
after(() => rmSync(dir, { recursive: true, force: true }));

for (const [name, [text, expect]] of Object.entries(CASES)) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(sortLines(path), expect);
  });
}

test("not-found", () => {
  assert.throws(() => sortLines(join(dir, "missing.txt")), { code: "ENOENT" });
});
sort_lines.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

// Package sortlines sorts the lines of a text file.
package sortlines

import (
	"os"
	"slices"
	"strings"
)

// SortLines returns the lines of the UTF-8 file at path, sorted by code point.
// A line ends at LF, and the LF is not part of it. A last line with no LF is a
// line too. A missing file gives an error that matches fs.ErrNotExist.
func SortLines(path string) ([]string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	lines := strings.Split(string(data), "\n")
	// After the LF at the end of the last line, Split gives one empty string.
	// An empty file gives [""] too, which is no lines.
	if lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}
	// Go compares strings byte by byte, and the order of the UTF-8 bytes is
	// the order of the code points.
	slices.Sort(lines)
	return lines, nil
}
sort_lines_test.go 75 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

package sortlines

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"testing"
)

var cases = []struct {
	name string
	data string
	want []string
}{
	{"simple", "pear\napple\nfig\n", []string{"apple", "fig", "pear"}},
	{"case", "b\nB\na\nA\n", []string{"A", "B", "a", "b"}},
	{"numbers", "10\n9\n100\n", []string{"10", "100", "9"}},
	{"empty", "", []string{}},
	{"one-empty-line", "\n", []string{""}},
	{"empty-lines", "b\n\na\n\n", []string{"", "", "a", "b"}},
	{"duplicates", "b\na\nb\n", []string{"a", "b", "b"}},
	{"no-final-newline", "b\na", []string{"a", "b"}},
	{"crlf", "b\r\na\r\n", []string{"a\r", "b\r"}},
	{"prefix", "ab\na\n", []string{"a", "ab"}},
	{"whitespace", "b\n a\n\tc\n", []string{"\tc", " a", "b"}},
	{"non-ascii", "\u00e9\nz\ne\n", []string{"e", "z", "\u00e9"}},
	// U+FF61 is below U+1F600, but its UTF-16 code unit is above 0xD83D.
	{"supplementary", "\U0001f600\n\uff61\n", []string{"\uff61", "\U0001f600"}},
	{"other-line-breaks", "b\u2028a\nb\x1ca\nb\x0ca\n", []string{"b\x0ca", "b\x1ca", "b\u2028a"}},
	{"many-lines", strings.Repeat("b\na\n", 50000), aThenB(50000)},
}

// aThenB returns n lines "a" and then n lines "b".
func aThenB(n int) []string {
	lines := make([]string, 2*n)
	for i := range lines {
		lines[i] = "a"
		if i >= n {
			lines[i] = "b"
		}
	}
	return lines
}

func TestSortLines(t *testing.T) {
	dir := t.TempDir()
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(dir, c.name+".txt")
			if err := os.WriteFile(path, []byte(c.data), 0o644); err != nil {
				t.Fatal(err)
			}
			got, err := SortLines(path)
			if err != nil {
				t.Fatal(err)
			}
			if !slices.Equal(got, c.want) {
				t.Errorf("got %q, want %q", got, c.want)
			}
		})
	}
}

func TestNotFound(t *testing.T) {
	_, err := SortLines(filepath.Join(t.TempDir(), "missing.txt"))
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("got %v, want fs.ErrNotExist", err)
	}
}
sort_lines.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

//! Sorts the lines of a text file.

use std::fs;
use std::io;
use std::path::Path;

/// Returns the lines of the UTF-8 file at `path`, sorted by code point. A line
/// ends at LF, and the LF is not part of it. A last line with no LF is a line
/// too. A missing file gives an error of the kind `ErrorKind::NotFound`, and a
/// file that is not valid UTF-8 gives `ErrorKind::InvalidData`.
pub fn sort_lines(path: impl AsRef<Path>) -> io::Result<Vec<String>> {
    let text = fs::read_to_string(path)?;
    // str::lines also removes a CR before each LF, so split at LF only.
    let mut lines: Vec<String> = text.split('\n').map(String::from).collect();
    // After the LF at the end of the last line, split gives one empty string.
    // An empty file gives [""] too, which is no lines.
    if lines.last().is_some_and(|line| line.is_empty()) {
        lines.pop();
    }
    // Strings compare by their bytes, and the order of the UTF-8 bytes is the
    // order of the code points. Equal lines are equal bytes, so an unstable
    // sort gives the same result as a stable one.
    lines.sort_unstable();
    Ok(lines)
}
tests/sort_lines_test.rs 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use algo_sort_the_lines_of_a_file::sort_lines;

/// Writes the text to a new file in the temporary directory and returns its path.
fn write(name: &str, text: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("sort-lines-{}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join(name);
    fs::write(&path, text).unwrap();
    path
}

const CASES: &[(&str, &str, &[&str])] = &[
    ("simple", "pear\napple\nfig\n", &["apple", "fig", "pear"]),
    ("case", "b\nB\na\nA\n", &["A", "B", "a", "b"]),
    ("numbers", "10\n9\n100\n", &["10", "100", "9"]),
    ("empty", "", &[]),
    ("one-empty-line", "\n", &[""]),
    ("empty-lines", "b\n\na\n\n", &["", "", "a", "b"]),
    ("duplicates", "b\na\nb\n", &["a", "b", "b"]),
    ("no-final-newline", "b\na", &["a", "b"]),
    ("crlf", "b\r\na\r\n", &["a\r", "b\r"]),
    ("prefix", "ab\na\n", &["a", "ab"]),
    ("whitespace", "b\n a\n\tc\n", &["\tc", " a", "b"]),
    ("non-ascii", "\u{e9}\nz\ne\n", &["e", "z", "\u{e9}"]),
    // U+FF61 is below U+1F600, but its UTF-16 code unit is above 0xD83D.
    ("supplementary", "\u{1f600}\n\u{ff61}\n", &["\u{ff61}", "\u{1f600}"]),
    ("other-line-breaks", "b\u{2028}a\nb\x1ca\nb\x0ca\n", &["b\x0ca", "b\x1ca", "b\u{2028}a"]),
];

#[test]
fn cases() {
    for &(name, text, want) in CASES {
        let path = write(&format!("{name}.txt"), text);
        assert_eq!(sort_lines(&path).unwrap(), want, "{name}");
    }
}

#[test]
fn many_lines() {
    let path = write("many-lines.txt", &"b\na\n".repeat(50000));
    let mut want = vec!["a"; 50000];
    want.extend(vec!["b"; 50000]);
    assert_eq!(sort_lines(&path).unwrap(), want);
}

#[test]
fn not_found() {
    let err = sort_lines("no/such/dir/missing.txt").unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}
sort_lines.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

# sort_lines PATH
# Prints the lines of the file at PATH, sorted by their bytes, each with an LF
# at the end. For UTF-8 text, the order of the bytes is the order of the code
# points. Returns a nonzero status, and prints nothing on stdout, if the file
# cannot be read.
sort_lines() {
  [[ -r $1 && ! -d $1 ]] || { printf 'sort_lines: cannot read %s\n' "$1" >&2; return 1; }
  # In the POSIX locale, sort compares the bytes. In another locale, it uses
  # the collation of that locale, so the order changes from machine to
  # machine. sort adds an LF to a last line that has none.
  LC_ALL=C sort -- "$1"
}
test_sort_lines.bats 44 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-the-lines-of-a-file/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/sort_lines.sh"
  file="$BATS_TEST_TMPDIR/input.txt"
}

check() { # check BYTES WANT
  printf '%b' "$1" >"$file"
  # The x keeps the final LFs, which $(...) removes.
  got=$(sort_lines "$file" && printf x)
  [ "$got" = "$(printf '%bx' "$2")" ]
}

@test "simple" { check 'pear\napple\nfig\n' 'apple\nfig\npear\n'; }
@test "case" { check 'b\nB\na\nA\n' 'A\nB\na\nb\n'; }
@test "numbers" { check '10\n9\n100\n' '10\n100\n9\n'; }
@test "empty" { check '' ''; }
@test "one-empty-line" { check '\n' '\n'; }
@test "empty-lines" { check 'b\n\na\n\n' '\n\na\nb\n'; }
@test "duplicates" { check 'b\na\nb\n' 'a\nb\nb\n'; }
@test "no-final-newline" { check 'b\na' 'a\nb\n'; }
@test "crlf" { check 'b\r\na\r\n' 'a\r\nb\r\n'; }
@test "prefix" { check 'ab\na\n' 'a\nab\n'; }
@test "whitespace" { check 'b\n a\n\tc\n' '\tc\n a\nb\n'; }
@test "non-ascii" { check '\xc3\xa9\nz\ne\n' 'e\nz\n\xc3\xa9\n'; }
@test "supplementary" { check '\xf0\x9f\x98\x80\n\xef\xbd\xa1\n' '\xef\xbd\xa1\n\xf0\x9f\x98\x80\n'; }
@test "other-line-breaks" { check 'b\xe2\x80\xa8a\nb\x1ca\nb\x0ca\n' 'b\x0ca\nb\x1ca\nb\xe2\x80\xa8a\n'; }

@test "many-lines" {
  yes 'b
a' | head -n 100000 >"$file"
  [ "$(sort_lines "$file" | uniq -c | awk '{ print $2, $1 }')" = "$(printf 'a 50000\nb 50000')" ]
}

@test "not-found" {
  run sort_lines "$BATS_TEST_TMPDIR/missing.txt"
  [ "$status" -ne 0 ]
  [ "$output" = "sort_lines: cannot read $BATS_TEST_TMPDIR/missing.txt" ]
}

References

  1. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), sort, DESCRIPTION; OPTIONS (-n); INPUT FILES
  2. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 3, Definitions, 3.172 Incomplete Line; 3.185 Line
  3. RFC 3629, UTF-8, a transformation format of ISO 10646, 1. Introduction
  4. The Python Standard Library, Built-in Functions, open (newline)
  5. The Python Language Reference, Expressions, Value comparisons
  6. Node.js documentation, Buffer, Buffer.compare(buf1, buf2)
  7. Java SE 25 API, java.util.Arrays, compareUnsigned(byte[], byte[])
  8. .NET API reference, MemoryExtensions.SequenceCompareTo
  9. The Go Programming Language Specification, Comparison operators
  10. The Rust Standard Library, str, lines; impl Ord for str
  11. cppreference.com, memcmp
  12. cppreference.com, std::char_traits::eq, lt
  13. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 7, Locale, 7.3.2.6 LC_COLLATE Category in the POSIX Locale
  14. MDN Web Docs, Array.prototype.sort(), Description
  15. Java SE 25 API, java.lang.String, compareTo
  16. .NET API reference, String.CompareOrdinal
  17. The Python Standard Library, Built-in Types, str.splitlines

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source