|
| 1 | +/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ |
| 2 | +/* |
| 3 | + * Copyright 2025-Current Couchbase, Inc. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +#include "chrono_utils.hxx" |
| 19 | + |
| 20 | +#include <array> |
| 21 | +#include <chrono> |
| 22 | +#include <stdexcept> |
| 23 | + |
| 24 | +namespace couchbase::core |
| 25 | +{ |
| 26 | +auto |
| 27 | +to_iso8601_utc(std::time_t time_in_seconds, std::int64_t microseconds) -> std::string |
| 28 | +{ |
| 29 | + std::tm tm{}; |
| 30 | +#if defined(_MSC_VER) |
| 31 | + gmtime_s(&tm, &time_in_seconds); |
| 32 | +#else |
| 33 | + gmtime_r(&time_in_seconds, &tm); |
| 34 | +#endif |
| 35 | + |
| 36 | + std::array<char, 100> buffer{}; |
| 37 | + auto rc = std::snprintf(buffer.data(), |
| 38 | + buffer.size(), |
| 39 | + "%04d-%02d-%02dT%02d:%02d:%02d.%06lldZ", |
| 40 | + tm.tm_year + 1900, |
| 41 | + tm.tm_mon + 1, |
| 42 | + tm.tm_mday, |
| 43 | + tm.tm_hour, |
| 44 | + tm.tm_min, |
| 45 | + tm.tm_sec, |
| 46 | + static_cast<long long>(microseconds)); |
| 47 | + auto bytes_written = static_cast<std::size_t>(rc); |
| 48 | + if (rc < 0 || bytes_written >= buffer.size()) { |
| 49 | + throw std::range_error("unable to format date: not enough memory in the buffer"); |
| 50 | + } |
| 51 | + return { buffer.data(), bytes_written }; |
| 52 | +} |
| 53 | + |
| 54 | +auto |
| 55 | +to_iso8601_utc(const std::chrono::system_clock::time_point& time_point) -> std::string |
| 56 | +{ |
| 57 | + const auto duration{ time_point.time_since_epoch() }; |
| 58 | + const auto seconds{ std::chrono::duration_cast<std::chrono::seconds>(duration) }; |
| 59 | + const auto micros{ std::chrono::duration_cast<std::chrono::microseconds>(duration - seconds) }; |
| 60 | + |
| 61 | + return to_iso8601_utc(std::chrono::system_clock::to_time_t(time_point), micros.count()); |
| 62 | +} |
| 63 | +} // namespace couchbase::core |
0 commit comments