blob: 22d9c7af247d0ae84554c9bf4a920334f6333f8a [file] [log] [blame]
// Copyright 2022 Google LLC
//
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
#include <flashupdate/version.hpp>
#include <charconv>
#include <format>
#include <span>
namespace flashupdate
{
namespace version
{
std::string Version::format()
{
return std::format("{}.{}.{}.{}", major, minor, point, subpoint);
}
uint32_t Version::splitVersionChunk(std::string_view& version)
{
if (version.empty())
{
throw std::runtime_error(
std::format("Empty version string, got {}.{}.{}.{} so far.", major,
minor, point, subpoint));
}
auto index = version.find('.');
auto sub = version.substr(0, index);
uint32_t num;
auto [ptr, ec]{std::from_chars(version.begin(), version.end(), num)};
if (ec != std::errc())
{
throw std::runtime_error(
std::format("failed to convert string `{}` to uint32_t: {}", sub,
std::make_error_code(ec).message()));
}
if (ptr != version.begin() + sub.size())
{
throw std::runtime_error(
std::format("converted invalid characters: {}", sub));
}
version = ptr + (index == std::string::npos ? 0 : 1);
return num;
}
Version::Version(std::string_view version) :
major(splitVersionChunk(version)), minor(splitVersionChunk(version)),
point(splitVersionChunk(version)), subpoint(splitVersionChunk(version))
{}
} // namespace version
} // namespace flashupdate