Programming Search⌘K

Taskintro

Compute a word count

Also called word count, wc, count the words of a file, count lines words and bytes.

Count the lines, words and bytes of a UTF-8 file as wc does, with a word as a run of code points that do not have the Unicode property White_Space.

Task

Count the lines, the words and the bytes of a UTF-8 file, as wc does. Each solution returns three numbers:

  • lines: the number of LF bytes (\n, 0x0A) in the file, the number that wc -l prints. A last line with no LF is not counted.
  • words: the number of words. POSIX says: "The wc utility shall consider a word to be a non-zero-length string of characters delimited by white space."1 Here a word is a run of one or more code points that do not have the Unicode property White_Space.
  • bytes: the size of the file in bytes, the number that wc -c prints.

POSIX does not give one set of white space characters. For wc, the locale category LC_CTYPE decides "which characters are defined as white-space characters."1 For the POSIX locale, the set is "exactly , , , , , and ".2 Other locales add other characters, so one file can give different word counts. This task uses a fixed set, the 25 code points of White_Space in the Unicode Character Database3:

Code points Characters
U+0009 to U+000D tab, LF, VT, FF, CR
U+0020, U+0085, U+00A0 space, NEXT LINE (NEL), NO-BREAK SPACE
U+1680, U+2000 to U+200A OGHAM SPACE MARK and 11 spaces of fixed widths
U+2028, U+2029 LINE SEPARATOR, PARAGRAPH SEPARATOR
U+202F, U+205F, U+3000 NARROW NO-BREAK SPACE, MEDIUM MATHEMATICAL SPACE, IDEOGRAPHIC SPACE

ZERO WIDTH SPACE (U+200B), SOFT HYPHEN (U+00AD), U+FEFF and the control characters U+001C to U+001F are not White_Space, so they are part of a word.

The file is UTF-8 with no byte order mark. If its bytes are not valid UTF-8, or the file does not exist, the solution reports an error and returns no result. An empty file gives (0, 0, 0). The file can be larger than the memory.

Solutions

Each solution decodes the bytes as strict UTF-8 and keeps one flag: is the last code point part of a word?

  1. Set lines, words and bytes to 0, and in_word to false.
  2. Read a chunk of bytes, add its length to bytes, and decode it.
  3. For each code point: if it is White_Space, set in_word to false, and add 1 to lines if it is LF. Else, if in_word is false, add 1 to words and set in_word to true.
  4. At the end of the file, check that no part of a UTF-8 sequence is left, and return the three numbers.

A chunk can end in the middle of a UTF-8 sequence. So a solution decodes with an incremental decoder that keeps the start of the sequence for the next chunk, or it cuts the file at LF bytes. An LF byte is never part of a longer UTF-8 sequence, so each line decodes on its own.

  • Python. codecs.getincrementaldecoder('utf-8') with errors='strict', on chunks of 64 KiB that open(path, 'rb') gives. The last call is decode(b'', final=True). "If final is true the decoder must decode the input completely and must flush all buffers."4 A sequence that the end of the file cuts raises UnicodeDecodeError. A set of the 25 code points tests for White_Space.
  • JavaScript and TypeScript (Node.js). A for await loop over fs.createReadStream(path), and a TextDecoder with fatal: true and ignoreBOM: true. With fatal, the decoder throws "a TypeError when decoding invalid data", and else it "will substitute malformed data with a replacement character."5 Each chunk goes to decode(chunk, { stream: true }), because stream must be true "if processing the data in chunks".6 The last call, decode(), throws if a sequence is cut. ignoreBOM: true keeps a U+FEFF at the start as a character. A Set of the 25 code points tests for White_Space. The TypeScript file adds types only.
  • Java. An InputStreamReader with a CharsetDecoder for UTF-8 whose malformed action is CodingErrorAction.REPORT. The constructor "Creates an InputStreamReader that uses the given charset decoder."7 A malformed result is reported only "if the malformed action of this decoder is CodingErrorAction.REPORT"; "otherwise the malformed input will be ignored or replaced".8 Bad bytes throw MalformedInputException. A FilterInputStream under the reader counts the bytes. The test for White_Space is a method of its own, not Character.isWhitespace (see Pitfalls).
  • C#. A StreamReader with new UTF8Encoding(false, true) and detectEncodingFromByteOrderMarks: false. The second argument is throwOnInvalidBytes, and Microsoft recommends to "enable error detection by calling a constructor with a throwOnInvalidBytes parameter and setting its value to true".9 Bad bytes throw DecoderFallbackException. After the last read, stream.Position is the number of bytes. Each White_Space code point is one UTF-16 unit, so the test runs on each char.
  • Go. bufio.Reader.ReadRune with a buffer of 64 KiB. "If the encoded rune is invalid, it consumes one byte and returns unicode.ReplacementChar (U+FFFD) with a size of 1."10 A real U+FFFD in the file has a size of 3, so the code reports ErrInvalidUTF8 only for the size 1. unicode.IsSpace "reports whether the rune is a space character as defined by Unicode's White Space property".11
  • Rust. BufRead::read_until(b'\n', &mut line) gives one line with its LF: it reads "until the delimiter or EOF is found".12 Then std::str::from_utf8 checks the line. It "Returns Err if the slice is not UTF-8".13 The code maps that error to ErrorKind::InvalidData. char::is_whitespace "Returns true if this char has the White_Space property."14 A line is in memory as a whole, so a file of one very long line needs that much memory.
  • C. POSIX getline reads one line with its LF. A function of about 30 lines decodes the UTF-8 by RFC 3629 and refuses overlong forms, surrogates and code points above U+10FFFF.15 On bad bytes, word_count returns -1 and sets errno to EILSEQ. A function of its own tests for White_Space, because iswspace depends on the locale (see Pitfalls).
  • C++. std::getline on a binary std::ifstream, the same decoder as in C, and std::expected (C++23) for the result. The errors are cannot_open, invalid_utf8 and read_failed.
  • Bash. iconv -f UTF-8 -t UTF-8 checks the bytes and stops with a nonzero status on bad bytes. wc -l and wc -c give the lines and the bytes. For the words, sed in the C locale changes the UTF-8 bytes of each White_Space code point above U+007F to a space. Then wc -w counts in the C locale, where the white space is the six characters of the POSIX locale.2 After iconv has checked the file, a match of those bytes cannot start inside another character.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/. The result is (lines, words, bytes).

  • simple, multiple-spaces and tabs-and-lines: a run of white space, at the start, in the middle or at the end, does not make an empty word.
  • empty: (0, 0, 0). only-white-space: lines but no words, (2, 0, 4).
  • no-final-newline: one two gives (0, 2, 7). The last line is not counted, as in wc -l.
  • crlf: CR is White_Space, so CRLF does not change the words, and each CRLF holds one LF.
  • non-ascii: naïve café has 10 characters and 12 bytes before the LF. The bytes count is 13, not 11.
  • unicode-spaces and nel: NO-BREAK SPACE, IDEOGRAPHIC SPACE, LINE SEPARATOR and NEL separate words. LINE SEPARATOR and NEL do not add to lines.
  • not-white-space: ZERO WIDTH SPACE, SOFT HYPHEN and U+FEFF do not separate words, so a, b, c and d with them between are one word.
  • control-separators: U+001C and U+001F are not White_Space, so (1, 1, 6).

The tests also write a file of 100000 lines a b, which is larger than one chunk, and a file in which the first 64 KiB end inside the 3 bytes of U+3000. The cases in cases/errors.jsonl must give the error invalid-utf8: the bytes FF FE, a sequence that the end of the file cuts (E2 82) and an encoded surrogate (ED A0 80). RFC 3629 says that UTF-8 prohibits "encoding character numbers between U+D800 and U+DFFF".15 A missing file must give not-found. The toolchain does not load that file yet, so each test file holds these cases by name.

