Programming Search⌘K

Taskcore

Implement a string form for a type

Also called implement toString, override toString, implement __str__, implement Display, implement String method, print an object, custom string form.

Give a Color type a display form such as

Task

Write a type Color with three channels, red, green and blue, each 0 to 255. Its display form is the hexadecimal notation of the web: a # and two upper-case hexadecimal digits for each channel, so Color(255, 128, 0) shows as #FF8000. Give the type this form through the normal string conversion of the language, so that print(c), "color " + c or format!("{c}") shows #FF8000 with no call to a special method. Where the language has a second form for programmers, also give a debug form that shows the type and the fields, such as Color(r=255, g=128, b=0).

Then use it. The function format_colors(reds, greens, blues) makes the value Color(reds[i], greens[i], blues[i]) for each index and returns the display form of each one. For example, format_colors([255, 10], [128, 11], [0, 12]) is ["#FF8000", "#0A0B0C"]. The lists have 0 to 10,000 items, and the tests also check the forms through the print functions of each language.

Java states the aim of the method: it "returns a string that "textually represents" this object", and the result "should be a concise but informative representation that is easy for a person to read".1

Solutions

Language Display form Debug form Called by
Python __str__ __repr__ print, str, f-strings; repr and lists for the debug form
JavaScript toString() a nodejs.util.inspect.custom method in Node.js String(c), template literals, +
TypeScript as JavaScript as JavaScript as JavaScript
Java override toString() none; one method for both +, String.valueOf, println, List.toString
C# override ToString() none; one method for both interpolation, string.Join, Console.WriteLine
Go a String() string method a GoString() string method %v and %s, Print; %#v for the Go syntax form
Rust impl Display #[derive(Debug)] {}, to_string(); {:?} for the debug form
C a function that fills a buffer a second function the program calls them
C++ operator<< for std::ostream none in the standard std::cout << c, std::ostringstream
  • Python defines both methods. __repr__ should "look like a valid Python expression that could be used to recreate an object with the same value", and __str__ is the informal form.2 The format spec 02X in the f-string pads each channel to two upper-case digits. A list shows its items with repr, so str([c]) is [Color(r=255, g=128, b=0)].
  • Java overrides toString in a record. The record would generate a form from its components, and the override replaces it. The documentation recommends the override for all classes: "It is recommended that all subclasses override this method."1 String.format with the conversion %02X for each channel gives the digits.
  • C# overrides ToString in a sealed record, which also replaces the generated form. Without an override, the default "returns the fully qualified name of the type of the Object".3 The format string {R:X2} gives two upper-case hexadecimal digits.
  • Go gives the type a String method, so the type implements fmt.Stringer. "The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print."4 A GoString method gives the form for %#v; here it is color.New(255, 128, 0), which is valid Go.
  • Rust implements Display and derives Debug. "Implementing this trait for a type will automatically implement the ToString trait for the type, allowing the usage of the .to_string() method."5 Display "is for user-facing output, and so cannot be derived", but the documentation of Debug says: "Generally speaking, you should just derive a Debug implementation."56 The derived form is Color { r: 255, g: 128, b: 0 }.
  • JavaScript and TypeScript override toString, which "is meant to be overridden by derived objects for custom type coercion logic".7 The method pads each channel with padStart(2, "0"). Node.js calls the method whose key is the registered symbol nodejs.util.inspect.custom for console.log and util.inspect, so the class gives the debug form there.
  • C has no methods, so color_format writes the form into a buffer of COLOR_STR_SIZE bytes, which holds 7 characters and the null terminator. For snprintf, "At most bufsz - 1 characters are written", and its return value is "number of bytes that would be written not including the null terminator", so color_debug returns the length of the full text and the caller can see a cut.8
  • C++ defines operator<< for std::ostream, which works with std::cout and std::ostringstream. The class stores the channels as std::uint8_t, which is a character type, so to_string converts each one to unsigned before it formats it.

