Theme Catppuccin
Make yourself at homeCatppuccin

A softer light for long learning sessions.

Appearance

Loading your preference…

Dark palette

Choose a dark palette to try it.

Light uses Latte. Your choices stay in this browser.

Back to your source shelf

Inside the companion

Modern C++ errors

Follow one pixel through validation, std::expected, and a complete-or-unchanged update.

Project files 6

Make failure part of the interface

Typed channel errors, pixel results, and the commit interface.

29 lines pixel.hpp
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <string_view>

namespace pixel {
struct Pixel {
    std::uint8_t red{};
    std::uint8_t green{};
    std::uint8_t blue{};
    bool operator==(const Pixel&) const = default;
};
enum class ChannelError { non_finite, outside_unit_interval };
struct PixelError {
    std::size_t channel;
    ChannelError reason;
};

[[nodiscard]] std::string_view describe(ChannelError error) noexcept;
// An intentionally bounded SDR example using a gamma-2 approximation, not sRGB.
[[nodiscard]] std::expected<std::uint8_t, ChannelError> encode_channel(double linear);
[[nodiscard]] std::expected<Pixel, PixelError> prepare_pixel(std::array<double, 3> linear);
// Intentional in-out operation: replace only after all three channels succeed.
[[nodiscard]] std::expected<void, PixelError> replace_pixel(
    Pixel& current, std::array<double, 3> linear);
}

This is the file included with the course. Copy and download give you its complete source.

Taking your work offline? Download all course companions