Pitfalls

  • Each language has its own white space. The function or pattern that a language calls white space is often not White_Space. Python str.split() with no argument splits at runs of whitespace.16 For Python, a character is whitespace if its general category is Zs, or if its bidirectional class is WS, B or S.16 The bidirectional class of U+001C to U+001E is B, and of U+001F it is S, so split cuts a word there:
# Six code points between 'a' and 'b'. Only the first three have the
# Unicode property White_Space.
samples = ['\u00a0', '\u0085', '\u2028', '\u001c', '\u200b', '\ufeff']
print('code point: parts')
for sep in samples:
    text = 'a' + sep + 'b'
    print(f'U+{ord(sep):04X}: {len(text.split())}')
Output
code point: parts
U+00A0: 2
U+0085: 2
U+2028: 2
U+001C: 2
U+200B: 1
U+FEFF: 1

In JavaScript, \s "Matches any whitespace or line terminator character."17 That set has U+FEFF, and for U+0085, MDN says: "U+0085 NEXT LINE has no special role".18 So \s does not cut at NEL, but it cuts at U+FEFF:

// Six code points between 'a' and 'b'. Only the first three have the
// Unicode property White_Space.
const samples = ['\u00a0', '\u0085', '\u2028', '\u001c', '\u200b', '\ufeff'];
console.log('code point: parts');
for (const sep of samples) {
  const text = 'a' + sep + 'b';
  const hex = sep.codePointAt(0).toString(16).toUpperCase().padStart(4, '0');
  console.log(`U+${hex}: ${text.split(/\s+/).length}`);
}
Output
code point: parts
U+00A0: 2
U+0085: 1
U+2028: 2
U+001C: 1
U+200B: 1
U+FEFF: 2

Java Character.isWhitespace is true if the character "is a Unicode space character ( SPACE_SEPARATOR , LINE_SEPARATOR , or PARAGRAPH_SEPARATOR ) but is not also a non-breaking space", and for U+0009 to U+000D and U+001C to U+001F.19 The non-breaking spaces are U+00A0, U+2007 and U+202F. So isWhitespace is false for NO-BREAK SPACE and NEL, and true for U+001C:

public class Main {
    public static void main(String[] args) {
        // Six code points. Only the first three have the Unicode property White_Space.
        int[] samples = {0x00a0, 0x0085, 0x2028, 0x001c, 0x200b, 0xfeff};
        for (int cp : samples) {
            System.out.printf("U+%04X: isWhitespace %b%n", cp, Character.isWhitespace(cp));
        }
    }
}
Output
U+00A0: isWhitespace false
U+0085: isWhitespace false
U+2028: isWhitespace true
U+001C: isWhitespace true
U+200B: isWhitespace false
U+FEFF: isWhitespace false

.NET Char.IsWhiteSpace lists the Space_Separator category, U+2028, U+2029, U+0009 to U+000D and "NEXT LINE (U+0085)".20 That is the White_Space set. Go unicode.IsSpace11 and Rust char::is_whitespace14 also use White_Space. Pick one definition, say which one in the code, and test it with the cases above.

  • wc -w depends on the locale. The locale decides which characters are white space,1 and C iswspace adds "any whitespace character specific to the current locale".21 Two systems, or two locales on one system, can give two word counts for one file. Set the locale, or count with a fixed set, as the Bash solution does.
  • Replacement of bad bytes. A decoder that is not strict puts U+FFFD in place of bad bytes, and U+FFFD is not White_Space. So a word count over a file in Latin-1 gives a result and no error. Use a strict decoder: errors='strict', fatal: true, CodingErrorAction.REPORT or throwOnInvalidBytes: true.
  • A chunk that cuts a character. A sequence of 2 to 4 bytes can start at the end of one chunk and end in the next. If each chunk is decoded on its own, a strict decoder reports an error for valid text, and a decoder that is not strict puts U+FFFD in place of the character. Keep the state of the decoder across chunks, or cut the file at LF bytes.
  • Counting split parts. text.split(' ') gives an empty string for each extra space and for a space at the start or the end. Count runs of characters that are not white space, not the parts of a split at one character.
  • Characters are not bytes. The bytes number is the size of the file. The length of the decoded string is a number of code points in Python and of UTF-16 units in JavaScript, Java and C#, and both are different from the number of bytes for text that is not ASCII.

Code

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

word_count.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-word-count/.

"""Counts the lines, words and bytes of a UTF-8 file, as wc does."""

import codecs
from os import PathLike

CHUNK = 64 * 1024

# The 25 code points that have the Unicode property White_Space (PropList.txt).
WHITE_SPACE = frozenset(
    map(chr, [*range(0x09, 0x0E), 0x20, 0x85, 0xA0, 0x1680, *range(0x2000, 0x200B), 0x2028, 0x2029, 0x202F, 0x205F, 0x3000])
)


def word_count(path: str | PathLike[str]) -> tuple[int, int, int]:
    """Returns (lines, words, bytes) for the UTF-8 file at path.

    lines is the number of LF bytes. A word is a run of one or more code points
    that are not White_Space. Raises UnicodeDecodeError if the bytes are not
    valid UTF-8, and OSError, for example FileNotFoundError, if the file cannot
    be read.
    """
    decoder = codecs.getincrementaldecoder("utf-8")(errors="strict")
    lines = words = size = 0
    in_word = False

    def count(text: str) -> None:
        nonlocal lines, words, in_word
        for ch in text:
            if ch in WHITE_SPACE:
                in_word = False
                lines += ch == "\n"
            elif not in_word:
                in_word = True
                words += 1

    with open(path, "rb") as f:
        while chunk := f.read(CHUNK):
            size += len(chunk)
            # The decoder keeps a sequence that the chunk cuts until the next chunk.
            count(decoder.decode(chunk))
    count(decoder.decode(b"", final=True))  # raises if the file ends inside a sequence
    return lines, words, size
test_word_count.py 56 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-word-count/.

from pathlib import Path

import pytest

from word_count import CHUNK, word_count

# name: (the text of the file, (lines, words, bytes))
CASES = {
    "simple": ("one two three\n", (1, 3, 14)),
    "multiple-spaces": ("  a   b  \n", (1, 2, 10)),
    "tabs-and-lines": ("a\tb\nc\n", (2, 3, 6)),
    "empty": ("", (0, 0, 0)),
    "only-white-space": (" \n\t\n", (2, 0, 4)),
    "no-final-newline": ("one two", (0, 2, 7)),
    "crlf": ("a b\r\nc\r\n", (2, 3, 8)),
    "non-ascii": ("na\u00efve caf\u00e9\n", (1, 2, 13)),
    "unicode-spaces": ("a\u00a0b\u3000c\u2028d\n", (1, 4, 13)),
    "not-white-space": ("a\u200bb\u00adc\ufeffd\n", (1, 1, 13)),
    "control-separators": ("a\x1cb\x1fc\n", (1, 1, 6)),
    "nel": ("a\u0085b\n", (1, 2, 5)),
    # 100000 lines: more than one chunk of 64 KiB.
    "many-lines": ("a b\n" * 100000, (100000, 200000, 400000)),
    # The chunk ends inside the 3 bytes of U+3000.
    "chunk-boundary": ("x" * (CHUNK - 1) + "\u3000y\n", (1, 2, CHUNK + 4)),
}

