libcruft-util/colour.cpp

51 lines
1.6 KiB
C++
Raw Normal View History

2011-09-13 15:14:12 +10:00
/*
2018-08-04 15:14:06 +10:00
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
2011-09-13 15:14:12 +10:00
*
* Copyright 2010-2017 Danny Robson <danny@nerdcruft.net>
2011-09-13 15:14:12 +10:00
*/
#include "colour.hpp"
#include "ascii.hpp"
#include "parse/value.hpp"
2011-09-13 15:14:12 +10:00
2017-05-22 16:20:21 +10:00
///////////////////////////////////////////////////////////////////////////////
static cruft::srgba4f
parse_hex (cruft::view<const char*> &str)
{
if (str.size () != strlen ("#012345"))
throw std::invalid_argument ("expected length of 7");
if (str[0] != '#')
throw std::invalid_argument ("expected leading '#'");
if (!cruft::ascii::is_hex (str[1]) ||
!cruft::ascii::is_hex (str[2]) ||
!cruft::ascii::is_hex (str[3]) ||
!cruft::ascii::is_hex (str[4]) ||
!cruft::ascii::is_hex (str[5]) ||
!cruft::ascii::is_hex (str[6]))
{
throw std::invalid_argument ("expected hex digits");
2015-04-09 21:50:42 +10:00
}
uint8_t r = cruft::ascii::from_hex (str[1]) << 4u | cruft::ascii::from_hex (str[2]);
uint8_t g = cruft::ascii::from_hex (str[3]) << 4u | cruft::ascii::from_hex (str[4]);
uint8_t b = cruft::ascii::from_hex (str[5]) << 4u | cruft::ascii::from_hex (str[6]);
2015-04-09 21:50:42 +10:00
str = str.consume (7u);
return cruft::srgba<4,uint8_t> { r, g, b, 255 }.template cast<float> ();
2015-04-09 21:50:42 +10:00
}
2011-09-13 15:14:12 +10:00
///////////////////////////////////////////////////////////////////////////////
template <>
cruft::srgba4f
cruft::parse::value<cruft::srgba4f> (cruft::view<const char*> &str)
{
return parse_hex (str);
}