Alternatives

  • Generated forms. A Java record, a C# record, a Kotlin data class, a Python @dataclass and Rust's #[derive(Debug)] generate a form from the fields. Keep it when the debug form is enough, and override it only for the display form.
  • A format with options. In C#, IFormattable lets the caller choose a form with a format string. The ToString documentation advises it when the string "can be formatted in multiple ways".3 In Go, a type with a Format method implements fmt.Formatter and reads the verb and the flags itself.4
  • A separate method. A method such as toHex() is clear when the type has many forms and none of them is the natural one. The normal conversion then gives the debug form.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: no colors give an empty list.
  • single: one color, #010203.
  • zero: all channels 0 give #000000, not #000.
  • max: all channels 255 give #FFFFFF.
  • padding: the values 10, 11 and 12 need a leading zero each, #0A0B0C. Without the width of two digits, the form is #ABC, which a reader takes as a different color.

Pitfalls

  • A form without padding. hex(10) in Python, (10).toString(16) in JavaScript and %X in C give one digit. Use a width and a fill character, such as {:02X} or %02X, and test a channel below 16.
  • A string form that calls itself. In Go, a String method that formats the receiver with %v or %s calls itself. The fmt documentation warns: "convert the value before recurring".4 The same loop happens in Java when toString uses "" + this.
  • A string form that throws. The print functions call the method at times that the type does not choose, such as in a log line or a debugger. C# says: "Your ToString() override should not throw an exception."3
  • Secrets in the form. A generated form shows every field, including a password or a token. Override it, or leave the field out, before a value goes to a log.
  • uint8_t in a C++ stream. std::cout << c.r with a std::uint8_t field prints a character, not a number. Convert the field to unsigned first.
  • Code that parses the string form. A generated form can change between versions. Of the form that a Java record generates, the documentation says: "The precise format produced by this implicitly provided implementation is subject to change, so the present syntax should not be parsed by applications to recover record component values."9 Use a separate, documented format for data that a program reads.

Code

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

color.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

"""A Color with a display form for users and a debug form for programmers."""


class Color:
    __slots__ = ("_r", "_g", "_b")

    def __init__(self, r: int, g: int, b: int) -> None:
        for v in (r, g, b):
            if not 0 <= v <= 255:
                raise ValueError(f"not a channel value: {v}")
        self._r, self._g, self._b = r, g, b

    def __str__(self) -> str:
        # The display form: print, str() and f-strings call it.
        return f"#{self._r:02X}{self._g:02X}{self._b:02X}"

    def __repr__(self) -> str:
        # The debug form: repr(), the prompt and the items of a list call it.
        return f"Color(r={self._r}, g={self._g}, b={self._b})"


def format_colors(reds: list[int], greens: list[int], blues: list[int]) -> list[str]:
    if not len(reds) == len(greens) == len(blues):
        raise ValueError("the lists must have the same length")
    return [str(Color(r, g, b)) for r, g, b in zip(reds, greens, blues)]
test_color.py 35 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

import pytest

from color import Color, format_colors

CASES = {
    "orange": (([255], [128], [0]), ["#FF8000"]),
    "three": (([255, 0, 0], [0, 255, 0], [0, 0, 255]), ["#FF0000", "#00FF00", "#0000FF"]),
    "mixed": (([18, 171], [52, 205], [86, 239]), ["#123456", "#ABCDEF"]),
    "empty": (([], [], []), []),
    "single": (([1], [2], [3]), ["#010203"]),
    "zero": (([0], [0], [0]), ["#000000"]),
    "max": (([255], [255], [255]), ["#FFFFFF"]),
    "padding": (([10, 0], [11, 15], [12, 16]), ["#0A0B0C", "#000F10"]),
}


@pytest.mark.parametrize("name", CASES)
def test_format_colors(name):
    args, want = CASES[name]
    assert format_colors(*args) == want


def test_forms():
    c = Color(255, 128, 0)
    assert str(c) == "#FF8000" and f"{c}" == "#FF8000"
    assert repr(c) == "Color(r=255, g=128, b=0)"
    assert str([c]) == "[Color(r=255, g=128, b=0)]"


def test_bad_value():
    with pytest.raises(ValueError):
        Color(256, 0, 0)
color.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

#include "color.hpp"

#include <cstdio>
#include <sstream>
#include <stdexcept>