# name: the bytes of a file that is not valid UTF-8
INVALID = {
    "invalid-bytes": b"ok\xff\xfe\n",
    "truncated": b"ok \xe2\x82",
    "surrogate": b"a\xed\xa0\x80b\n",
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    text, want = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(text.encode("utf-8"))
    assert word_count(path) == want


@pytest.mark.parametrize("name", INVALID)
def test_invalid_utf8(tmp_path: Path, name: str) -> None:
    path = tmp_path / "input.txt"
    path.write_bytes(INVALID[name])
    with pytest.raises(UnicodeDecodeError):
        word_count(path)


def test_missing_file(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        word_count(tmp_path / "missing.txt")
word_count.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

#include "word_count.hpp"

#include <fstream>
#include <string>
#include <string_view>

namespace {

// The 25 code points that have the Unicode property White_Space.
bool is_white_space(char32_t c) {
    return (c >= 0x09 && c <= 0x0d) || c == 0x20 || c == 0x85 || c == 0xa0 || c == 0x1680 ||
           (c >= 0x2000 && c <= 0x200a) || c == 0x2028 || c == 0x2029 || c == 0x202f ||
           c == 0x205f || c == 0x3000;
}

// Decodes one UTF-8 sequence at the start of s. It returns the length of the
// sequence and stores the code point in cp, or returns 0 if the bytes are not
// valid UTF-8 (RFC 3629: no overlong forms, no surrogates, nothing above U+10FFFF).
std::size_t decode(std::string_view s, char32_t& cp) {
    const auto b = [&](std::size_t i) { return static_cast<unsigned char>(s[i]); };
    if (b(0) < 0x80) {
        cp = b(0);
        return 1;
    }
    std::size_t len;
    char32_t min;
    if (b(0) >= 0xc2 && b(0) <= 0xdf) {
        len = 2, min = 0x80, cp = b(0) & 0x1fu;
    } else if (b(0) >= 0xe0 && b(0) <= 0xef) {
        len = 3, min = 0x800, cp = b(0) & 0x0fu;
    } else if (b(0) >= 0xf0 && b(0) <= 0xf4) {
        len = 4, min = 0x10000, cp = b(0) & 0x07u;
    } else {
        return 0;
    }
    if (s.size() < len) {
        return 0;
    }
    for (std::size_t i = 1; i < len; ++i) {
        if ((b(i) & 0xc0u) != 0x80) {
            return 0;
        }
        cp = (cp << 6) | (b(i) & 0x3fu);
    }
    if (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) {
        return 0;
    }
    return len;
}

}  // namespace

std::expected<WordCount, CountError> word_count(const std::filesystem::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        return std::unexpected(CountError::cannot_open);
    }
    WordCount result;
    std::string line;
    // getline removes the LF. An LF byte is never part of a longer UTF-8
    // sequence, so each line decodes on its own.
    while (std::getline(in, line)) {
        const bool had_lf = !in.eof();
        result.bytes += line.size() + (had_lf ? 1 : 0);
        result.lines += had_lf ? 1 : 0;
        // The LF that ends the line is white space, so a word never goes on to the next line.
        bool in_word = false;
        for (std::string_view s = line; !s.empty();) {
            char32_t cp;
            const std::size_t len = decode(s, cp);
            if (len == 0) {
                return std::unexpected(CountError::invalid_utf8);
            }
            if (is_white_space(cp)) {
                in_word = false;
            } else if (!in_word) {
                in_word = true;
                ++result.words;
            }
            s.remove_prefix(len);
        }
    }
    if (in.bad()) {
        return std::unexpected(CountError::read_failed);
    }
    return result;
}
word_count.hpp 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.
// since: C++23 (std::expected)

#pragma once

#include <cstdint>
#include <expected>
#include <filesystem>

struct WordCount {
    std::uintmax_t lines = 0;  // the number of LF bytes
    std::uintmax_t words = 0;  // runs of one or more code points that are not White_Space
    std::uintmax_t bytes = 0;
    bool operator==(const WordCount&) const = default;
};

enum class CountError { cannot_open, invalid_utf8, read_failed };

// Counts the lines, words and bytes of the UTF-8 file at path.
std::expected<WordCount, CountError> word_count(const std::filesystem::path& path);
test_word_count.cpp 90 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

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

#include "word_count.hpp"

namespace {

const std::filesystem::path input = "word_count_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;
    WordCount want;
};

struct invalid_case {
    const char* name;
    std::string data;
};

}  // namespace

int main() {
    std::string many;
    for (int i = 0; i < 100000; ++i) {
        many += "a b\n";  // 100000 lines: more than one buffer of 64 KiB
    }
    // A long line, and U+3000 at the end of the first 64 KiB.
    const std::string boundary = std::string(64 * 1024 - 1, 'x') + "\xe3\x80\x80y\n";

    // A hex escape takes all the hex digits after it, so a literal ends after
    // each escape that a letter from a to f follows.
    const std::vector<test_case> cases = {
        {"simple", "one two three\n", {1, 3, 14}},
        {"multiple-spaces", "  a   b  \n", {1, 2, 10}},
        {"tabs-and-lines", "a\tb\nc\n", {2, 3, 6}},
        {"empty", "", {0, 0, 0}},
        {"only-white-space", " \n\t\n", {2, 0, 4}},
        {"no-final-newline", "one two", {0, 2, 7}},
        {"crlf", "a b\r\nc\r\n", {2, 3, 8}},
        {"non-ascii", "na\xc3\xaf" "ve caf\xc3\xa9\n", {1, 2, 13}},
        {"unicode-spaces", "a\xc2\xa0" "b\xe3\x80\x80" "c\xe2\x80\xa8" "d\n", {1, 4, 13}},
        {"not-white-space", "a\xe2\x80\x8b" "b\xc2\xad" "c\xef\xbb\xbf" "d\n", {1, 1, 13}},
        {"control-separators", "a\x1c" "b\x1f" "c\n", {1, 1, 6}},
        {"nel", "a\xc2\x85" "b\n", {1, 2, 5}},
        {"many-lines", many, {100000, 200000, 400000}},
        {"chunk-boundary", boundary, {1, 2, 64 * 1024 + 4}},
    };
    for (const auto& c : cases) {
        write(c.data);
        const auto got = word_count(input);
        if (!got || *got != c.want) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            return 1;
        }
    }

    const std::vector<invalid_case> invalid = {
        {"invalid-bytes", "ok\xff\xfe\n"},
        {"truncated", "ok \xe2\x82"},
        {"surrogate", "a\xed\xa0\x80" "b\n"},
    };
    for (const auto& c : invalid) {
        write(c.data);
        const auto got = word_count(input);
        if (got || got.error() != CountError::invalid_utf8) {
            std::fprintf(stderr, "case %s: no invalid_utf8 error\n", c.name);
            return 1;
        }
    }
    std::filesystem::remove(input);

    const auto missing = word_count("word_count_missing.txt");
    if (missing || missing.error() != CountError::cannot_open) {
        std::fprintf(stderr, "case missing: no cannot_open error\n");
        return 1;
    }
    std::puts("ok");
    return 0;
}
WordCount.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * The lines, words and bytes of a UTF-8 file, as wc counts them. {@code lines} is the number of LF
 * bytes, and a word is a run of one or more code points that are not White_Space.
 */
public record WordCount(long lines, long words, long bytes) {

  /** True for the 25 code points that have the Unicode property White_Space. */
  static boolean isWhiteSpace(int c) {
    return (c >= 0x09 && c <= 0x0d) || c == 0x20 || c == 0x85 || c == 0xa0 || c == 0x1680
        || (c >= 0x2000 && c <= 0x200a) || c == 0x2028 || c == 0x2029 || c == 0x202f
        || c == 0x205f || c == 0x3000;
  }

