Taskcore
Align columns of text
Also called align columns, column alignment, pad fields to columns, format text as a table.
Align the fields of a text in columns, left, right or center, where a dollar sign separates two fields and the width of a column is the number of code points of its longest field.
- Evidence
- Code in 10 languages
Task
Align the fields of a text in columns. Rosetta Code states the task like this: "Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space."1 The task also says: "Further, allow for each word in a column to be either left justified, right justified, or center justified within its column."1 The function takes the text and the alignment, left, right or center, and returns the aligned text.
The task leaves some rules open. This page uses these rules:
- A line ends at LF. A final LF ends the last line and does not start a new line. A last line with no LF is a line too.
- A
$separates two fields. A$at the end of a line does not start a new field, because "The example input texts lines may, or may not, have trailing dollar characters."1 Two$with nothing between them make an empty field. An empty line has no fields, and stays empty in the result. - The width of a column is the number of code points of its longest field. A line can have fewer fields than the other lines. Then it has no field in the last columns.
- All the columns use the same alignment. The task says: "All columns should share the same alignment."1
- One space separates two columns. The task says: "The minimum space between columns should be computed from the text and not hard-coded."1 Here the space is the result of the widths that the code calculates, and one space more.
- The padding goes where the alignment puts it. For
left, the spaces go after the field. Forright, they go before the field. Forcenter, the spaces go on the two sides, and if their number is odd, the odd space goes after the field. - The last field of a line has no padding after it. The task says: "Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task."1 So no line of the result ends with a space that comes from padding.
- Each line of the result ends with LF. An empty text gives an empty result. An alignment that is not
left,rightorcenteris an error.
For example, the text a$bb$c LF dd$e$fff LF with left gives a bb c LF dd e fff LF.
Solutions
The method is the same in each language:
- Split the text into lines, and split each line into fields.
- For each column, find the largest number of code points of a field in the column.
- Write each line again. Before each field except the first, write one space. Then write the padding before the field, the field, and the padding after the field if it is not the last field of the line.
The number of code points is not the length of the string in all languages. Some languages count bytes, and some count UTF-16 code units. Each solution uses a function that counts code points, so the column of a field with the letter é or with a character outside the BMP has the correct width.
- Python. A
strcounts code points: "Strings are immutable sequences of Unicode code points."2 Solen(field)is the width.text.split('\n')gives an empty last part after a final LF, and the code removes it.line.split('$')keeps empty fields, because "consecutive delimiters are not grouped together and are deemed to delimit empty strings".2 The code removes the last field if the line ends with$. The code builds the padding with' ' * n, and does not usestr.center(see the pitfalls). A bad alignment raisesValueError. - JavaScript and TypeScript. The string property
length"contains the length of the string in UTF-16 code units."3 So the code counts code points with afor...ofloop. The string iterator "yields the Unicode code points of the string value as individual strings".4 The code builds the padding with' '.repeat(n), and does not usepadEnd(see the pitfalls). A bad alignment throws aRangeError. The TypeScript file adds the typeAlignand the types of the cases. - Java.
String.length()counts UTF-16 units: "The length is equal to the number of Unicode code units in the string."5 The code usescodePointCount(0, s.length()), which "Returns the number of Unicode code points in the specified text range of this" string.5 A loop withindexOfsplits the lines and the fields, and aStringBuilderbuilds the result. A bad alignment throws anIllegalArgumentException. - C#. "The Length property returns the number of Char objects in this instance, not the number of Unicode characters."6 The code counts code points with
EnumerateRunes().Count().EnumerateRunes"Returns an enumeration of Rune from this string."7StringBuilder.Append(' ', n)writes the padding. A bad alignment throws anArgumentException. - Go. "A string value is a (possibly empty) sequence of bytes", and
lengives the number of bytes.8 The code usesutf8.RuneCountInString. "RuneCountInString is like RuneCount but its input is a string", and "RuneCount returns the number of runes in p."9strings.Splitsplits the text and the lines, and astrings.Builderbuilds the result. A bad alignment gives the errorErrBadAlign. - Rust. For
str::len, "This length is in bytes".10 The code useschars().count(). A Rustchar"represents a Unicode Scalar Value".10split_terminatorsplits the text into lines and each line into fields. It is likesplit, "except that the trailing substring is skipped if empty".10 So a final LF does not give an empty line, and a final$does not give an empty field. The alignment is the enumAlign, and itsFromStrgives the errorBadAlignfor a bad word. - C. The code walks the bytes of the text. In UTF-8, each byte after the first byte of a code point has the form
10xxxxxx: "The following octet(s) all have the higher-order bit set to 1 and the following bit set to 0".11 So the code counts the bytes that are not from 0x80 to 0xBF. The code can split the text at each$byte and LF byte, because "US-ASCII octet values do not appear otherwise in a UTF-8 encoded character stream."11 A first pass finds the size of the result, and a second pass writes it into onemallocblock.align_columnsreturns the new string, or NULL witherrnoset toEINVALfor a bad alignment orENOMEM. - C++. The code is like the C code. It splits the text into
std::string_viewparts, counts code points withstd::ranges::count_ifon the bytes, and appends to astd::string. A bad alignment throwsstd::invalid_argument. - Bash. The function reads the text from stdin, and prints the result.
read -rreads each line, and the test|| [[ -n $line ]]keeps a last line with no LF.${rest%%\$*}and${rest#*\$}split each line at each$. In Bash,${#parameter}"Substitutes the length in characters of the value of" the parameter,12 and a character depends on the locale. So the function setslocal LC_ALL=C.LC_ALL"overrides the value of LANG and any other LC_ variable specifying a locale category."12 The C locale is the POSIX locale,13 and "The POSIX locale shall contain 256 single-byte characters".14 Then${#t}counts bytes. The function removes the bytes from 0x80 to 0xBF and counts the bytes that stay, as the C code does.printf -v out '%*s'with an empty string makes the padding. A bad alignment prints a message and returns 2.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
rosetta-left,rosetta-rightandrosetta-center: the input text of the Rosetta Code task, with each of the three alignments.1two-lines:a$bb$canddd$e$fff, left. The result isa bb canddd e fff.empty: an empty text gives an empty result.empty-line:a$b, an empty line, andccc$d. The empty line stays empty, and the other lines area bandccc d.empty-field:a$$bhas three fields, and the second is empty. Withc$dd$e, the result isa bandc dd e.trailing-dollar:a$b$has two fields, not three.ragged:a$b$candddd, right. The second line has one field, so it isdddwith no space after it.one-column:a,bbb,cc, right. The result isa,bbb,cc.no-final-newline: the text ends with no LF. The result still ends with LF.center-odd:ain a column of width 4 is one space,a, two spaces. The odd space goes after the field.center-last: the last field of a line gets the spaces before it, and no spaces after it.non-ascii:caféhas 4 code points and 5 bytes in UTF-8, so its column has width 4.outside-the-bmp: U+1F600 is one code point and two UTF-16 code units, so it counts as 1.spaces-in-field:a bis one field, because only$separates fields.
The tests also align 100000 lines, 0$x to 99999$x, to the right. The first line of the result is 0 x and the last line is 99999 x. The case in cases/errors.jsonl uses the alignment justify and must give the error bad-align. The toolchain does not load that file yet, so each test file holds the case by name.
Pitfalls
- The length of a string is often not the number of code points. Go and Rust strings count bytes,810 and Java, C# and JavaScript strings count UTF-16 code units.563 With such a length,
caféhas width 5 in Go and Rust, and a character outside the BMP has width 2 in Java, C# and JavaScript. Then the column of that field is too wide by one. padEndandpadStartpad to a number of UTF-16 code units. The parametertargetLengthis "The length of the resulting string once the current str has been padded."15 So a string with a character outside the BMP gets one space too few. Here the letter U+1D465 gets one space andabalso gets one space:
// U+1D465 is a letter outside the BMP, so it is two UTF-16 code units.
const rows = [["\u{1D465}", "1"], ["ab", "2"]];
for (const [a, b] of rows) {
console.log(`[${a.padEnd(3)}] ${b}`);
}
console.log("\u{1D465}".length, [..."\u{1D465}"].length);
[𝑥 ] 1
[ab ] 2
2 1
printfpads to a number of bytes. POSIX says for the field width: "If the converted value has fewer bytes than the field width, it shall be padded with" spaces.16 The Bashprintfdoes the same in a UTF-8 locale, but${#word}counts characters. Socafé, 5 bytes, gets no space, andabcgets two:
export LC_ALL=C.UTF-8
word='café'
printf '[%-5s]\n' "$word" abc
echo "${#word}"
[café]
[abc ]
4
- Python
str.centerdoes not put the odd space on the same side each time. The documentation says only "Return centered in a string of length" width.2 It does not say where the odd space goes, and the side changes with the length of the string:
for word, width in [("a", 4), ("ab", 5), ("abc", 6)]:
print(f"[{word.center(width)}]")
[ a ]
[ ab ]
[ abc ]
So the solutions calculate the left padding as half of the padding, rounded down, and put the rest after the field.
- A code point is not one column on the screen. Some characters "occur only in the context of East Asian typography where they are wide characters",17 and a terminal shows them in two columns. POSIX
wcwidthcan "determine the number of column positions required for the wide character".18 Also, "nonspacing marks do not possess actual advance width."17 So a letter with a combining mark is two code points in one column. Unicode text segmentation finds the boundaries of "user-perceived characters, words, and sentences."19 This page counts code points. For a terminal, count the columns of each grapheme cluster. - A
$at the end of a line can add an empty column. If the code splitsa$b$at each$, it gets the fieldsa,band an empty field. Then the fieldbis not the last field, and the line gets padding afterb. Remove an empty last field, or use a split that does not give it, such as Rustsplit_terminator.10
Related tasks
- Delimited text: text with a separator between fields, such as CSV and TSV.
- Fixed-width text format: records in which each field has a fixed number of columns.
- Find the length of a string: the length of a string in bytes, code units, code points and graphemes.
- Count the graphemes of a string: count the user-perceived characters of a string.
- Characters, code points and graphemes: what a code point is, and how it differs from a byte and a character.
- UTF-8: the encoding that the C and Bash solutions read one byte at a time.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/align-columns-of-text/.
"""Aligns the columns of a text in which a $ separates the fields."""
ALIGNS = ("left", "right", "center")
def align_columns(text: str, align: str) -> str:
"""Returns text with its fields in columns.
A line ends at LF. Each $ in a line separates two fields, and a $ at the
end of a line does not start a new field. An empty line has no fields. The
width of a column is the largest number of code points of a field in it.
Each field is padded with spaces to the width of its column, on the right
(left), on the left (right), or on the two sides (center), with the odd
space on the right. One space separates two columns. The padding on the
right of the last field of a line is not written. Each line of the result
ends with LF. Raises ValueError if align is not left, right or center.
"""
if align not in ALIGNS:
raise ValueError(f"bad align: {align!r}")
lines = text.split("\n")
if lines[-1] == "":
# A final LF ends the last line. It does not start a new line.
lines.pop()
rows = [split_fields(line) for line in lines]
widths: list[int] = []
for row in rows:
for j, field in enumerate(row):
if j == len(widths):
widths.append(0)
widths[j] = max(widths[j], len(field))
out = []
for row in rows:
parts = []
for j, field in enumerate(row):
pad = widths[j] - len(field)
left = {"left": 0, "right": pad, "center": pad // 2}[align]
right = pad - left if j < len(row) - 1 else 0
parts.append(" " * left + field + " " * right)
out.append(" ".join(parts) + "\n")
return "".join(out)
def split_fields(line: str) -> list[str]:
"""Returns the fields of a line: none for an empty line."""
if line == "":
return []
fields = line.split("$")
if line.endswith("$"):
fields.pop()
return fields
test_align_columns.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/align-columns-of-text/.
import json
import pathlib
import unittest
from align_columns import align_columns
CASES = pathlib.Path(__file__).resolve().parent.parent.parent / "cases"
def load(name):
with open(CASES / name, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
class AlignColumnsTest(unittest.TestCase):
def test_cases(self):
for case in load("basic.jsonl") + load("edge.jsonl"):
with self.subTest(case["name"]):
args = case["args"]
self.assertEqual(align_columns(args["text"], args["align"]), case["expect"])
def test_many_lines(self):
text = "".join(f"{i}$x\n" for i in range(100000))
lines = align_columns(text, "right").split("\n")
self.assertEqual(len(lines), 100001)
self.assertEqual(lines[0], " 0 x")
self.assertEqual(lines[99999], "99999 x")
def test_bad_align(self):
for case in load("errors.jsonl"):
with self.subTest(case["name"]):
with self.assertRaises(ValueError):
align_columns(case["args"]["text"], case["args"]["align"])
if __name__ == "__main__":
unittest.main()
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
#include "align_columns.hpp"
#include <algorithm>
#include <stdexcept>
#include <vector>
namespace {
// Returns the number of code points in the UTF-8 text. A byte from 0x80 to
// 0xBF continues a code point, so the code counts the other bytes.
std::size_t code_points(std::string_view s) {
return static_cast<std::size_t>(
std::ranges::count_if(s, [](char c) { return (static_cast<unsigned char>(c) & 0xC0) != 0x80; }));
}
// Splits s at each sep. A sep at the end does not start a new part, and an
// empty s has no parts.
std::vector<std::string_view> split(std::string_view s, char sep) {
std::vector<std::string_view> parts;
while (!s.empty()) {
std::size_t at = s.find(sep);
parts.push_back(s.substr(0, at));
s = at == std::string_view::npos ? std::string_view{} : s.substr(at + 1);
}
return parts;
}
} // namespace
std::string align_columns(std::string_view text, std::string_view align) {
if (align != "left" && align != "right" && align != "center") {
throw std::invalid_argument("align must be left, right or center");
}
std::vector<std::vector<std::string_view>> rows;
std::vector<std::size_t> widths;
for (std::string_view line : split(text, '\n')) {
rows.push_back(split(line, '$'));
const auto& fields = rows.back();
if (fields.size() > widths.size()) {
widths.resize(fields.size());
}
for (std::size_t j = 0; j < fields.size(); j++) {
widths[j] = std::max(widths[j], code_points(fields[j]));
}
}
std::string out;
for (const auto& fields : rows) {
for (std::size_t j = 0; j < fields.size(); j++) {
std::size_t pad = widths[j] - code_points(fields[j]);
std::size_t left = align == "left" ? 0 : align == "right" ? pad : pad / 2;
if (j > 0) {
out += ' ';
}
out.append(left, ' ');
out += fields[j];
if (j + 1 < fields.size()) {
out.append(pad - left, ' ');
}
}
out += '\n';
}
return out;
}
align_columns.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
#pragma once
#include <string>
#include <string_view>
// Aligns the fields of the text in columns. A $ separates two fields, and
// align is "left", "right" or "center". Throws std::invalid_argument if
// align is not one of these words.
std::string align_columns(std::string_view text, std::string_view align);
test_align_columns.cpp 100 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
#include "align_columns.hpp"
#include <iostream>
#include <stdexcept>
#include <string>
namespace {
const std::string rosetta =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n"
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n"
"column$are$separated$by$at$least$one$space.\n"
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"justified,$right$justified,$or$center$justified$within$its$column.\n"
;
struct Case {
std::string name, text, align, want;
};
const Case cases[] = {
{"rosetta-left", rosetta, "left", "Given a text file of many lines, where fields within a line\n"
"are delineated by a single 'dollar' character, write a program\n"
"that aligns each column of fields by ensuring that words in each\n"
"column are separated by at least one space.\n"
"Further, allow for each word in a column to be either left\n"
"justified, right justified, or center justified within its column.\n"},
{"rosetta-right", rosetta, "right", " Given a text file of many lines, where fields within a line\n"
" are delineated by a single 'dollar' character, write a program\n"
" that aligns each column of fields by ensuring that words in each\n"
" column are separated by at least one space.\n"
" Further, allow for each word in a column to be either left\n"
"justified, right justified, or center justified within its column.\n"},
{"rosetta-center", rosetta, "center", " Given a text file of many lines, where fields within a line\n"
" are delineated by a single 'dollar' character, write a program\n"
" that aligns each column of fields by ensuring that words in each\n"
" column are separated by at least one space.\n"
" Further, allow for each word in a column to be either left\n"
"justified, right justified, or center justified within its column.\n"},
{"two-lines", "a$bb$c\ndd$e$fff\n", "left", "a bb c\ndd e fff\n"},
{"empty", "", "left", ""},
{"empty-line", "a$b\n"
"\n"
"ccc$d\n", "left", "a b\n"
"\n"
"ccc d\n"},
{"empty-field", "a$$b\nc$dd$e\n", "left", "a b\nc dd e\n"},
{"trailing-dollar", "a$b$\ncc$d\n", "left", "a b\ncc d\n"},
{"ragged", "a$b$c\nddd\n", "right", " a b c\nddd\n"},
{"one-column", "a\n"
"bbb\n"
"cc\n", "right", " a\n"
"bbb\n"
" cc\n"},
{"no-final-newline", "a$b\ncc$d", "left", "a b\ncc d\n"},
{"center-odd", "a$b\nbbbb$c\n", "center", " a b\nbbbb c\n"},
{"center-last", "x$a\nx$bbbb\n", "center", "x a\nx bbbb\n"},
{"non-ascii", "caf\303\251$x\nab$y\n", "left", "caf\303\251 x\nab y\n"},
{"outside-the-bmp", "\360\237\230\200$x\nab$y\n", "left", "\360\237\230\200 x\nab y\n"},
{"spaces-in-field", "a b$c\nd$e\n", "left", "a b c\nd e\n"},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
std::string got = align_columns(c.text, c.align);
if (got != c.want) {
std::cerr << "FAIL " << c.name << ": got \"" << got << "\"\n";
failures++;
}
}
// 100000 lines from 0$x to 99999$x.
std::string many;
for (int i = 0; i < 100000; i++) {
many += std::to_string(i) + "$x\n";
}
std::string got = align_columns(many, "right");
if (got.size() != 100000 * 8 || !got.starts_with(" 0 x\n") || !got.ends_with("99999 x\n")) {
std::cerr << "FAIL many-lines\n";
failures++;
}
try {
align_columns("a$b\n", "justify");
std::cerr << "FAIL bad-align: no exception\n";
failures++;
} catch (const std::invalid_argument&) {
}
if (failures == 0) {
std::cout << "ok\n";
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
import java.util.ArrayList;
import java.util.List;
/** Aligns the fields of a text in columns. */
public final class AlignColumns {
private AlignColumns() {}
/**
* Aligns the fields of the text in columns. A $ separates two fields, and align is "left",
* "right" or "center".
*
* @throws IllegalArgumentException if align is not one of these words
*/
public static String align(String text, String align) {
if (!align.equals("left") && !align.equals("right") && !align.equals("center")) {
throw new IllegalArgumentException("align must be left, right or center: " + align);
}
List<List<String>> rows = new ArrayList<>();
List<Integer> widths = new ArrayList<>();
for (String line : split(text, '\n')) {
List<String> fields = split(line, '$');
rows.add(fields);
for (int j = 0; j < fields.size(); j++) {
int width = width(fields.get(j));
if (j == widths.size()) {
widths.add(width);
} else if (width > widths.get(j)) {
widths.set(j, width);
}
}
}
StringBuilder out = new StringBuilder();
for (List<String> fields : rows) {
for (int j = 0; j < fields.size(); j++) {
String field = fields.get(j);
int pad = widths.get(j) - width(field);
int left =
switch (align) {
case "left" -> 0;
case "right" -> pad;
default -> pad / 2;
};
if (j > 0) {
out.append(' ');
}
out.append(" ".repeat(left)).append(field);
if (j + 1 < fields.size()) {
out.append(" ".repeat(pad - left));
}
}
out.append('\n');
}
return out.toString();
}
/** Returns the number of code points in s. String.length() counts UTF-16 code units. */
private static int width(String s) {
return s.codePointCount(0, s.length());
}
/** Splits s at each sep. A sep at the end does not start a new part. */
private static List<String> split(String s, char sep) {
List<String> parts = new ArrayList<>();
int start = 0;
while (start < s.length()) {
int at = s.indexOf(sep, start);
if (at < 0) {
at = s.length();
}
parts.add(s.substring(start, at));
start = at + 1;
}
return parts;
}
}
AlignColumnsTest.java 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class AlignColumnsTest {
static final String ROSETTA =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" +
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" +
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" +
"column$are$separated$by$at$least$one$space.\n" +
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" +
"justified,$right$justified,$or$center$justified$within$its$column.\n";
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("rosetta-left", ROSETTA, "left", "Given a text file of many lines, where fields within a line\n" +
"are delineated by a single 'dollar' character, write a program\n" +
"that aligns each column of fields by ensuring that words in each\n" +
"column are separated by at least one space.\n" +
"Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n"),
Arguments.of("rosetta-right", ROSETTA, "right", " Given a text file of many lines, where fields within a line\n" +
" are delineated by a single 'dollar' character, write a program\n" +
" that aligns each column of fields by ensuring that words in each\n" +
" column are separated by at least one space.\n" +
" Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n"),
Arguments.of("rosetta-center", ROSETTA, "center", " Given a text file of many lines, where fields within a line\n" +
" are delineated by a single 'dollar' character, write a program\n" +
" that aligns each column of fields by ensuring that words in each\n" +
" column are separated by at least one space.\n" +
" Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n"),
Arguments.of("two-lines", "a$bb$c\ndd$e$fff\n", "left", "a bb c\ndd e fff\n"),
Arguments.of("empty", "", "left", ""),
Arguments.of("empty-line", "a$b\n" +
"\n" +
"ccc$d\n", "left", "a b\n" +
"\n" +
"ccc d\n"),
Arguments.of("empty-field", "a$$b\nc$dd$e\n", "left", "a b\nc dd e\n"),
Arguments.of("trailing-dollar", "a$b$\ncc$d\n", "left", "a b\ncc d\n"),
Arguments.of("ragged", "a$b$c\nddd\n", "right", " a b c\nddd\n"),
Arguments.of("one-column", "a\n" +
"bbb\n" +
"cc\n", "right", " a\n" +
"bbb\n" +
" cc\n"),
Arguments.of("no-final-newline", "a$b\ncc$d", "left", "a b\ncc d\n"),
Arguments.of("center-odd", "a$b\nbbbb$c\n", "center", " a b\nbbbb c\n"),
Arguments.of("center-last", "x$a\nx$bbbb\n", "center", "x a\nx bbbb\n"),
Arguments.of("non-ascii", "caf\u00e9$x\nab$y\n", "left", "caf\u00e9 x\nab y\n"),
Arguments.of("outside-the-bmp", "\ud83d\ude00$x\nab$y\n", "left", "\ud83d\ude00 x\nab y\n"),
Arguments.of("spaces-in-field", "a b$c\nd$e\n", "left", "a b c\nd e\n"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void alignsTheColumns(String name, String text, String align, String want) {
assertEquals(want, AlignColumns.align(text, align));
}
@Test
void manyLines() {
StringBuilder text = new StringBuilder();
for (int i = 0; i < 100000; i++) {
text.append(i).append("$x\n");
}
String[] lines = AlignColumns.align(text.toString(), "right").split("\n", -1);
assertEquals(100001, lines.length);
assertEquals(" 0 x", lines[0]);
assertEquals("99999 x", lines[99999]);
}
@Test
void badAlign() {
assertThrows(IllegalArgumentException.class, () -> AlignColumns.align("a$b\n", "justify"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
#include "align_columns.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
enum align { LEFT, RIGHT, CENTER };
// A field is n bytes at s, in the text.
struct field {
const char *s;
size_t n;
size_t width; // the number of code points
};
// Returns the number of code points in the n bytes at s. A UTF-8 byte from
// 0x80 to 0xBF continues a code point, so the code counts the other bytes.
static size_t code_points(const char *s, size_t n) {
size_t count = 0;
for (size_t i = 0; i < n; i++) {
count += ((unsigned char)s[i] & 0xC0) != 0x80;
}
return count;
}
// Adds an item to the array *items with *len items, and makes the array
// larger if it is full. Returns 0, or -1 if there is no memory.
static int push(void **items, size_t *len, size_t *cap, size_t size, const void *item) {
if (*len == *cap) {
size_t bigger = *cap == 0 ? 16 : *cap * 2;
void *p = realloc(*items, bigger * size);
if (p == NULL) {
return -1;
}
*items = p;
*cap = bigger;
}
memcpy((char *)*items + *len * size, item, size);
(*len)++;
return 0;
}
char *align_columns(const char *text, const char *align) {
enum align a;
if (strcmp(align, "left") == 0) {
a = LEFT;
} else if (strcmp(align, "right") == 0) {
a = RIGHT;
} else if (strcmp(align, "center") == 0) {
a = CENTER;
} else {
errno = EINVAL;
return NULL;
}
struct field *fields = NULL; // the fields of all the lines, in order
size_t nfields = 0, fields_cap = 0;
size_t *counts = NULL; // the number of fields in each line
size_t nlines = 0, counts_cap = 0;
size_t *widths = NULL;
size_t columns = 0;
char *out = NULL;
// Split the text into lines and fields.
for (const char *s = text; *s != '\0';) {
const char *lf = strchr(s, '\n');
const char *end = lf != NULL ? lf : s + strlen(s);
size_t count = 0;
// A $ at the end of the line does not start a new field, and an
// empty line has no fields.
for (const char *p = s; p < end; count++) {
const char *dollar = memchr(p, '$', (size_t)(end - p));
const char *stop = dollar != NULL ? dollar : end;
struct field f = {p, (size_t)(stop - p), code_points(p, (size_t)(stop - p))};
if (push((void **)&fields, &nfields, &fields_cap, sizeof f, &f) != 0) {
goto no_memory;
}
p = dollar != NULL ? dollar + 1 : end;
}
if (push((void **)&counts, &nlines, &counts_cap, sizeof count, &count) != 0) {
goto no_memory;
}
if (count > columns) {
columns = count;
}
s = lf != NULL ? lf + 1 : end;
}
// Find the width of each column.
widths = calloc(columns + 1, sizeof *widths);
if (widths == NULL) {
goto no_memory;
}
for (size_t i = 0, k = 0; i < nlines; i++) {
for (size_t j = 0; j < counts[i]; j++, k++) {
if (fields[k].width > widths[j]) {
widths[j] = fields[k].width;
}
}
}
// The first pass finds the size of the result, and the second writes it.
size_t size = 0;
for (int pass = 0; pass < 2; pass++) {
size_t at = 0;
for (size_t i = 0, k = 0; i < nlines; i++) {
for (size_t j = 0; j < counts[i]; j++, k++) {
size_t pad = widths[j] - fields[k].width;
size_t left = a == LEFT ? 0 : a == RIGHT ? pad : pad / 2;
size_t right = j + 1 < counts[i] ? pad - left : 0;
if (pass == 1) {
char *p = out + at;
if (j > 0) {
*p++ = ' ';
}
memset(p, ' ', left);
memcpy(p + left, fields[k].s, fields[k].n);
memset(p + left + fields[k].n, ' ', right);
}
at += (j > 0) + left + fields[k].n + right;
}
if (pass == 1) {
out[at] = '\n';
}
at++;
}
if (pass == 0) {
size = at;
out = malloc(size + 1);
if (out == NULL) {
goto no_memory;
}
}
}
out[size] = '\0';
free(fields);
free(counts);
free(widths);
return out;
no_memory:
free(fields);
free(counts);
free(widths);
errno = ENOMEM;
return NULL;
}
align_columns.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
#ifndef ALIGN_COLUMNS_H
#define ALIGN_COLUMNS_H
// Returns text with its fields in columns, in a new string that the caller
// frees. text is UTF-8. A line ends at LF. Each $ in a line separates two
// fields, and a $ at the end of a line does not start a new field. An empty
// line has no fields. The width of a column is the largest number of code
// points of a field in it. Each field is padded with spaces to the width of
// its column, on the right ("left"), on the left ("right"), or on the two
// sides ("center"), with the odd space on the right. One space separates two
// columns. The padding on the right of the last field of a line is not
// written. Each line of the result ends with LF. Returns NULL with errno set
// to EINVAL if align is not "left", "right" or "center", or to ENOMEM if
// there is no memory.
char *align_columns(const char *text, const char *align);
#endif
test_align_columns.c 102 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
#include "align_columns.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char rosetta[] =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n"
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n"
"column$are$separated$by$at$least$one$space.\n"
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"justified,$right$justified,$or$center$justified$within$its$column.\n"
;
struct test_case {
const char *name, *text, *align, *want;
};
static const struct test_case cases[] = {
{"rosetta-left", rosetta, "left", "Given a text file of many lines, where fields within a line\n"
"are delineated by a single 'dollar' character, write a program\n"
"that aligns each column of fields by ensuring that words in each\n"
"column are separated by at least one space.\n"
"Further, allow for each word in a column to be either left\n"
"justified, right justified, or center justified within its column.\n"},
{"rosetta-right", rosetta, "right", " Given a text file of many lines, where fields within a line\n"
" are delineated by a single 'dollar' character, write a program\n"
" that aligns each column of fields by ensuring that words in each\n"
" column are separated by at least one space.\n"
" Further, allow for each word in a column to be either left\n"
"justified, right justified, or center justified within its column.\n"},
{"rosetta-center", rosetta, "center", " Given a text file of many lines, where fields within a line\n"
" are delineated by a single 'dollar' character, write a program\n"
" that aligns each column of fields by ensuring that words in each\n"
" column are separated by at least one space.\n"
" Further, allow for each word in a column to be either left\n"
"justified, right justified, or center justified within its column.\n"},
{"two-lines", "a$bb$c\ndd$e$fff\n", "left", "a bb c\ndd e fff\n"},
{"empty", "", "left", ""},
{"empty-line", "a$b\n"
"\n"
"ccc$d\n", "left", "a b\n"
"\n"
"ccc d\n"},
{"empty-field", "a$$b\nc$dd$e\n", "left", "a b\nc dd e\n"},
{"trailing-dollar", "a$b$\ncc$d\n", "left", "a b\ncc d\n"},
{"ragged", "a$b$c\nddd\n", "right", " a b c\nddd\n"},
{"one-column", "a\n"
"bbb\n"
"cc\n", "right", " a\n"
"bbb\n"
" cc\n"},
{"no-final-newline", "a$b\ncc$d", "left", "a b\ncc d\n"},
{"center-odd", "a$b\nbbbb$c\n", "center", " a b\nbbbb c\n"},
{"center-last", "x$a\nx$bbbb\n", "center", "x a\nx bbbb\n"},
{"non-ascii", "caf\303\251$x\nab$y\n", "left", "caf\303\251 x\nab y\n"},
{"outside-the-bmp", "\360\237\230\200$x\nab$y\n", "left", "\360\237\230\200 x\nab y\n"},
{"spaces-in-field", "a b$c\nd$e\n", "left", "a b c\nd e\n"},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
char *got = align_columns(c->text, c->align);
if (got == NULL || strcmp(got, c->want) != 0) {
fprintf(stderr, "FAIL %s: got \"%s\"\n", c->name, got != NULL ? got : "(null)");
failures++;
}
free(got);
}
// 100000 lines from 0$x to 99999$x.
char *many = malloc(100000 * 8 + 1);
size_t len = 0;
for (int i = 0; i < 100000; i++) {
len += (size_t)snprintf(many + len, 100000 * 8 + 1 - len, "%d$x\n", i);
}
char *got = align_columns(many, "right");
if (got == NULL || strncmp(got, " 0 x\n", 8) != 0 || strcmp(got + strlen(got) - 8, "99999 x\n") != 0 ||
strlen(got) != 100000 * 8) {
fprintf(stderr, "FAIL many-lines\n");
failures++;
}
free(got);
free(many);
errno = 0;
if (align_columns("a$b\n", "justify") != NULL || errno != EINVAL) {
fprintf(stderr, "FAIL bad-align\n");
failures++;
}
if (failures == 0) {
printf("ok\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
using System.Text;
public static class AlignColumns
{
// Aligns the fields of the text in columns. A $ separates two fields, and
// align is "left", "right" or "center". Throws ArgumentException if align
// is not one of these words.
public static string Align(string text, string align)
{
if (align is not ("left" or "right" or "center"))
{
throw new ArgumentException("align must be left, right or center", nameof(align));
}
var rows = new List<List<string>>();
var widths = new List<int>();
foreach (string line in Split(text, '\n'))
{
List<string> fields = Split(line, '$');
rows.Add(fields);
for (int j = 0; j < fields.Count; j++)
{
int width = Width(fields[j]);
if (j == widths.Count)
{
widths.Add(width);
}
else if (width > widths[j])
{
widths[j] = width;
}
}
}
var output = new StringBuilder();
foreach (List<string> fields in rows)
{
for (int j = 0; j < fields.Count; j++)
{
int pad = widths[j] - Width(fields[j]);
int left = align switch { "left" => 0, "right" => pad, _ => pad / 2 };
if (j > 0)
{
output.Append(' ');
}
output.Append(' ', left).Append(fields[j]);
if (j + 1 < fields.Count)
{
output.Append(' ', pad - left);
}
}
output.Append('\n');
}
return output.ToString();
}
// Returns the number of code points in s. String.Length counts UTF-16
// code units.
private static int Width(string s) => s.EnumerateRunes().Count();
// Splits s at each sep. A sep at the end does not start a new part.
private static List<string> Split(string s, char sep)
{
var parts = new List<string>();
int start = 0;
while (start < s.Length)
{
int at = s.IndexOf(sep, start);
if (at < 0)
{
at = s.Length;
}
parts.Add(s[start..at]);
start = at + 1;
}
return parts;
}
}
AlignColumnsTests.cs 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
using System.Text;
using Xunit;
public sealed class AlignColumnsTests
{
private const string Rosetta =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" +
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" +
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" +
"column$are$separated$by$at$least$one$space.\n" +
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" +
"justified,$right$justified,$or$center$justified$within$its$column.\n";
public static TheoryData<string, string, string, string> Cases => new()
{
{ "rosetta-left", Rosetta, "left", "Given a text file of many lines, where fields within a line\n" +
"are delineated by a single 'dollar' character, write a program\n" +
"that aligns each column of fields by ensuring that words in each\n" +
"column are separated by at least one space.\n" +
"Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n" },
{ "rosetta-right", Rosetta, "right", " Given a text file of many lines, where fields within a line\n" +
" are delineated by a single 'dollar' character, write a program\n" +
" that aligns each column of fields by ensuring that words in each\n" +
" column are separated by at least one space.\n" +
" Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n" },
{ "rosetta-center", Rosetta, "center", " Given a text file of many lines, where fields within a line\n" +
" are delineated by a single 'dollar' character, write a program\n" +
" that aligns each column of fields by ensuring that words in each\n" +
" column are separated by at least one space.\n" +
" Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n" },
{ "two-lines", "a$bb$c\ndd$e$fff\n", "left", "a bb c\ndd e fff\n" },
{ "empty", "", "left", "" },
{ "empty-line", "a$b\n" +
"\n" +
"ccc$d\n", "left", "a b\n" +
"\n" +
"ccc d\n" },
{ "empty-field", "a$$b\nc$dd$e\n", "left", "a b\nc dd e\n" },
{ "trailing-dollar", "a$b$\ncc$d\n", "left", "a b\ncc d\n" },
{ "ragged", "a$b$c\nddd\n", "right", " a b c\nddd\n" },
{ "one-column", "a\n" +
"bbb\n" +
"cc\n", "right", " a\n" +
"bbb\n" +
" cc\n" },
{ "no-final-newline", "a$b\ncc$d", "left", "a b\ncc d\n" },
{ "center-odd", "a$b\nbbbb$c\n", "center", " a b\nbbbb c\n" },
{ "center-last", "x$a\nx$bbbb\n", "center", "x a\nx bbbb\n" },
{ "non-ascii", "caf\u00e9$x\nab$y\n", "left", "caf\u00e9 x\nab y\n" },
{ "outside-the-bmp", "\ud83d\ude00$x\nab$y\n", "left", "\ud83d\ude00 x\nab y\n" },
{ "spaces-in-field", "a b$c\nd$e\n", "left", "a b c\nd e\n" },
};
[Theory]
[MemberData(nameof(Cases))]
public void AlignsTheColumns(string name, string text, string align, string want)
{
Assert.Equal(want, AlignColumns.Align(text, align));
}
[Fact]
public void ManyLines()
{
var text = new StringBuilder();
for (int i = 0; i < 100000; i++)
{
text.Append(i).Append("$x\n");
}
string[] lines = AlignColumns.Align(text.ToString(), "right").Split('\n');
Assert.Equal(100001, lines.Length);
Assert.Equal(" 0 x", lines[0]);
Assert.Equal("99999 x", lines[99999]);
}
[Fact]
public void BadAlign()
{
Assert.Throws<ArgumentException>(() => AlignColumns.Align("a$b\n", "justify"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
const ALIGNS = ["left", "right", "center"];
// Returns text with its fields in columns. A line ends at LF. Each $ in a line
// separates two fields, and a $ at the end of a line does not start a new
// field. An empty line has no fields. The width of a column is the largest
// number of code points of a field in it. Each field is padded with spaces to
// the width of its column, on the right (left), on the left (right), or on the
// two sides (center), with the odd space on the right. One space separates two
// columns. The padding on the right of the last field of a line is not
// written. Each line of the result ends with LF. Throws a RangeError if align
// is not left, right or center.
export function alignColumns(text, align) {
if (!ALIGNS.includes(align)) {
throw new RangeError(`bad align: ${align}`);
}
const lines = text.split("\n");
if (lines.at(-1) === "") {
// A final LF ends the last line. It does not start a new line.
lines.pop();
}
const rows = lines.map(splitFields);
const widths = [];
for (const row of rows) {
row.forEach((field, j) => {
widths[j] = Math.max(widths[j] ?? 0, codePoints(field));
});
}
let out = "";
for (const row of rows) {
const parts = row.map((field, j) => {
const pad = widths[j] - codePoints(field);
const left = align === "left" ? 0 : align === "right" ? pad : Math.floor(pad / 2);
const right = j < row.length - 1 ? pad - left : 0;
return " ".repeat(left) + field + " ".repeat(right);
});
out += parts.join(" ") + "\n";
}
return out;
}
// Returns the fields of a line: none for an empty line.
function splitFields(line) {
if (line === "") {
return [];
}
const fields = line.split("$");
if (line.endsWith("$")) {
fields.pop();
}
return fields;
}
// length counts UTF-16 code units, so a character outside the BMP counts as 2.
// The string iterator gives code points.
function codePoints(s) {
let n = 0;
for (const _ of s) {
n++;
}
return n;
}
alignColumns.test.js 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { test } from "node:test";
import { alignColumns } from "./alignColumns.js";
const node = fileURLToPath(new URL("../../", import.meta.url));
function load(name) {
return readFileSync(join(node, "cases", name), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
}
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
assert.equal(alignColumns(c.args.text, c.args.align), c.expect);
});
}
test("many-lines", () => {
let text = "";
for (let i = 0; i < 100000; i++) {
text += `${i}$x\n`;
}
const lines = alignColumns(text, "right").split("\n");
assert.equal(lines.length, 100001);
assert.equal(lines[0], " 0 x");
assert.equal(lines[99999], "99999 x");
});
for (const c of load("errors.jsonl")) {
test(c.name, () => {
assert.throws(() => alignColumns(c.args.text, c.args.align), RangeError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
export type Align = "left" | "right" | "center";
const ALIGNS: readonly string[] = ["left", "right", "center"];
// Returns text with its fields in columns. A line ends at LF. Each $ in a line
// separates two fields, and a $ at the end of a line does not start a new
// field. An empty line has no fields. The width of a column is the largest
// number of code points of a field in it. Each field is padded with spaces to
// the width of its column, on the right (left), on the left (right), or on the
// two sides (center), with the odd space on the right. One space separates two
// columns. The padding on the right of the last field of a line is not
// written. Each line of the result ends with LF. Throws a RangeError if align
// is not left, right or center.
export function alignColumns(text: string, align: Align): string {
if (!ALIGNS.includes(align)) {
throw new RangeError(`bad align: ${align}`);
}
const lines = text.split("\n");
if (lines.at(-1) === "") {
// A final LF ends the last line. It does not start a new line.
lines.pop();
}
const rows = lines.map(splitFields);
const widths: number[] = [];
for (const row of rows) {
row.forEach((field, j) => {
widths[j] = Math.max(widths[j] ?? 0, codePoints(field));
});
}
let out = "";
for (const row of rows) {
const parts = row.map((field, j) => {
const pad = widths[j] - codePoints(field);
const left = align === "left" ? 0 : align === "right" ? pad : Math.floor(pad / 2);
const right = j < row.length - 1 ? pad - left : 0;
return " ".repeat(left) + field + " ".repeat(right);
});
out += parts.join(" ") + "\n";
}
return out;
}
// Returns the fields of a line: none for an empty line.
function splitFields(line: string): string[] {
if (line === "") {
return [];
}
const fields = line.split("$");
if (line.endsWith("$")) {
fields.pop();
}
return fields;
}
// length counts UTF-16 code units, so a character outside the BMP counts as 2.
// The string iterator gives code points.
function codePoints(s: string): number {
let n = 0;
for (const _ of s) {
n++;
}
return n;
}
alignColumns.test.ts 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { test } from "node:test";
import { type Align, alignColumns } from "./alignColumns.ts";
interface Case {
name: string;
args: { text: string; align: Align };
expect?: string;
error?: string;
}
const node = fileURLToPath(new URL("../../", import.meta.url));
function load(name: string): Case[] {
return readFileSync(join(node, "cases", name), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line) as Case);
}
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
assert.equal(alignColumns(c.args.text, c.args.align), c.expect);
});
}
test("many-lines", () => {
let text = "";
for (let i = 0; i < 100000; i++) {
text += `${i}$x\n`;
}
const lines = alignColumns(text, "right").split("\n");
assert.equal(lines.length, 100001);
assert.equal(lines[0], " 0 x");
assert.equal(lines[99999], "99999 x");
});
for (const c of load("errors.jsonl")) {
test(c.name, () => {
assert.throws(() => alignColumns(c.args.text, c.args.align), RangeError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
// Package aligncolumns aligns the columns of a text in which a $ separates
// the fields.
package aligncolumns
import (
"errors"
"strings"
"unicode/utf8"
)
// ErrBadAlign is the error when align is not left, right or center.
var ErrBadAlign = errors.New("align is not left, right or center")
// AlignColumns returns text with its fields in columns. A line ends at LF.
// Each $ in a line separates two fields, and a $ at the end of a line does not
// start a new field. An empty line has no fields. The width of a column is the
// largest number of code points of a field in it. Each field is padded with
// spaces to the width of its column, on the right (left), on the left
// (right), or on the two sides (center), with the odd space on the right. One
// space separates two columns. The padding on the right of the last field of
// a line is not written. Each line of the result ends with LF.
func AlignColumns(text, align string) (string, error) {
if align != "left" && align != "right" && align != "center" {
return "", ErrBadAlign
}
lines := strings.Split(text, "\n")
if lines[len(lines)-1] == "" {
// A final LF ends the last line. It does not start a new line.
lines = lines[:len(lines)-1]
}
rows := make([][]string, len(lines))
var widths []int
for i, line := range lines {
rows[i] = splitFields(line)
for j, field := range rows[i] {
if j == len(widths) {
widths = append(widths, 0)
}
// len counts bytes. RuneCountInString counts code points.
widths[j] = max(widths[j], utf8.RuneCountInString(field))
}
}
var b strings.Builder
for _, row := range rows {
for j, field := range row {
pad := widths[j] - utf8.RuneCountInString(field)
left := 0
switch align {
case "right":
left = pad
case "center":
left = pad / 2
}
right := pad - left
if j == len(row)-1 {
right = 0
}
if j > 0 {
b.WriteByte(' ')
}
b.WriteString(strings.Repeat(" ", left))
b.WriteString(field)
b.WriteString(strings.Repeat(" ", right))
}
b.WriteByte('\n')
}
return b.String(), nil
}
// splitFields returns the fields of a line: none for an empty line.
func splitFields(line string) []string {
if line == "" {
return nil
}
fields := strings.Split(line, "$")
if strings.HasSuffix(line, "$") {
fields = fields[:len(fields)-1]
}
return fields
}
align_columns_test.go 90 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
package aligncolumns
import (
"errors"
"fmt"
"strings"
"testing"
)
const rosetta = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" +
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" +
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" +
"column$are$separated$by$at$least$one$space.\n" +
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" +
"justified,$right$justified,$or$center$justified$within$its$column.\n"
var cases = []struct{ name, text, align, want string }{
{"rosetta-left", rosetta, "left", "Given a text file of many lines, where fields within a line\n" +
"are delineated by a single 'dollar' character, write a program\n" +
"that aligns each column of fields by ensuring that words in each\n" +
"column are separated by at least one space.\n" +
"Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n"},
{"rosetta-right", rosetta, "right", " Given a text file of many lines, where fields within a line\n" +
" are delineated by a single 'dollar' character, write a program\n" +
" that aligns each column of fields by ensuring that words in each\n" +
" column are separated by at least one space.\n" +
" Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n"},
{"rosetta-center", rosetta, "center", " Given a text file of many lines, where fields within a line\n" +
" are delineated by a single 'dollar' character, write a program\n" +
" that aligns each column of fields by ensuring that words in each\n" +
" column are separated by at least one space.\n" +
" Further, allow for each word in a column to be either left\n" +
"justified, right justified, or center justified within its column.\n"},
{"two-lines", "a$bb$c\ndd$e$fff\n", "left", "a bb c\ndd e fff\n"},
{"empty", "", "left", ""},
{"empty-line", "a$b\n" +
"\n" +
"ccc$d\n", "left", "a b\n" +
"\n" +
"ccc d\n"},
{"empty-field", "a$$b\nc$dd$e\n", "left", "a b\nc dd e\n"},
{"trailing-dollar", "a$b$\ncc$d\n", "left", "a b\ncc d\n"},
{"ragged", "a$b$c\nddd\n", "right", " a b c\nddd\n"},
{"one-column", "a\n" +
"bbb\n" +
"cc\n", "right", " a\n" +
"bbb\n" +
" cc\n"},
{"no-final-newline", "a$b\ncc$d", "left", "a b\ncc d\n"},
{"center-odd", "a$b\nbbbb$c\n", "center", " a b\nbbbb c\n"},
{"center-last", "x$a\nx$bbbb\n", "center", "x a\nx bbbb\n"},
{"non-ascii", "caf\u00e9$x\nab$y\n", "left", "caf\u00e9 x\nab y\n"},
{"outside-the-bmp", "\U0001f600$x\nab$y\n", "left", "\U0001f600 x\nab y\n"},
{"spaces-in-field", "a b$c\nd$e\n", "left", "a b c\nd e\n"},
}
func TestAlignColumns(t *testing.T) {
for _, c := range cases {
got, err := AlignColumns(c.text, c.align)
if err != nil || got != c.want {
t.Errorf("%s: got %q, %v; want %q", c.name, got, err, c.want)
}
}
}
func TestManyLines(t *testing.T) {
var b strings.Builder
for i := range 100000 {
fmt.Fprintf(&b, "%d$x\n", i)
}
got, err := AlignColumns(b.String(), "right")
if err != nil {
t.Fatal(err)
}
lines := strings.Split(got, "\n")
if len(lines) != 100001 || lines[0] != " 0 x" || lines[99999] != "99999 x" {
t.Errorf("got %d lines, %q, %q", len(lines), lines[0], lines[99999])
}
}
func TestBadAlign(t *testing.T) {
if _, err := AlignColumns("a$b\n", "justify"); !errors.Is(err, ErrBadAlign) {
t.Errorf("got %v, want ErrBadAlign", err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
//! Aligns the columns of a text in which a `$` separates the fields.
use std::fmt;
use std::str::FromStr;
/// Where a field goes in its column.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
Left,
Right,
Center,
}
/// The error when a text is not `left`, `right` or `center`.
#[derive(Debug, PartialEq, Eq)]
pub struct BadAlign(pub String);
impl fmt::Display for BadAlign {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "bad align: {:?}", self.0)
}
}
impl std::error::Error for BadAlign {}
impl FromStr for Align {
type Err = BadAlign;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"left" => Ok(Align::Left),
"right" => Ok(Align::Right),
"center" => Ok(Align::Center),
_ => Err(BadAlign(s.to_string())),
}
}
}
/// Returns `text` with its fields in columns. A line ends at LF. Each `$` in a
/// line separates two fields, and a `$` at the end of a line does not start a
/// new field. An empty line has no fields. The width of a column is the
/// largest number of code points of a field in it. Each field is padded with
/// spaces to the width of its column, on the right (`Left`), on the left
/// (`Right`), or on the two sides (`Center`), with the odd space on the
/// right. One space separates two columns. The padding on the right of the
/// last field of a line is not written. Each line of the result ends with LF.
pub fn align_columns(text: &str, align: Align) -> String {
// split_terminator does not give an empty last line after a final LF.
let rows: Vec<Vec<&str>> = text.split_terminator('\n').map(split_fields).collect();
let mut widths: Vec<usize> = Vec::new();
for row in &rows {
for (j, field) in row.iter().enumerate() {
// len() counts bytes. chars().count() counts code points.
let width = field.chars().count();
if j == widths.len() {
widths.push(width);
} else {
widths[j] = widths[j].max(width);
}
}
}
let mut out = String::with_capacity(text.len());
for row in &rows {
for (j, field) in row.iter().enumerate() {
let pad = widths[j] - field.chars().count();
let left = match align {
Align::Left => 0,
Align::Right => pad,
Align::Center => pad / 2,
};
let right = if j + 1 < row.len() { pad - left } else { 0 };
if j > 0 {
out.push(' ');
}
out.extend(std::iter::repeat_n(' ', left));
out.push_str(field);
out.extend(std::iter::repeat_n(' ', right));
}
out.push('\n');
}
out
}
/// Returns the fields of a line: none for an empty line.
fn split_fields(line: &str) -> Vec<&str> {
if line.is_empty() {
return Vec::new();
}
// split_terminator does not give an empty last field after a final $.
line.split_terminator('$').collect()
}
tests/align_columns_test.rs 96 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/align-columns-of-text/.
use algo_align_columns::{align_columns, Align, BadAlign};
const ROSETTA: &str = concat!(
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n",
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n",
"column$are$separated$by$at$least$one$space.\n",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n",
"justified,$right$justified,$or$center$justified$within$its$column.\n",
);
/// Each case is (name, text, align, result).
const CASES: &[(&str, &str, &str, &str)] = &[
("rosetta-left", ROSETTA, "left", concat!(
"Given a text file of many lines, where fields within a line\n",
"are delineated by a single 'dollar' character, write a program\n",
"that aligns each column of fields by ensuring that words in each\n",
"column are separated by at least one space.\n",
"Further, allow for each word in a column to be either left\n",
"justified, right justified, or center justified within its column.\n",
)),
("rosetta-right", ROSETTA, "right", concat!(
" Given a text file of many lines, where fields within a line\n",
" are delineated by a single 'dollar' character, write a program\n",
" that aligns each column of fields by ensuring that words in each\n",
" column are separated by at least one space.\n",
" Further, allow for each word in a column to be either left\n",
"justified, right justified, or center justified within its column.\n",
)),
("rosetta-center", ROSETTA, "center", concat!(
" Given a text file of many lines, where fields within a line\n",
" are delineated by a single 'dollar' character, write a program\n",
" that aligns each column of fields by ensuring that words in each\n",
" column are separated by at least one space.\n",
" Further, allow for each word in a column to be either left\n",
"justified, right justified, or center justified within its column.\n",
)),
("two-lines", "a$bb$c\ndd$e$fff\n", "left", "a bb c\ndd e fff\n"),
("empty", "", "left", ""),
("empty-line", concat!(
"a$b\n",
"\n",
"ccc$d\n",
), "left", concat!(
"a b\n",
"\n",
"ccc d\n",
)),
("empty-field", "a$$b\nc$dd$e\n", "left", "a b\nc dd e\n"),
("trailing-dollar", "a$b$\ncc$d\n", "left", "a b\ncc d\n"),
("ragged", "a$b$c\nddd\n", "right", " a b c\nddd\n"),
("one-column", concat!(
"a\n",
"bbb\n",
"cc\n",
), "right", concat!(
" a\n",
"bbb\n",
" cc\n",
)),
("no-final-newline", "a$b\ncc$d", "left", "a b\ncc d\n"),
("center-odd", "a$b\nbbbb$c\n", "center", " a b\nbbbb c\n"),
("center-last", "x$a\nx$bbbb\n", "center", "x a\nx bbbb\n"),
("non-ascii", "caf\u{e9}$x\nab$y\n", "left", "caf\u{e9} x\nab y\n"),
("outside-the-bmp", "\u{1f600}$x\nab$y\n", "left", "\u{1f600} x\nab y\n"),
("spaces-in-field", "a b$c\nd$e\n", "left", "a b c\nd e\n"),
];
#[test]
fn cases() {
for &(name, text, align, want) in CASES {
let align: Align = align.parse().unwrap();
assert_eq!(align_columns(text, align), want, "{name}");
}
}
#[test]
fn many_lines() {
let text: String = (0..100000).map(|i| format!("{i}$x\n")).collect();
let got = align_columns(&text, Align::Right);
let lines: Vec<&str> = got.split('\n').collect();
assert_eq!(lines.len(), 100001);
assert_eq!(lines[0], " 0 x");
assert_eq!(lines[99999], "99999 x");
}
#[test]
fn bad_align() {
assert_eq!(
"justify".parse::<Align>(),
Err(BadAlign("justify".to_string()))
);
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/align-columns-of-text/.
# Aligns the fields of the text on stdin in columns and writes the result to
# stdout. A $ separates two fields, and $1 is left, right or center.
align_columns() {
local align=$1
case $align in
left | right | center) ;;
*)
echo "align_columns: align must be left, right or center: $align" >&2
return 2
;;
esac
# In the C locale, bash works on bytes, so ${#t} counts bytes and no byte
# of a UTF-8 text is a bad character. A $ byte is always a $ in UTF-8.
local LC_ALL=C
local -a lines=() widths=() fields=()
local line width j n=0 pad left out
# read returns 1 for a last line with no LF, but it sets the line.
while IFS= read -r line || [[ -n $line ]]; do
lines[n++]=$line
done
# In bash 3.2, ${lines[i]} walks the array from the start, but a for loop
# over "${lines[@]}" does not. The + form keeps set -u quiet when there
# are no lines.
for line in ${lines[@]+"${lines[@]}"}; do
_align_columns_split "$line"
for ((j = 0; j < ${#fields[@]}; j++)); do
_align_columns_width "${fields[j]}"
if ((width > ${widths[j]:-0})); then
widths[j]=$width
fi
done
done
for line in ${lines[@]+"${lines[@]}"}; do
_align_columns_split "$line"
out=
for ((j = 0; j < ${#fields[@]}; j++)); do
_align_columns_width "${fields[j]}"
pad=$((${widths[j]:-0} - width))
case $align in
left) left=0 ;;
right) left=$pad ;;
center) left=$((pad / 2)) ;;
esac
((j > 0)) && out+=' '
# printf %*s counts bytes, so it pads an empty string, not the field.
printf -v out '%s%*s%s' "$out" "$left" '' "${fields[j]}"
if ((j + 1 < ${#fields[@]})); then
printf -v out '%s%*s' "$out" "$((pad - left))" ''
fi
done
printf '%s\n' "$out"
done
}
# Puts the fields of $1 in the array fields. A $ at the end does not start a
# new field, and an empty line has no fields.
_align_columns_split() {
local rest=$1
fields=()
while [[ -n $rest ]]; do
if [[ $rest == *'$'* ]]; then
fields+=("${rest%%\$*}")
rest=${rest#*\$}
else
fields+=("$rest")
rest=
fi
done
}
# Puts the number of code points in the UTF-8 text $1 in width. The caller
# sets the C locale, so ${#t} counts bytes. The code first removes each byte
# from 0x80 to 0xBF, which continues a code point.
_align_columns_width() {
local t=${1//[$'\x80'-$'\xbf']/}
width=${#t}
}
test_align_columns.bats 78 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/align-columns-of-text/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/align_columns.sh"
# The first example of the Rosetta Code task, with no final LF.
rosetta='Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'\''dollar'\''$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'
}
check() { # check TEXT ALIGN WANT, with printf %b escapes in TEXT and WANT
# The x keeps a final LF, which $(...) removes.
[ "$(printf '%b' "$1" | align_columns "$2"; printf x)" = "$(printf '%bx' "$3")" ]
}
@test "two-lines" { check 'a$bb$c\ndd$e$fff\n' left 'a bb c\ndd e fff\n'; }
@test "empty" { check '' left ''; }
@test "empty-line" { check 'a$b\n\nccc$d\n' left 'a b\n\nccc d\n'; }
@test "empty-field" { check 'a$$b\nc$dd$e\n' left 'a b\nc dd e\n'; }
@test "trailing-dollar" { check 'a$b$\ncc$d\n' left 'a b\ncc d\n'; }
@test "ragged" { check 'a$b$c\nddd\n' right ' a b c\nddd\n'; }
@test "one-column" { check 'a\nbbb\ncc\n' right ' a\nbbb\n cc\n'; }
@test "no-final-newline" { check 'a$b\ncc$d' left 'a b\ncc d\n'; }
@test "center-odd" { check 'a$b\nbbbb$c\n' center ' a b\nbbbb c\n'; }
@test "center-last" { check 'x$a\nx$bbbb\n' center 'x a\nx bbbb\n'; }
@test "non-ascii" { check 'caf\xc3\xa9$x\nab$y\n' left 'caf\xc3\xa9 x\nab y\n'; }
@test "outside-the-bmp" { check '\xf0\x9f\x98\x80$x\nab$y\n' left '\xf0\x9f\x98\x80 x\nab y\n'; }
@test "spaces-in-field" { check 'a b$c\nd$e\n' left 'a b c\nd e\n'; }
@test "rosetta-left" {
want='Given a text file of many lines, where fields within a line
are delineated by a single '\''dollar'\'' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.'
check "$rosetta\n" left "$want\n"
}
@test "rosetta-right" {
want=' Given a text file of many lines, where fields within a line
are delineated by a single '\''dollar'\'' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.'
check "$rosetta\n" right "$want\n"
}
@test "rosetta-center" {
want=' Given a text file of many lines, where fields within a line
are delineated by a single '\''dollar'\'' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.'
check "$rosetta\n" center "$want\n"
}
@test "many-lines" {
out="$BATS_TEST_TMPDIR/out.txt"
seq 0 99999 | sed 's/$/$x/' | align_columns right >"$out"
[ "$(wc -l <"$out")" -eq 100000 ]
[ "$(head -n 1 "$out")" = " 0 x" ]
[ "$(tail -n 1 "$out")" = "99999 x" ]
}
@test "bad-align" {
run align_columns justify </dev/null
[ "$status" -eq 2 ]
}
References
- Rosetta Code, Align columns (task text, from acmeism/RosettaCodeData), task text
- The Python Standard Library, Built-in Types, Text Sequence Type, str; str.center, str.ljust, str.rjust, str.split
- MDN Web Docs, String length, Description
- MDN Web Docs, String.prototype[Symbol.iterator](), Description
- Java SE 21 API, java.lang.String, length; codePointCount
- .NET API reference, String.Length, Remarks
- .NET API reference, String.EnumerateRunes, Definition
- The Go Programming Language Specification, String types
- Go standard library, package unicode/utf8, RuneCount; RuneCountInString
- The Rust Standard Library, primitive type str, len; chars; split_terminator
- RFC 3629, UTF-8, a transformation format of ISO 10646, 1 Introduction; 3 UTF-8 definition
- GNU Bash Reference Manual, 3.5.3 Shell Parameter Expansion; 5.2 Bash Variables (LC_ALL)
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Locale, 7.2 POSIX Locale
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Character Set, 6.2 Character Encoding
- MDN Web Docs, String.prototype.padEnd(), Parameters
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), fprintf, DESCRIPTION (field width)
- Unicode Standard Annex 11, East Asian Width, 4 Definitions (ED4)
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), wcwidth, DESCRIPTION
- Unicode Standard Annex 29, Unicode Text Segmentation, Summary
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 423MXR Edit this page History Report an error Markdown