namespace color {

Color::Color(int r, int g, int b) {
    for (int v : {r, g, b}) {
        if (v < 0 || v > 255) {
            throw std::out_of_range("not a channel value: " + std::to_string(v));
        }
    }
    r_ = static_cast<std::uint8_t>(r);
    g_ = static_cast<std::uint8_t>(g);
    b_ = static_cast<std::uint8_t>(b);
}

std::string Color::to_string() const {
    char buf[8];
    // A std::uint8_t is a character type, so convert it to int before it is printed as a number.
    std::snprintf(buf, sizeof buf, "#%02X%02X%02X", static_cast<unsigned>(r_), static_cast<unsigned>(g_),
                  static_cast<unsigned>(b_));
    return buf;
}

std::ostream& operator<<(std::ostream& os, const Color& c) { return os << c.to_string(); }

std::vector<std::string> format_colors(const std::vector<int>& reds, const std::vector<int>& greens,
                                       const std::vector<int>& blues) {
    if (reds.size() != greens.size() || reds.size() != blues.size()) {
        throw std::invalid_argument("the lists must have the same length");
    }
    std::vector<std::string> out;
    out.reserve(reds.size());
    for (std::size_t i = 0; i < reds.size(); i++) {
        std::ostringstream s;
        s << Color(reds[i], greens[i], blues[i]);
        out.push_back(s.str());
    }
    return out;
}

}  // namespace color
color.hpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

#ifndef COLOR_HPP
#define COLOR_HPP

#include <cstdint>
#include <ostream>
#include <string>
#include <vector>

namespace color {

class Color {
  public:
    // Throws std::out_of_range when a value is not 0 to 255.
    Color(int r, int g, int b);

    // The display form, such as "#FF8000".
    std::string to_string() const;

    friend bool operator==(const Color&, const Color&) = default;

  private:
    std::uint8_t r_, g_, b_;
};

// Writes the display form, so that std::cout << c and std::ostringstream work.
std::ostream& operator<<(std::ostream& os, const Color& c);

// Returns the display form of each color; throws std::invalid_argument when the lengths differ.
std::vector<std::string> format_colors(const std::vector<int>& reds, const std::vector<int>& greens,
                                       const std::vector<int>& blues);

}  // namespace color

#endif
test_color.cpp 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

#include "color.hpp"

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>

using color::Color;

static int failures = 0;