  /**
   * Counts the lines, words and bytes of the UTF-8 file at path.
   *
   * @throws java.nio.charset.MalformedInputException if the bytes are not valid UTF-8
   * @throws java.nio.file.NoSuchFileException if the file does not exist
   */
  public static WordCount of(Path path) throws IOException {
    long lines = 0, words = 0;
    boolean inWord = false;
    // REPORT makes the decoder throw on bad bytes. The default of InputStreamReader replaces them.
    var decoder =
        StandardCharsets.UTF_8
            .newDecoder()
            .onMalformedInput(CodingErrorAction.REPORT)
            .onUnmappableCharacter(CodingErrorAction.REPORT);
    char[] buf = new char[32 * 1024];
    try (CountingStream in = new CountingStream(Files.newInputStream(path));
        Reader reader = new InputStreamReader(in, decoder)) {
      int n;
      while ((n = reader.read(buf)) != -1) {
        for (int i = 0; i < n; i++) {
          // Each White_Space code point is one char. A surrogate is never white space.
          if (isWhiteSpace(buf[i])) {
            inWord = false;
            if (buf[i] == '\n') {
              lines++;
            }
          } else if (!inWord) {
            inWord = true;
            words++;
          }
        }
      }
      return new WordCount(lines, words, in.count);
    }
  }

  /** Counts the bytes that pass through it. */
  private static final class CountingStream extends FilterInputStream {
    long count;

    CountingStream(InputStream in) {
      super(in);
    }

    @Override
    public int read() throws IOException {
      int b = super.read();
      if (b != -1) {
        count++;
      }
      return b;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
      int n = super.read(b, off, len);
      if (n > 0) {
        count += n;
      }
      return n;
    }
  }
}
WordCountTest.java 70 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

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

