description Using std::byte to write a color class

Why?

Because I can. No, really, there is no other explanation. I was reading up on Cxx17 and found out about std::byte, so I decided to find a use for it. This is the result. Remove the SDL_Color operator if you don’t want to use SDL.

Usage


// Quite simple:
Color col("#12345678");

/**********************************************************************************
* __          ___              _  _____      _    _____
* \ \        / (_)            | |/ ____|    | |  / ____|
*  \ \  /\  / / _ _ __ ___  __| | |     __ _| |_| |  __  __ _ _ __ ___   ___  ___
*   \ \/  \/ / | | '__/ _ \/ _` | |    / _` | __| | |_ |/ _` | '_ ` _ \ / _ \/ __|
*    \  /\  /  | | | |  __/ (_| | |___| (_| | |_| |__| | (_| | | | | | |  __/\__ \
*     \/  \/   |_|_|  \___|\__,_|\_____\__,_|\__|\_____|\__,_|_| |_| |_|\___||___/
* --------------------------------------------------------------------------------
* _author  : Domenico Gentner
* _mail    : code@tuxstash.de
* _license : This file has been placed in the Public Domain (CC0)
***********************************************************************************/
#pragma once


//-------------------------------------------------------------
struct Color
//-------------------------------------------------------------
{
	Color()
		: r{0x00}, b{0x00}, g{0x00}, a{0x00}
	{
	}

	Color(const std::string& col)
	{
		set(col);
	}

	void set(const std::string& col)
	{
		if (col.length() < 9) {
			LOG_ERROR("String too short");
			return;
		}
		color = col;
		r = std::byte(std::stoi(col.substr(1, 2), nullptr, 16));
		g = std::byte(std::stoi(col.substr(3, 2), nullptr, 16));
		b = std::byte(std::stoi(col.substr(5, 2), nullptr, 16));
		a = std::byte(std::stoi(col.substr(7, 2), nullptr, 16));
	}

	Uint8 red()
	{
		return std::to_integer<Uint8>(r);
	}

	Uint8 green()
	{
		return std::to_integer<Uint8>(g);
	}

	Uint8 blue()
	{
		return std::to_integer<Uint8>(b);
	}

	Uint8 alpha()
	{
		return std::to_integer<Uint8>(a);
	}

	operator std::string()
	{
		return color;
	}

	std::string& operator=(const std::string& s)
	{
		this->color = s;
		set(color);
		return this->color;
	}

	operator SDL_Color()
	{
		SDL_Color col = { red(), green(), blue(), alpha() };
		return col;
	}

	std::byte r;
	std::byte g;
	std::byte b;
	std::byte a;
	std::string color;
};

tweet gist  •  August 22 2019