static void check(std::string_view name, const std::vector<int>& reds, const std::vector<int>& greens,
                  const std::vector<int>& blues, const std::vector<std::string>& want) {
    if (color::format_colors(reds, greens, blues) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

static void expect(std::string_view name, bool ok) {
    if (!ok) {
        std::cerr << "check " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("orange", {255}, {128}, {0}, {"#FF8000"});
    check("three", {255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {"#FF0000", "#00FF00", "#0000FF"});
    check("mixed", {18, 171}, {52, 205}, {86, 239}, {"#123456", "#ABCDEF"});
    check("empty", {}, {}, {}, {});
    check("single", {1}, {2}, {3}, {"#010203"});
    check("zero", {0}, {0}, {0}, {"#000000"});
    check("max", {255}, {255}, {255}, {"#FFFFFF"});
    check("padding", {10, 0}, {11, 15}, {12, 16}, {"#0A0B0C", "#000F10"});

    Color c(255, 128, 0);
    expect("to_string", c.to_string() == "#FF8000");
    std::ostringstream s;
    s << "color " << c << ' ' << 42;
    expect("stream", s.str() == "color #FF8000 42");
    bool threw = false;
    try {
        [[maybe_unused]] Color bad(256, 0, 0);
    } catch (const std::out_of_range&) {
        threw = true;
    }
    expect("bad value", threw);

    if (failures == 0) {
        std::cout << "all tests passed\n";
    }
    return failures == 0 ? 0 : 1;
}
Color.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

import java.util.ArrayList;
import java.util.List;

/** A color whose string form is the hexadecimal notation, such as #FF8000. */
public record Color(int r, int g, int b) {
  public Color {
    for (int v : new int[] {r, g, b}) {
      if (v < 0 || v > 255) {
        throw new IllegalArgumentException("not a channel value: " + v);
      }
    }
  }

  /** The display form. String concatenation, String.valueOf and println call it. */
  @Override
  public String toString() {
    return String.format("#%02X%02X%02X", r, g, b);
  }

  public static List<String> formatColors(List<Integer> reds, List<Integer> greens, List<Integer> blues) {
    if (reds.size() != greens.size() || reds.size() != blues.size()) {
      throw new IllegalArgumentException("the lists must have the same length");
    }
    List<String> out = new ArrayList<>(reds.size());
    for (int i = 0; i < reds.size(); i++) {
      out.add(String.valueOf(new Color(reds.get(i), greens.get(i), blues.get(i))));
    }
    return out;
  }
}
ColorTest.java 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

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

import java.util.List;
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 ColorTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("orange", List.of(255), List.of(128), List.of(0), List.of("#FF8000")),
        Arguments.of(
            "three",
            List.of(255, 0, 0),
            List.of(0, 255, 0),
            List.of(0, 0, 255),
            List.of("#FF0000", "#00FF00", "#0000FF")),
        Arguments.of("mixed", List.of(18, 171), List.of(52, 205), List.of(86, 239), List.of("#123456", "#ABCDEF")),
        Arguments.of("empty", List.of(), List.of(), List.of(), List.of()),
        Arguments.of("single", List.of(1), List.of(2), List.of(3), List.of("#010203")),
        Arguments.of("zero", List.of(0), List.of(0), List.of(0), List.of("#000000")),
        Arguments.of("max", List.of(255), List.of(255), List.of(255), List.of("#FFFFFF")),
        Arguments.of("padding", List.of(10, 0), List.of(11, 15), List.of(12, 16), List.of("#0A0B0C", "#000F10")));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void formatColors(String name, List<Integer> reds, List<Integer> greens, List<Integer> blues, List<String> want) {
    assertEquals(want, Color.formatColors(reds, greens, blues), name);
  }

  @Test
  void forms() {
    Color c = new Color(255, 128, 0);
    assertEquals("#FF8000", c.toString());
    assertEquals("color #FF8000", "color " + c);
    assertEquals("[#FF8000]", List.of(c).toString());
  }

  @Test
  void badValue() {
    assertThrows(IllegalArgumentException.class, () -> new Color(256, 0, 0));
  }
}
color.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

#include "color.h"

#include <stdio.h>

bool color_make(int r, int g, int b, Color *out) {
    if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
        return false;
    }
    *out = (Color){(unsigned char)r, (unsigned char)g, (unsigned char)b};
    return true;
}

char *color_format(Color c, char buf[COLOR_STR_SIZE]) {
    snprintf(buf, COLOR_STR_SIZE, "#%02X%02X%02X", c.r, c.g, c.b);
    return buf;
}

int color_debug(Color c, char *buf, size_t size) {
    return snprintf(buf, size, "Color(r=%d, g=%d, b=%d)", c.r, c.g, c.b);
}

int format_colors(const int *reds, const int *greens, const int *blues, size_t n, char (*out)[COLOR_STR_SIZE]) {
    for (size_t i = 0; i < n; i++) {
        Color c;
        if (!color_make(reds[i], greens[i], blues[i], &c)) {
            return -1;
        }
        color_format(c, out[i]);
    }
    return 0;
}
color.h 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

#ifndef COLOR_H
#define COLOR_H

#include <stdbool.h>
#include <stddef.h>

// The display form "#RRGGBB" has 7 characters and a null terminator.
#define COLOR_STR_SIZE 8

typedef struct {
    unsigned char r, g, b;
} Color;

// color_make sets *out and returns true when each value is 0 to 255.
bool color_make(int r, int g, int b, Color *out);

// color_format writes the display form of c into buf and returns buf.
char *color_format(Color c, char buf[COLOR_STR_SIZE]);

// color_debug writes the debug form "Color(r=255, g=128, b=0)" into buf, which has size bytes.
// It returns the length of the full text, as snprintf does; a value of size or more means the text was cut.
int color_debug(Color c, char *buf, size_t size);

// format_colors writes the display form of each color into out[i]. It returns 0, or -1 when a value is out of range.
int format_colors(const int *reds, const int *greens, const int *blues, size_t n, char (*out)[COLOR_STR_SIZE]);

#endif
test_color.c 60 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

#include "color.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, const int *reds, const int *greens, const int *blues, size_t n,
                  const char *const *want) {
    char out[4][COLOR_STR_SIZE];
    if (format_colors(reds, greens, blues, n, out) != 0) {
        fprintf(stderr, "case %s failed: error\n", name);
        failures++;
        return;
    }
    for (size_t i = 0; i < n; i++) {
        if (strcmp(out[i], want[i]) != 0) {
            fprintf(stderr, "case %s failed at %zu: got %s, want %s\n", name, i, out[i], want[i]);
            failures++;
            return;
        }
    }
}