import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
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 WordCountTest {
  @TempDir Path dir;

  private static final int CHUNK = 64 * 1024;

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("simple", "one two three\n", new WordCount(1, 3, 14)),
        Arguments.of("multiple-spaces", "  a   b  \n", new WordCount(1, 2, 10)),
        Arguments.of("tabs-and-lines", "a\tb\nc\n", new WordCount(2, 3, 6)),
        Arguments.of("empty", "", new WordCount(0, 0, 0)),
        Arguments.of("only-white-space", " \n\t\n", new WordCount(2, 0, 4)),
        Arguments.of("no-final-newline", "one two", new WordCount(0, 2, 7)),
        Arguments.of("crlf", "a b\r\nc\r\n", new WordCount(2, 3, 8)),
        Arguments.of("non-ascii", "na\u00efve caf\u00e9\n", new WordCount(1, 2, 13)),
        Arguments.of("unicode-spaces", "a\u00a0b\u3000c\u2028d\n", new WordCount(1, 4, 13)),
        Arguments.of("not-white-space", "a\u200bb\u00adc\ufeffd\n", new WordCount(1, 1, 13)),
        Arguments.of("control-separators", "a\u001cb\u001fc\n", new WordCount(1, 1, 6)),
        Arguments.of("nel", "a\u0085b\n", new WordCount(1, 2, 5)),
        // 100000 lines: more than one buffer of 64 KiB.
        Arguments.of("many-lines", "a b\n".repeat(100000), new WordCount(100000, 200000, 400000)),
        // A long line, and U+3000 at the end of the first 64 KiB.
        Arguments.of("chunk-boundary", "x".repeat(CHUNK - 1) + "\u3000y\n", new WordCount(1, 2, CHUNK + 4)));
  }

  static Stream<Arguments> invalid() {
    return Stream.of(
        Arguments.of("invalid-bytes", new byte[] {'o', 'k', (byte) 0xff, (byte) 0xfe, '\n'}),
        Arguments.of("truncated", new byte[] {'o', 'k', ' ', (byte) 0xe2, (byte) 0x82}),
        Arguments.of("surrogate", new byte[] {'a', (byte) 0xed, (byte) 0xa0, (byte) 0x80, 'b', '\n'}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void counts(String name, String text, WordCount want) throws IOException {
    Path path = Files.write(dir.resolve("input.txt"), text.getBytes(StandardCharsets.UTF_8));
    assertEquals(want, WordCount.of(path));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("invalid")
  void invalidUtf8(String name, byte[] data) throws IOException {
    Path path = Files.write(dir.resolve("input.txt"), data);
    assertThrows(CharacterCodingException.class, () -> WordCount.of(path));
  }

  @Test
  void missingFile() {
    assertThrows(NoSuchFileException.class, () -> WordCount.of(dir.resolve("missing.txt")));
  }
}
word_count.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

#define _POSIX_C_SOURCE 200809L  // for getline

#include "word_count.h"

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// The 25 code points that have the Unicode property White_Space.
static bool is_white_space(uint32_t c) {
    return (c >= 0x09 && c <= 0x0d) || c == 0x20 || c == 0x85 || c == 0xa0 || c == 0x1680 ||
           (c >= 0x2000 && c <= 0x200a) || c == 0x2028 || c == 0x2029 || c == 0x202f ||
           c == 0x205f || c == 0x3000;
}

// Decodes one UTF-8 sequence at s, with n > 0 bytes left. It returns the
// length of the sequence and stores the code point in *cp, or returns 0 if
// the bytes are not valid UTF-8 (RFC 3629: no overlong forms, no surrogates,
// nothing above U+10FFFF).
static size_t decode(const unsigned char *s, size_t n, uint32_t *cp) {
    if (s[0] < 0x80) {
        *cp = s[0];
        return 1;
    }
    size_t len;
    uint32_t min;
    if (s[0] >= 0xc2 && s[0] <= 0xdf) {
        len = 2, min = 0x80, *cp = s[0] & 0x1fu;
    } else if (s[0] >= 0xe0 && s[0] <= 0xef) {
        len = 3, min = 0x800, *cp = s[0] & 0x0fu;
    } else if (s[0] >= 0xf0 && s[0] <= 0xf4) {
        len = 4, min = 0x10000, *cp = s[0] & 0x07u;
    } else {
        return 0;
    }
    if (n < len) {
        return 0;
    }
    for (size_t i = 1; i < len; i++) {
        if ((s[i] & 0xc0u) != 0x80) {
            return 0;
        }
        *cp = (*cp << 6) | (s[i] & 0x3fu);
    }
    if (*cp < min || *cp > 0x10ffff || (*cp >= 0xd800 && *cp <= 0xdfff)) {
        return 0;
    }
    return len;
}

int word_count(const char *path, struct word_count *out) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    struct word_count c = {0, 0, 0};
    char *line = NULL;
    size_t cap = 0;
    ssize_t n;
    // getline reads up to and with the next LF. An LF byte is never part of a
    // longer UTF-8 sequence, so each line decodes on its own.
    while ((n = getline(&line, &cap, f)) != -1) {
        const unsigned char *s = (const unsigned char *)line;
        size_t left = (size_t)n;
        bool in_word = false;
        c.bytes += left;
        while (left > 0) {
            uint32_t cp;
            size_t len = decode(s, left, &cp);
            if (len == 0) {
                free(line);
                fclose(f);
                errno = EILSEQ;
                return -1;
            }
            if (is_white_space(cp)) {
                in_word = false;
                c.lines += cp == '\n';
            } else if (!in_word) {
                in_word = true;
                c.words++;
            }
            s += len;
            left -= len;
        }
    }
    // getline returns -1 both at the end of the file and on an error.
    int err = ferror(f) ? errno : 0;
    free(line);
    fclose(f);
    if (err != 0) {
        errno = err;
        return -1;
    }
    *out = c;
    return 0;
}
word_count.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

#ifndef WORD_COUNT_H
#define WORD_COUNT_H

#include <stdint.h>

struct word_count {
    uintmax_t lines;  // the number of LF bytes
    uintmax_t words;  // runs of one or more code points that are not White_Space
    uintmax_t bytes;
};

// word_count reads the UTF-8 file at path and stores the counts in *out. It
// returns 0. On an error it returns -1 and sets errno: EILSEQ for bytes that
// are not valid UTF-8, or the error of fopen or getline.
int word_count(const char *path, struct word_count *out);

#endif
test_word_count.c 92 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

#include "word_count.h"

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

static const char *path = "word_count_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 n, uintmax_t lines, uintmax_t words, uintmax_t bytes) {
    write_file(data, n);
    struct word_count c = {99, 99, 99};
    if (word_count(path, &c) != 0 || c.lines != lines || c.words != words || c.bytes != bytes) {
        fprintf(stderr, "case %s: got %ju %ju %ju\n", name, c.lines, c.words, c.bytes);
        exit(1);
    }
}

static void check_invalid(const char *name, const char *data, size_t n) {
    write_file(data, n);
    struct word_count c;
    errno = 0;
    if (word_count(path, &c) != -1 || errno != EILSEQ) {
        fprintf(stderr, "case %s: no EILSEQ error\n", name);
        exit(1);
    }
}

// sizeof counts the bytes of the literal, but not the final NUL. A hex escape
// takes all the hex digits after it, so a literal ends after each escape that
// a letter from a to f follows.
#define CASE(name, data, lines, words, bytes) check(name, data, sizeof(data) - 1, lines, words, bytes)
#define INVALID(name, data) check_invalid(name, data, sizeof(data) - 1)

int main(void) {
    CASE("simple", "one two three\n", 1, 3, 14);
    CASE("multiple-spaces", "  a   b  \n", 1, 2, 10);
    CASE("tabs-and-lines", "a\tb\nc\n", 2, 3, 6);
    CASE("empty", "", 0, 0, 0);
    CASE("only-white-space", " \n\t\n", 2, 0, 4);
    CASE("no-final-newline", "one two", 0, 2, 7);
    CASE("crlf", "a b\r\nc\r\n", 2, 3, 8);
    CASE("non-ascii", "na\xc3\xaf" "ve caf\xc3\xa9\n", 1, 2, 13);
    CASE("unicode-spaces", "a\xc2\xa0" "b\xe3\x80\x80" "c\xe2\x80\xa8" "d\n", 1, 4, 13);
    CASE("not-white-space", "a\xe2\x80\x8b" "b\xc2\xad" "c\xef\xbb\xbf" "d\n", 1, 1, 13);
    CASE("control-separators", "a\x1c" "b\x1f" "c\n", 1, 1, 6);
    CASE("nel", "a\xc2\x85" "b\n", 1, 2, 5);

    // 100000 lines: more than one buffer of 64 KiB.
    size_t n = 4 * 100000;
    char *big = malloc(n);
    assert(big != NULL);
    for (size_t i = 0; i < 100000; i++) {
        memcpy(big + 4 * i, "a b\n", 4);
    }
    check("many-lines", big, n, 100000, 200000, 400000);
    free(big);

    // A long line, and U+3000 at the end of the first 64 KiB.
    n = 64 * 1024 + 4;
    big = malloc(n);
    assert(big != NULL);
    memset(big, 'x', 64 * 1024 - 1);
    memcpy(big + 64 * 1024 - 1, "\xe3\x80\x80y\n", 5);
    check("chunk-boundary", big, n, 1, 2, n);
    free(big);

    INVALID("invalid-bytes", "ok\xff\xfe\n");
    INVALID("truncated", "ok \xe2\x82");
    INVALID("surrogate", "a\xed\xa0\x80" "b\n");
    remove(path);

    struct word_count c;
    errno = 0;
    if (word_count("word_count_missing.txt", &c) != -1 || errno != ENOENT) {
        fprintf(stderr, "case missing: no ENOENT error\n");
        return 1;
    }
    puts("ok");
    return 0;
}
WordCount.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

using System.Text;

/// <summary>
/// The lines, words and bytes of a UTF-8 file, as wc counts them. Lines is the number of LF bytes,
/// and a word is a run of one or more code points that are not White_Space.
/// </summary>
public readonly record struct WordCount(long Lines, long Words, long Bytes)
{
    // throwOnInvalidBytes: true makes the decoder throw on a bad byte sequence.
    private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

    /// <summary>True for the 25 code points that have the Unicode property White_Space.</summary>
    public static bool IsWhiteSpace(char c) =>
        c is (>= '\u0009' and <= '\u000d') or ' ' or '\u0085' or '\u00a0' or '\u1680'
            or (>= '\u2000' and <= '\u200a') or '\u2028' or '\u2029' or '\u202f' or '\u205f' or '\u3000';

    /// <summary>Counts the lines, words and bytes of the UTF-8 file at path.</summary>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    /// <exception cref="DecoderFallbackException">The bytes are not valid UTF-8.</exception>
    public static WordCount Read(string path)
    {
        long lines = 0, words = 0;
        bool inWord = false;
        using FileStream stream = File.OpenRead(path);
        // detectEncodingFromByteOrderMarks: false keeps a leading U+FEFF as a character.
        using var reader = new StreamReader(stream, StrictUtf8, detectEncodingFromByteOrderMarks: false, bufferSize: 64 * 1024);
        var buffer = new char[32 * 1024];
        int n;
        while ((n = reader.Read(buffer, 0, buffer.Length)) > 0)
        {
            foreach (char c in buffer.AsSpan(0, n))
            {
                // Each White_Space code point is one char. A surrogate is never white space.
                if (IsWhiteSpace(c))
                {
                    inWord = false;
                    if (c == '\n') lines++;
                }
                else if (!inWord)
                {
                    inWord = true;
                    words++;
                }
            }
        }
        // The reader has read the whole stream, so Position is the number of bytes.
        return new WordCount(lines, words, stream.Position);
    }
}
WordCountTests.cs 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

using System.Text;
using Xunit;

public sealed class WordCountTests : IDisposable
{
    private const int Chunk = 64 * 1024;

    private readonly string dir = Directory.CreateTempSubdirectory("word-count-").FullName;

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

    private string Write(byte[] data)
    {
        string path = Path.Combine(dir, "input.txt");
        File.WriteAllBytes(path, data);
        return path;
    }

    public static TheoryData<string, string, long, long, long> Cases => new()
    {
        { "simple", "one two three\n", 1, 3, 14 },
        { "multiple-spaces", "  a   b  \n", 1, 2, 10 },
        { "tabs-and-lines", "a\tb\nc\n", 2, 3, 6 },
        { "empty", "", 0, 0, 0 },
        { "only-white-space", " \n\t\n", 2, 0, 4 },
        { "no-final-newline", "one two", 0, 2, 7 },
        { "crlf", "a b\r\nc\r\n", 2, 3, 8 },
        { "non-ascii", "na\u00efve caf\u00e9\n", 1, 2, 13 },
        { "unicode-spaces", "a\u00a0b\u3000c\u2028d\n", 1, 4, 13 },
        { "not-white-space", "a\u200bb\u00adc\ufeffd\n", 1, 1, 13 },
        { "control-separators", "a\u001cb\u001fc\n", 1, 1, 6 },
        { "nel", "a\u0085b\n", 1, 2, 5 },
        // 100000 lines: more than one buffer of 64 KiB.
        { "many-lines", string.Concat(Enumerable.Repeat("a b\n", 100000)), 100000, 200000, 400000 },
        // A long line, and U+3000 at the end of the first 64 KiB.
        { "chunk-boundary", new string('x', Chunk - 1) + "\u3000y\n", 1, 2, Chunk + 4 },
    };

    public static TheoryData<string, byte[]> Invalid => new()
    {
        { "invalid-bytes", [0x6f, 0x6b, 0xff, 0xfe, 0x0a] },
        { "truncated", [0x6f, 0x6b, 0x20, 0xe2, 0x82] },
        { "surrogate", [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Counts(string name, string text, long lines, long words, long bytes)
    {
        Assert.False(string.IsNullOrEmpty(name));
        // new UTF8Encoding(false) writes no byte order mark.
        Assert.Equal(new WordCount(lines, words, bytes), WordCount.Read(Write(new UTF8Encoding(false).GetBytes(text))));
    }

    [Theory]
    [MemberData(nameof(Invalid))]
    public void InvalidUtf8(string name, byte[] data)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Throws<DecoderFallbackException>(() => WordCount.Read(Write(data)));
    }

    [Fact]
    public void MissingFile() =>
        Assert.Throws<FileNotFoundException>(() => WordCount.Read(Path.Combine(dir, "missing.txt")));
}
wordCount.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

import { createReadStream } from "node:fs";

// The 25 code points that have the Unicode property White_Space (PropList.txt).
// The regular expression \s is a different set: it has U+FEFF and not U+0085.
const WHITE_SPACE = new Set([
  0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0x85, 0xa0, 0x1680,
  0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a,
  0x2028, 0x2029, 0x202f, 0x205f, 0x3000,
]);

// Returns { lines, words, bytes } for the UTF-8 file at path. lines is the
// number of LF bytes. A word is a run of one or more code points that are not
// White_Space. Bytes that are not valid UTF-8 reject with a TypeError, and a
// missing file rejects with an error whose code is "ENOENT".
export async function wordCount(path) {
  // fatal: true makes the decoder throw on bad bytes. ignoreBOM: true keeps a
  // leading U+FEFF as a character, so that each byte is counted.
  const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
  let lines = 0;
  let words = 0;
  let bytes = 0;
  let inWord = false;
  const count = (text) => {
    for (const ch of text) {
      const cp = ch.codePointAt(0);
      if (WHITE_SPACE.has(cp)) {
        inWord = false;
        if (cp === 0x0a) lines++;
      } else if (!inWord) {
        inWord = true;
        words++;
      }
    }
  };
  for await (const chunk of createReadStream(path)) {
    bytes += chunk.length;
    // stream: true keeps a sequence that the chunk cuts until the next chunk.
    count(decoder.decode(chunk, { stream: true }));
  }
  count(decoder.decode()); // throws if the file ends inside a sequence
  return { lines, words, bytes };
}
wordCount.test.js 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

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 { wordCount } from "./wordCount.js";

const CHUNK = 64 * 1024; // the default highWaterMark of a file stream

// name: [the text of the file, lines, words, bytes]
const CASES = {
  simple: ["one two three\n", 1, 3, 14],
  "multiple-spaces": ["  a   b  \n", 1, 2, 10],
  "tabs-and-lines": ["a\tb\nc\n", 2, 3, 6],
  empty: ["", 0, 0, 0],
  "only-white-space": [" \n\t\n", 2, 0, 4],
  "no-final-newline": ["one two", 0, 2, 7],
  crlf: ["a b\r\nc\r\n", 2, 3, 8],
  "non-ascii": ["na\u00efve caf\u00e9\n", 1, 2, 13],
  "unicode-spaces": ["a\u00a0b\u3000c\u2028d\n", 1, 4, 13],
  "not-white-space": ["a\u200bb\u00adc\ufeffd\n", 1, 1, 13],
  "control-separators": ["a\x1cb\x1fc\n", 1, 1, 6],
  nel: ["a\u0085b\n", 1, 2, 5],
  // 100000 lines: more than one chunk of 64 KiB.
  "many-lines": ["a b\n".repeat(100000), 100000, 200000, 400000],
  // The chunk ends inside the 3 bytes of U+3000.
  "chunk-boundary": ["x".repeat(CHUNK - 1) + "\u3000y\n", 1, 2, CHUNK + 4],
};

// name: the bytes of a file that is not valid UTF-8
const INVALID = {
  "invalid-bytes": [0x6f, 0x6b, 0xff, 0xfe, 0x0a],
  truncated: [0x6f, 0x6b, 0x20, 0xe2, 0x82],
  surrogate: [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a],
};

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

for (const [name, [text, lines, words, bytes]] of Object.entries(CASES)) {
  test(name, async () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(await wordCount(path), { lines, words, bytes });
  });
}

for (const [name, data] of Object.entries(INVALID)) {
  test(name, async () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, Buffer.from(data));
    await assert.rejects(wordCount(path), TypeError);
  });
}

