libcruft-util/colour.cpp

58 lines
1.8 KiB
C++
Raw Normal View History

2011-09-13 15:14:12 +10:00
/*
2015-04-13 18:05:28 +10:00
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
2011-09-13 15:14:12 +10:00
*
2015-04-13 18:05:28 +10:00
* http://www.apache.org/licenses/LICENSE-2.0
2011-09-13 15:14:12 +10:00
*
2015-04-13 18:05:28 +10:00
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
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.hpp"
2011-09-13 15:14:12 +10:00
2017-05-22 16:20:21 +10:00
///////////////////////////////////////////////////////////////////////////////
static util::srgba4f
parse_hex (util::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 (!util::ascii::is_hex (str[1]) ||
!util::ascii::is_hex (str[2]) ||
!util::ascii::is_hex (str[3]) ||
!util::ascii::is_hex (str[4]) ||
!util::ascii::is_hex (str[5]) ||
!util::ascii::is_hex (str[6]))
{
throw std::invalid_argument ("expected hex digits");
2015-04-09 21:50:42 +10:00
}
uint8_t r = util::ascii::from_hex (str[1]) << 4u | util::ascii::from_hex (str[2]);
uint8_t g = util::ascii::from_hex (str[3]) << 4u | util::ascii::from_hex (str[4]);
uint8_t b = util::ascii::from_hex (str[5]) << 4u | util::ascii::from_hex (str[6]);
2015-04-09 21:50:42 +10:00
return util::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 <>
util::srgba4f
util::parse<util::srgba4f> (util::view<const char*> str)
{
return parse_hex (str);
}