static void expect(const char *name, bool ok) {
    if (!ok) {
        fprintf(stderr, "check %s failed\n", name);
        failures++;
    }
}

int main(void) {
    check("orange", (int[]){255}, (int[]){128}, (int[]){0}, 1, (const char *[]){"#FF8000"});
    check("three", (int[]){255, 0, 0}, (int[]){0, 255, 0}, (int[]){0, 0, 255}, 3,
          (const char *[]){"#FF0000", "#00FF00", "#0000FF"});
    check("mixed", (int[]){18, 171}, (int[]){52, 205}, (int[]){86, 239}, 2, (const char *[]){"#123456", "#ABCDEF"});
    check("empty", NULL, NULL, NULL, 0, NULL);
    check("single", (int[]){1}, (int[]){2}, (int[]){3}, 1, (const char *[]){"#010203"});
    check("zero", (int[]){0}, (int[]){0}, (int[]){0}, 1, (const char *[]){"#000000"});
    check("max", (int[]){255}, (int[]){255}, (int[]){255}, 1, (const char *[]){"#FFFFFF"});
    check("padding", (int[]){10, 0}, (int[]){11, 15}, (int[]){12, 16}, 2, (const char *[]){"#0A0B0C", "#000F10"});

    Color c;
    expect("make", color_make(255, 128, 0, &c));
    expect("bad value", !color_make(256, 0, 0, &c));
    char buf[COLOR_STR_SIZE];
    expect("display", strcmp(color_format(c, buf), "#FF8000") == 0);
    char debug[64];
    expect("debug", color_debug(c, debug, sizeof debug) == 24 && strcmp(debug, "Color(r=255, g=128, b=0)") == 0);
    char small[10];
    expect("debug cut", color_debug(c, small, sizeof small) == 24 && strcmp(small, "Color(r=2") == 0);

    if (failures == 0) {
        printf("all tests passed\n");
    }
    return failures == 0 ? 0 : 1;
}
Color.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

using System;
using System.Collections.Generic;

/// <summary>A color whose string form is the hexadecimal notation, such as #FF8000.</summary>
public sealed record Color
{
    public int R { get; }
    public int G { get; }
    public int B { get; }

    public Color(int r, int g, int b)
    {
        foreach (var v in new[] { r, g, b })
        {
            if (v < 0 || v > 255)
            {
                throw new ArgumentOutOfRangeException(nameof(r), v, "not a channel value");
            }
        }
        (R, G, B) = (r, g, b);
    }

    // The display form. Interpolation, string.Join and Console.WriteLine call it.
    // A record generates ToString from its properties; this override replaces it.
    public override string ToString() => $"#{R:X2}{G:X2}{B:X2}";

    public static List<string> FormatColors(IReadOnlyList<int> reds, IReadOnlyList<int> greens, IReadOnlyList<int> blues)
    {
        if (reds.Count != greens.Count || reds.Count != blues.Count)
        {
            throw new ArgumentException("the lists must have the same length");
        }
        var output = new List<string>(reds.Count);
        for (var i = 0; i < reds.Count; i++)
        {
            output.Add($"{new Color(reds[i], greens[i], blues[i])}");
        }
        return output;
    }
}
ColorTests.cs 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

using System;
using Xunit;

public sealed class ColorTests
{
    public static TheoryData<string, int[], int[], int[], string[]> Cases => new()
    {
        { "orange", new[] { 255 }, new[] { 128 }, new[] { 0 }, new[] { "#FF8000" } },
        { "three", new[] { 255, 0, 0 }, new[] { 0, 255, 0 }, new[] { 0, 0, 255 }, new[] { "#FF0000", "#00FF00", "#0000FF" } },
        { "mixed", new[] { 18, 171 }, new[] { 52, 205 }, new[] { 86, 239 }, new[] { "#123456", "#ABCDEF" } },
        { "empty", new int[] { }, new int[] { }, new int[] { }, new string[] { } },
        { "single", new[] { 1 }, new[] { 2 }, new[] { 3 }, new[] { "#010203" } },
        { "zero", new[] { 0 }, new[] { 0 }, new[] { 0 }, new[] { "#000000" } },
        { "max", new[] { 255 }, new[] { 255 }, new[] { 255 }, new[] { "#FFFFFF" } },
        { "padding", new[] { 10, 0 }, new[] { 11, 15 }, new[] { 12, 16 }, new[] { "#0A0B0C", "#000F10" } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void FormatColors(string name, int[] reds, int[] greens, int[] blues, string[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Color.FormatColors(reds, greens, blues));
    }

    [Fact]
    public void Forms()
    {
        var c = new Color(255, 128, 0);
        Assert.Equal("#FF8000", c.ToString());
        Assert.Equal("color #FF8000", $"color {c}");
        Assert.Equal("#FF8000, #000000", string.Join(", ", c, new Color(0, 0, 0)));
    }

    [Fact]
    public void BadValue()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => new Color(256, 0, 0));
    }
}
color.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