test("missing file", async () => {
  await assert.rejects(wordCount(join(dir, "missing.txt")), { code: "ENOENT" });
});
wordCount.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

import { createReadStream } from "node:fs";

// The 25 code points that have the Unicode property White_Space (PropList.txt).
// The regular expression \s is a different set: it has U+FEFF and not U+0085.
const WHITE_SPACE: ReadonlySet<number> = new Set([
  0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0x85, 0xa0, 0x1680,
  0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a,
  0x2028, 0x2029, 0x202f, 0x205f, 0x3000,
]);

export interface WordCount {
  lines: number; // the number of LF bytes
  words: number; // runs of one or more code points that are not White_Space
  bytes: number;
}

// Returns the counts for the UTF-8 file at path. Bytes that are not valid
// UTF-8 reject with a TypeError, and a missing file rejects with an error
// whose code is "ENOENT".
export async function wordCount(path: string): Promise<WordCount> {
  // fatal: true makes the decoder throw on bad bytes. ignoreBOM: true keeps a
  // leading U+FEFF as a character, so that each byte is counted.
  const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
  const result: WordCount = { lines: 0, words: 0, bytes: 0 };
  let inWord = false;
  const count = (text: string): void => {
    for (const ch of text) {
      const cp = ch.codePointAt(0)!;
      if (WHITE_SPACE.has(cp)) {
        inWord = false;
        if (cp === 0x0a) result.lines++;
      } else if (!inWord) {
        inWord = true;
        result.words++;
      }
    }
  };
  for await (const chunk of createReadStream(path) as AsyncIterable<Buffer>) {
    result.bytes += chunk.length;
    // stream: true keeps a sequence that the chunk cuts until the next chunk.
    count(decoder.decode(chunk, { stream: true }));
  }
  count(decoder.decode()); // throws if the file ends inside a sequence
  return result;
}
wordCount.test.ts 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

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 { wordCount } from "./wordCount.ts";

const CHUNK = 64 * 1024; // the default highWaterMark of a file stream

// name: [the text of the file, lines, words, bytes]
const CASES = {
  simple: ["one two three\n", 1, 3, 14],
  "multiple-spaces": ["  a   b  \n", 1, 2, 10],
  "tabs-and-lines": ["a\tb\nc\n", 2, 3, 6],
  empty: ["", 0, 0, 0],
  "only-white-space": [" \n\t\n", 2, 0, 4],
  "no-final-newline": ["one two", 0, 2, 7],
  crlf: ["a b\r\nc\r\n", 2, 3, 8],
  "non-ascii": ["na\u00efve caf\u00e9\n", 1, 2, 13],
  "unicode-spaces": ["a\u00a0b\u3000c\u2028d\n", 1, 4, 13],
  "not-white-space": ["a\u200bb\u00adc\ufeffd\n", 1, 1, 13],
  "control-separators": ["a\x1cb\x1fc\n", 1, 1, 6],
  nel: ["a\u0085b\n", 1, 2, 5],
  // 100000 lines: more than one chunk of 64 KiB.
  "many-lines": ["a b\n".repeat(100000), 100000, 200000, 400000],
  // The chunk ends inside the 3 bytes of U+3000.
  "chunk-boundary": ["x".repeat(CHUNK - 1) + "\u3000y\n", 1, 2, CHUNK + 4],
};

// name: the bytes of a file that is not valid UTF-8
const INVALID = {
  "invalid-bytes": [0x6f, 0x6b, 0xff, 0xfe, 0x0a],
  truncated: [0x6f, 0x6b, 0x20, 0xe2, 0x82],
  surrogate: [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a],
};

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

for (const [name, [text, lines, words, bytes]] of Object.entries(CASES)) {
  test(name, async () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(await wordCount(path), { lines, words, bytes });
  });
}

for (const [name, data] of Object.entries(INVALID)) {
  test(name, async () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, Buffer.from(data));
    await assert.rejects(wordCount(path), TypeError);
  });
}

test("missing file", async () => {
  await assert.rejects(wordCount(join(dir, "missing.txt")), { code: "ENOENT" });
});
word_count.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

// Package wordcount counts the lines, words and bytes of a UTF-8 file, as wc does.
package wordcount

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
	"unicode"
	"unicode/utf8"
)

// ErrInvalidUTF8 reports bytes that are not valid UTF-8.
var ErrInvalidUTF8 = errors.New("invalid UTF-8")

// Counts holds the result: Lines is the number of LF bytes, and a word is a
// run of one or more runes that are not white space.
type Counts struct {
	Lines, Words, Bytes int64
}

// Count reads UTF-8 text from r. unicode.IsSpace is true for the runes that
// have the Unicode property White_Space.
func Count(r io.Reader) (Counts, error) {
	var c Counts
	br := bufio.NewReaderSize(r, 64*1024)
	inWord := false
	for {
		ch, size, err := br.ReadRune()
		if errors.Is(err, io.EOF) {
			return c, nil
		}
		if err != nil {
			return Counts{}, err
		}
		// ReadRune gives U+FFFD with size 1 for a bad byte. A real U+FFFD has size 3.
		if ch == utf8.RuneError && size == 1 {
			return Counts{}, fmt.Errorf("%w at byte %d", ErrInvalidUTF8, c.Bytes)
		}
		c.Bytes += int64(size)
		switch {
		case unicode.IsSpace(ch):
			inWord = false
			if ch == '\n' {
				c.Lines++
			}
		case !inWord:
			inWord = true
			c.Words++
		}
	}
}

// CountFile counts the lines, words and bytes of the file at path.
func CountFile(path string) (Counts, error) {
	f, err := os.Open(path)
	if err != nil {
		return Counts{}, err
	}
	defer f.Close()
	return Count(f)
}
word_count_test.go 82 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

package wordcount

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

const chunk = 64 * 1024 // the size of the buffer of the reader

var cases = []struct {
	name string
	data string
	want Counts
}{
	{"simple", "one two three\n", Counts{1, 3, 14}},
	{"multiple-spaces", "  a   b  \n", Counts{1, 2, 10}},
	{"tabs-and-lines", "a\tb\nc\n", Counts{2, 3, 6}},
	{"empty", "", Counts{0, 0, 0}},
	{"only-white-space", " \n\t\n", Counts{2, 0, 4}},
	{"no-final-newline", "one two", Counts{0, 2, 7}},
	{"crlf", "a b\r\nc\r\n", Counts{2, 3, 8}},
	{"non-ascii", "na\u00efve caf\u00e9\n", Counts{1, 2, 13}},
	{"unicode-spaces", "a\u00a0b\u3000c\u2028d\n", Counts{1, 4, 13}},
	{"not-white-space", "a\u200bb\u00adc\ufeffd\n", Counts{1, 1, 13}},
	{"control-separators", "a\x1cb\x1fc\n", Counts{1, 1, 6}},
	{"nel", "a\u0085b\n", Counts{1, 2, 5}},
	// 100000 lines: more than one buffer of 64 KiB.
	{"many-lines", strings.Repeat("a b\n", 100000), Counts{100000, 200000, 400000}},
	// The buffer ends inside the 3 bytes of U+3000.
	{"chunk-boundary", strings.Repeat("x", chunk-1) + "\u3000y\n", Counts{1, 2, chunk + 4}},
}

// The bytes of files that are not valid UTF-8.
var invalid = []struct{ name, data string }{
	{"invalid-bytes", "ok\xff\xfe\n"},
	{"truncated", "ok \xe2\x82"},
	{"surrogate", "a\xed\xa0\x80b\n"},
}

func write(t *testing.T, data string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "input.txt")
	if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
		t.Fatal(err)
	}
	return path
}

func TestCountFile(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := CountFile(write(t, c.data))
			if err != nil || got != c.want {
				t.Fatalf("CountFile = %+v, %v; want %+v", got, err, c.want)
			}
		})
	}
}

func TestInvalidUTF8(t *testing.T) {
	for _, c := range invalid {
		t.Run(c.name, func(t *testing.T) {
			if _, err := CountFile(write(t, c.data)); !errors.Is(err, ErrInvalidUTF8) {
				t.Fatalf("err = %v; want ErrInvalidUTF8", err)
			}
		})
	}
}

func TestMissingFile(t *testing.T) {
	_, err := CountFile(filepath.Join(t.TempDir(), "missing.txt"))
	if !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("err = %v; want fs.ErrNotExist", err)
	}
}
word_count.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

//! Counts the lines, words and bytes of a UTF-8 file, as wc does.

use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;

/// The result: `lines` is the number of LF bytes, and a word is a run of one or
/// more chars that are not white space.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Counts {
    pub lines: u64,
    pub words: u64,
    pub bytes: u64,
}

/// Counts UTF-8 text from `r`, one line at a time. An LF byte is never part of
/// a longer UTF-8 sequence, so each line decodes on its own. Bytes that are not
/// valid UTF-8 give an error of kind `InvalidData`.
pub fn count<R: Read>(r: R) -> io::Result<Counts> {
    let mut reader = BufReader::with_capacity(64 * 1024, r);
    let mut line = Vec::new();
    let mut c = Counts::default();
    loop {
        line.clear();
        // read_until retries on ErrorKind::Interrupted.
        let n = reader.read_until(b'\n', &mut line)?;
        if n == 0 {
            return Ok(c);
        }
        c.bytes += n as u64;
        let text = std::str::from_utf8(&line).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        let mut in_word = false;
        for ch in text.chars() {
            // char::is_whitespace is true for the chars that have the property White_Space.
            if ch.is_whitespace() {
                in_word = false;
                if ch == '\n' {
                    c.lines += 1;
                }
            } else if !in_word {
                in_word = true;
                c.words += 1;
            }
        }
    }
}

/// Counts the lines, words and bytes of the file at `path`.
pub fn word_count(path: impl AsRef<Path>) -> io::Result<Counts> {
    count(File::open(path)?)
}
tests/word_count_test.rs 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-word-count/.

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

use algo_compute_a_word_count::{word_count, Counts};

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

const fn counts(lines: u64, words: u64, bytes: u64) -> Counts {
    Counts { lines, words, bytes }
}

const CASES: &[(&str, &str, Counts)] = &[
    ("simple", "one two three\n", counts(1, 3, 14)),
    ("multiple-spaces", "  a   b  \n", counts(1, 2, 10)),
    ("tabs-and-lines", "a\tb\nc\n", counts(2, 3, 6)),
    ("empty", "", counts(0, 0, 0)),
    ("only-white-space", " \n\t\n", counts(2, 0, 4)),
    ("no-final-newline", "one two", counts(0, 2, 7)),
    ("crlf", "a b\r\nc\r\n", counts(2, 3, 8)),
    ("non-ascii", "na\u{ef}ve caf\u{e9}\n", counts(1, 2, 13)),
    ("unicode-spaces", "a\u{a0}b\u{3000}c\u{2028}d\n", counts(1, 4, 13)),
    ("not-white-space", "a\u{200b}b\u{ad}c\u{feff}d\n", counts(1, 1, 13)),
    ("control-separators", "a\x1cb\x1fc\n", counts(1, 1, 6)),
    ("nel", "a\u{85}b\n", counts(1, 2, 5)),
];