const inspect = Symbol.for("nodejs.util.inspect.custom");

const hex = (v) => v.toString(16).toUpperCase().padStart(2, "0");

export class Color {
  #r;
  #g;
  #b;

  constructor(r, g, b) {
    for (const v of [r, g, b]) {
      if (!Number.isInteger(v) || v < 0 || v > 255) {
        throw new RangeError(`not a channel value: ${v}`);
      }
    }
    this.#r = r;
    this.#g = g;
    this.#b = b;
  }

  // The display form: String(c), template literals and + call it.
  toString() {
    return `#${hex(this.#r)}${hex(this.#g)}${hex(this.#b)}`;
  }

  // The debug form for console.log and util.inspect in Node.js.
  [inspect]() {
    return `Color(r=${this.#r}, g=${this.#g}, b=${this.#b})`;
  }
}

export function formatColors(reds, greens, blues) {
  if (reds.length !== greens.length || reds.length !== blues.length) {
    throw new RangeError("the lists must have the same length");
  }
  return reds.map((r, i) => `${new Color(r, greens[i], blues[i])}`);
}
color.test.js 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

import assert from "node:assert/strict";
import { test } from "node:test";
import { inspect } from "node:util";

import { Color, formatColors } from "./color.js";

const cases = [
  ["orange", [[255], [128], [0]], ["#FF8000"]],
  ["three", [[255, 0, 0], [0, 255, 0], [0, 0, 255]], ["#FF0000", "#00FF00", "#0000FF"]],
  ["mixed", [[18, 171], [52, 205], [86, 239]], ["#123456", "#ABCDEF"]],
  ["empty", [[], [], []], []],
  ["single", [[1], [2], [3]], ["#010203"]],
  ["zero", [[0], [0], [0]], ["#000000"]],
  ["max", [[255], [255], [255]], ["#FFFFFF"]],
  ["padding", [[10, 0], [11, 15], [12, 16]], ["#0A0B0C", "#000F10"]],
];

for (const [name, args, want] of cases) {
  test(name, () => {
    assert.deepEqual(formatColors(...args), want);
  });
}

test("forms", () => {
  const c = new Color(255, 128, 0);
  assert.equal(String(c), "#FF8000");
  assert.equal(`${c}`, "#FF8000");
  assert.equal("color " + c, "color #FF8000");
  assert.equal(inspect(c), "Color(r=255, g=128, b=0)");
});

test("bad value", () => {
  assert.throws(() => new Color(256, 0, 0), RangeError);
});
color.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

const inspect = Symbol.for("nodejs.util.inspect.custom");

const hex = (v: number): string => v.toString(16).toUpperCase().padStart(2, "0");

export class Color {
  readonly #r: number;
  readonly #g: number;
  readonly #b: number;

  constructor(r: number, g: number, b: number) {
    for (const v of [r, g, b]) {
      if (!Number.isInteger(v) || v < 0 || v > 255) {
        throw new RangeError(`not a channel value: ${v}`);
      }
    }
    this.#r = r;
    this.#g = g;
    this.#b = b;
  }

  // The display form: String(c), template literals and + call it.
  toString(): string {
    return `#${hex(this.#r)}${hex(this.#g)}${hex(this.#b)}`;
  }

  // The debug form for console.log and util.inspect in Node.js.
  [inspect](): string {
    return `Color(r=${this.#r}, g=${this.#g}, b=${this.#b})`;
  }
}

export function formatColors(reds: number[], greens: number[], blues: number[]): string[] {
  if (reds.length !== greens.length || reds.length !== blues.length) {
    throw new RangeError("the lists must have the same length");
  }
  return reds.map((r, i) => `${new Color(r, greens[i], blues[i])}`);
}
color.test.ts 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