/// The bytes of files that are not valid UTF-8.
const INVALID: &[(&str, &[u8])] = &[
    ("invalid-bytes", b"ok\xff\xfe\n"),
    ("truncated", b"ok \xe2\x82"),
    ("surrogate", b"a\xed\xa0\x80b\n"),
];

#[test]
fn cases() {
    for (name, text, want) in CASES {
        let path = write(name, text.as_bytes());
        assert_eq!(word_count(&path).unwrap(), *want, "{name}");
        fs::remove_file(&path).unwrap();
    }
}

#[test]
fn many_lines() {
    // 100000 lines: more than one buffer of 64 KiB.
    let path = write("many-lines", &b"a b\n".repeat(100_000));
    assert_eq!(word_count(&path).unwrap(), counts(100_000, 200_000, 400_000));
    fs::remove_file(&path).unwrap();
}

#[test]
fn chunk_boundary() {
    // The buffer ends inside the 3 bytes of U+3000.
    let mut data = vec![b'x'; 64 * 1024 - 1];
    data.extend_from_slice("\u{3000}y\n".as_bytes());
    let path = write("chunk-boundary", &data);
    assert_eq!(word_count(&path).unwrap(), counts(1, 2, 64 * 1024 + 4));
    fs::remove_file(&path).unwrap();
}

#[test]
fn invalid_utf8() {
    for (name, data) in INVALID {
        let path = write(name, data);
        let err = word_count(&path).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData, "{name}");
        fs::remove_file(&path).unwrap();
    }
}

#[test]
fn missing_file() {
    let err = word_count(std::env::temp_dir().join("word-count-missing.txt")).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}
word_count.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-word-count/.

# word_count PATH
# Prints "LINES WORDS BYTES" for the UTF-8 file at PATH. LINES is the number of
# LF bytes, and a word is a run of one or more code points that are not
# White_Space. Returns a nonzero status, and prints nothing on stdout, if the
# file cannot be read or its bytes are not valid UTF-8.
word_count() {
  local lines words bytes
  # iconv stops with a nonzero status on bytes that are not valid UTF-8.
  iconv -f UTF-8 -t UTF-8 <"$1" >/dev/null || return
  lines=$(LC_ALL=C wc -l <"$1") || return
  bytes=$(LC_ALL=C wc -c <"$1") || return
  # wc -w splits at the white space of the locale, and locales do not agree on
  # it. So sed changes the White_Space code points above U+007F to a space, and
  # wc counts in the C locale, where white space is tab, LF, VT, FF, CR and
  # space. Each pattern is the UTF-8 bytes of the code points:
  # U+0085 U+00A0, U+1680, U+2000..U+200A U+2028 U+2029 U+202F, U+205F, U+3000.
  words=$(LC_ALL=C sed \
    -e $'s/\xc2[\x85\xa0]/ /g' \
    -e $'s/\xe1\x9a\x80/ /g' \
    -e $'s/\xe2\x80[\x80-\x8a\xa8\xa9\xaf]/ /g' \
    -e $'s/\xe2\x81\x9f/ /g' \
    -e $'s/\xe3\x80\x80/ /g' <"$1" | LC_ALL=C wc -w) || return
  # $((...)) also accepts the blanks that some wc programs print.
  printf '%d %d %d\n' "$((lines))" "$((words))" "$((bytes))"
}
test_word_count.bats 54 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-word-count/.

bats_require_minimum_version 1.5.0

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

check() { # check BYTES WANT
  printf '%b' "$1" >"$file"
  run word_count "$file"
  [ "$status" -eq 0 ]
  [ "$output" = "$2" ]
}

invalid() { # invalid BYTES
  printf '%b' "$1" >"$file"
  run --separate-stderr word_count "$file"
  [ "$status" -ne 0 ]
  [ -z "$output" ]
}

@test "simple" { check 'one two three\n' "1 3 14"; }
@test "multiple-spaces" { check '  a   b  \n' "1 2 10"; }
@test "tabs-and-lines" { check 'a\tb\nc\n' "2 3 6"; }
@test "empty" { check '' "0 0 0"; }
@test "only-white-space" { check ' \n\t\n' "2 0 4"; }
@test "no-final-newline" { check 'one two' "0 2 7"; }
@test "crlf" { check 'a b\r\nc\r\n' "2 3 8"; }
@test "non-ascii" { check 'na\xc3\xafve caf\xc3\xa9\n' "1 2 13"; }
@test "unicode-spaces" { check 'a\xc2\xa0b\xe3\x80\x80c\xe2\x80\xa8d\n' "1 4 13"; }
@test "not-white-space" { check 'a\xe2\x80\x8bb\xc2\xadc\xef\xbb\xbfd\n' "1 1 13"; }
@test "control-separators" { check 'a\x1cb\x1fc\n' "1 1 6"; }
@test "nel" { check 'a\xc2\x85b\n' "1 2 5"; }

@test "many-lines" {
  yes 'a b' | head -n 100000 >"$file"
  run word_count "$file"
  [ "$status" -eq 0 ]
  [ "$output" = "100000 200000 400000" ]
}

@test "invalid-bytes" { invalid 'ok\xff\xfe\n'; }
@test "truncated" { invalid 'ok \xe2\x82'; }
@test "surrogate" { invalid 'a\xed\xa0\x80b\n'; }

@test "missing" {
  run --separate-stderr word_count "$BATS_TEST_TMPDIR/missing.txt"
  [ "$status" -ne 0 ]
  [ -z "$output" ]
}

References

  1. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), wc, DESCRIPTION; ENVIRONMENT VARIABLES (LC_CTYPE)
  2. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 7: Locale, 7.3.1 LC_CTYPE, the keyword space
  3. Unicode Character Database, PropList.txt, White_Space
  4. The Python Standard Library, codecs, getincrementaldecoder; IncrementalDecoder.decode
  5. MDN Web Docs, TextDecoder() constructor, options fatal and ignoreBOM
  6. MDN Web Docs, TextDecoder.decode(), the option stream; Exceptions
  7. Java SE 25 API, java.io.InputStreamReader, InputStreamReader(InputStream, CharsetDecoder)
  8. Java SE 25 API, java.nio.charset.CharsetDecoder, decode, CodingErrorAction.REPORT
  9. .NET API reference, UTF8Encoding constructors, UTF8Encoding(Boolean, Boolean)
  10. Go standard library, package bufio, Reader.ReadRune
  11. Go standard library, package unicode, IsSpace
  12. The Rust Standard Library, std::io::BufRead, read_until
  13. The Rust Standard Library, std::str::from_utf8, Errors
  14. The Rust Standard Library, char, is_whitespace
  15. F. Yergeau, RFC 3629, UTF-8, a transformation format of ISO 10646 (2003), Section 3 and Section 10
  16. The Python Standard Library, Built-in Types, str.isspace; str.split
  17. MDN Web Docs, Character class escape: \d, \D, \w, \W, \s, \S
  18. MDN Web Docs, Lexical grammar, White space; Line terminators
  19. Java SE 25 API, java.lang.Character, isWhitespace(int)
  20. .NET API reference, Char.IsWhiteSpace, Remarks
  21. cppreference.com, iswspace

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