import assert from "node:assert/strict";
import { test } from "node:test";
import { inspect } from "node:util";

import { Color, formatColors } from "./color.ts";

const cases: [string, [number[], number[], number[]], string[]][] = [
  ["orange", [[255], [128], [0]], ["#FF8000"]],
  ["three", [[255, 0, 0], [0, 255, 0], [0, 0, 255]], ["#FF0000", "#00FF00", "#0000FF"]],
  ["mixed", [[18, 171], [52, 205], [86, 239]], ["#123456", "#ABCDEF"]],
  ["empty", [[], [], []], []],
  ["single", [[1], [2], [3]], ["#010203"]],
  ["zero", [[0], [0], [0]], ["#000000"]],
  ["max", [[255], [255], [255]], ["#FFFFFF"]],
  ["padding", [[10, 0], [11, 15], [12, 16]], ["#0A0B0C", "#000F10"]],
];

for (const [name, args, want] of cases) {
  test(name, () => {
    assert.deepEqual(formatColors(args[0], args[1], args[2]), want);
  });
}

test("forms", () => {
  const c = new Color(255, 128, 0);
  assert.equal(String(c), "#FF8000");
  assert.equal(`${c}`, "#FF8000");
  assert.equal("color " + c, "color #FF8000");
  assert.equal(inspect(c), "Color(r=255, g=128, b=0)");
});

test("bad value", () => {
  assert.throws(() => new Color(256, 0, 0), RangeError);
});
color.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

// Package color gives a Color type with a display form and a Go syntax form.
package color

import "fmt"

// Color is a color with three channels of 0 to 255.
type Color struct {
	r, g, b uint8
}

// New makes a Color, or returns an error when a value is out of range.
func New(r, g, b int) (Color, error) {
	for _, v := range []int{r, g, b} {
		if v < 0 || v > 255 {
			return Color{}, fmt.Errorf("not a channel value: %d", v)
		}
	}
	return Color{uint8(r), uint8(g), uint8(b)}, nil
}

// String is the display form. fmt calls it for %v and %s and in Print and Println.
func (c Color) String() string {
	return fmt.Sprintf("#%02X%02X%02X", c.r, c.g, c.b)
}

// GoString is the Go syntax form. fmt calls it for %#v.
func (c Color) GoString() string {
	return fmt.Sprintf("color.New(%d, %d, %d)", c.r, c.g, c.b)
}

// FormatColors returns the display form of each color.
func FormatColors(reds, greens, blues []int) ([]string, error) {
	if len(reds) != len(greens) || len(reds) != len(blues) {
		return nil, fmt.Errorf("the lists must have the same length")
	}
	out := make([]string, 0, len(reds))
	for i := range reds {
		c, err := New(reds[i], greens[i], blues[i])
		if err != nil {
			return nil, err
		}
		out = append(out, fmt.Sprint(c))
	}
	return out, nil
}
color_test.go 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

package color

import (
	"fmt"
	"slices"
	"testing"
)

var cases = []struct {
	name                string
	reds, greens, blues []int
	want                []string
}{
	{"orange", []int{255}, []int{128}, []int{0}, []string{"#FF8000"}},
	{"three", []int{255, 0, 0}, []int{0, 255, 0}, []int{0, 0, 255}, []string{"#FF0000", "#00FF00", "#0000FF"}},
	{"mixed", []int{18, 171}, []int{52, 205}, []int{86, 239}, []string{"#123456", "#ABCDEF"}},
	{"empty", []int{}, []int{}, []int{}, []string{}},
	{"single", []int{1}, []int{2}, []int{3}, []string{"#010203"}},
	{"zero", []int{0}, []int{0}, []int{0}, []string{"#000000"}},
	{"max", []int{255}, []int{255}, []int{255}, []string{"#FFFFFF"}},
	{"padding", []int{10, 0}, []int{11, 15}, []int{12, 16}, []string{"#0A0B0C", "#000F10"}},
}

func TestFormatColors(t *testing.T) {
	for _, c := range cases {
		got, err := FormatColors(c.reds, c.greens, c.blues)
		if err != nil || !slices.Equal(got, c.want) {
			t.Errorf("case %s: got %v, %v; want %v", c.name, got, err, c.want)
		}
	}
}

func TestForms(t *testing.T) {
	c, err := New(255, 128, 0)
	if err != nil {
		t.Fatal(err)
	}
	checks := []struct{ got, want string }{
		{fmt.Sprint(c), "#FF8000"},
		{fmt.Sprintf("%v and %s", c, c), "#FF8000 and #FF8000"},
		{fmt.Sprint([]Color{c, {}}), "[#FF8000 #000000]"},
		{fmt.Sprintf("%#v", c), "color.New(255, 128, 0)"},
	}
	for _, ch := range checks {
		if ch.got != ch.want {
			t.Errorf("got %q, want %q", ch.got, ch.want)
		}
	}
}

func TestBadValue(t *testing.T) {
	if _, err := New(256, 0, 0); err == nil {
		t.Error("New(256, 0, 0) gave no error")
	}
}
color.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

//! A color with a display form (`Display`) and a debug form (`Debug`).

use std::fmt;

/// A color with three channels of 0 to 255. `Debug` is derived.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Color {
    r: u8,
    g: u8,
    b: u8,
}

impl Color {
    pub fn new(r: u8, g: u8, b: u8) -> Self {
        Color { r, g, b }
    }
}

/// The display form. `{}`, `format!`, `println!` and `to_string` use it.
impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{:02X}{:02X}{:02X}", self.r, self.g, self.b)
    }
}

/// Returns the display form of each color, or None when the slices differ in length.
pub fn format_colors(reds: &[u8], greens: &[u8], blues: &[u8]) -> Option<Vec<String>> {
    if reds.len() != greens.len() || reds.len() != blues.len() {
        return None;
    }
    Some(
        (0..reds.len())
            .map(|i| Color::new(reds[i], greens[i], blues[i]).to_string())
            .collect(),
    )
}
tests/color_test.rs 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-a-string-form-for-a-type/.

use algo_implement_a_string_form_for_a_type::{format_colors, Color};

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<u8>, Vec<u8>, Vec<u8>, Vec<&str>)> = vec![
        ("orange", vec![255], vec![128], vec![0], vec!["#FF8000"]),
        (
            "three",
            vec![255, 0, 0],
            vec![0, 255, 0],
            vec![0, 0, 255],
            vec!["#FF0000", "#00FF00", "#0000FF"],
        ),
        ("mixed", vec![18, 171], vec![52, 205], vec![86, 239], vec!["#123456", "#ABCDEF"]),
        ("empty", vec![], vec![], vec![], vec![]),
        ("single", vec![1], vec![2], vec![3], vec!["#010203"]),
        ("zero", vec![0], vec![0], vec![0], vec!["#000000"]),
        ("max", vec![255], vec![255], vec![255], vec!["#FFFFFF"]),
        ("padding", vec![10, 0], vec![11, 15], vec![12, 16], vec!["#0A0B0C", "#000F10"]),
    ];
    for (name, reds, greens, blues, want) in cases {
        let want: Vec<String> = want.iter().map(|s| s.to_string()).collect();
        assert_eq!(format_colors(&reds, &greens, &blues), Some(want), "case {name}");
    }
}

#[test]
fn forms() {
    let c = Color::new(255, 128, 0);
    assert_eq!(format!("{c}"), "#FF8000");
    assert_eq!(c.to_string(), "#FF8000");
    assert_eq!(format!("{c:?}"), "Color { r: 255, g: 128, b: 0 }");
    assert_eq!(format!("{:?}", vec![c]), "[Color { r: 255, g: 128, b: 0 }]");
}

#[test]
fn lengths_differ() {
    assert_eq!(format_colors(&[1], &[], &[]), None);
}

References

  1. Object (Java SE 21 & JDK 21), API documentation, toString
  2. Data model, The Python Language Reference, 3.3.1 Basic customization, object.__repr__ and object.__str__
  3. Object.ToString Method, .NET API reference, Remarks
  4. fmt package, Go standard library, type Stringer; type GoStringer
  5. Display trait, Rust standard library, Description
  6. Debug trait, Rust standard library, Description
  7. Object.prototype.toString(), JavaScript reference, MDN, Description
  8. printf, fprintf, sprintf, snprintf, cppreference.com, Parameters; Return value
  9. Record (Java SE 21 & JDK 21), API documentation, toString

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 (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