RcppCCTZ/ 0000755 0001762 0000144 00000000000 14726464450 011656 5 ustar ligges users RcppCCTZ/tests/ 0000755 0001762 0000144 00000000000 13521272406 013006 5 ustar ligges users RcppCCTZ/tests/tinytest.R 0000644 0001762 0000144 00000002125 13521272406 015014 0 ustar ligges users
# RcppCCTZ: Rcpp-based R bindings for CCTZ
#
# Copyright (C) 2019 Dirk Eddelbuettel
#
# This file is part of RcppCCTZ.
#
# RcppCCTZ is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of the
# License, or (at your option) any later version.
#
# RcppCCTZ is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with RcppCCTZ. If not, see .
if (requireNamespace("tinytest", quietly=TRUE)) {
## Set a seed to make the test deterministic
set.seed(42)
## there are several more granular ways to test files in a
## tinytest directory, see its package vignette; tests can also
## run once the package is installed using the same command
tinytest::test_package("RcppCCTZ")
}
RcppCCTZ/MD5 0000644 0001762 0000144 00000005152 14726464450 012171 0 ustar ligges users 61d3850e035c04669a8205b8a7b7de15 *ChangeLog
7e2d76d95050343cb08c59ce62846aa2 *DESCRIPTION
bdfe89628809034bb2aa6fafe2592d04 *NAMESPACE
ec6e931dfb406121352ecc96621e7f99 *R/RcppExports.R
d94d737785e7fdd2a6b0f60136b2d25d *R/init.R
53b99a6e02c193f8991c5acf43e0a555 *README.md
89936c36d9e3e87ade958c90bb42c0b7 *cleanup
a57b7b5c2a241a9ee61fc2393db4c2dd *inst/NEWS.Rd
2a1204292bf9baf598eaaf57041cf0cd *inst/include/RcppCCTZ_API.h
2c98ed80d8423e7c4a780a516a726765 *inst/include/RcppCCTZ_types.h
70cef418e3061411c75ffc0e29b44862 *inst/include/cctz/civil_time.h
47439f0b52cafc3be42e3c0ced78b415 *inst/include/cctz/civil_time_detail.h
3dd0d7916d951a093f524dfdba965b14 *inst/include/cctz/time_zone.h
407daaafb5b7e177d79f4e5a876de84a *inst/include/cctz/zone_info_source.h
455a20d2c32291dc8bc47dd3e21fe8c4 *inst/tinytest/test_format.R
97109413c7a0454e4fb1d8bc8aee4558 *inst/tinytest/test_parse.R
c550b4a54536330c6dc3a24d44aa58f7 *inst/tinytest/test_tz.R
e03aeb8e69c258a12b1f95a2db50d675 *man/RcppCCTZ-package.Rd
a848f8f29d54ef1531a1185c47d76838 *man/formatDatetime.Rd
98e74e616dd35f53631fea9ee74a0e39 *man/parseDatetime.Rd
a9c53e2ba5af3d54ac5ab64354817ce7 *man/toTz.Rd
22bcff7a2c3dc34dc747b17d67dfae63 *man/tzDiff.Rd
e4e12213cf62b2315fbaaed4c2c1c5cc *src/Makevars
13af8e362f1e392c08e22d0bd9f93b08 *src/Makevars.ucrt
e4e12213cf62b2315fbaaed4c2c1c5cc *src/Makevars.win
cb3a0102a75ec491e4e2e579d07a2590 *src/RcppExports.cpp
d0bc8bdbc1efe3b52812f915854b0d97 *src/RcppExports_snippet.h
8e48937ed5ce673434f4679db99d99a6 *src/civil_time_detail.cc
6cb528d1aac2b05edfbecb0b824a43ec *src/examples.cpp
2e379d00fe16be1165130445d7d4cdc9 *src/get_time.h
cdc9f7fcb5152c4b41906c969b28eae9 *src/time_tool.cc
19a5f0db02339633b061cd24b3cc2281 *src/time_zone_fixed.cc
a71187d54c274cc9bfbb48d44cc89195 *src/time_zone_fixed.h
fc6f636d19521e12fe56e8f97e5452a2 *src/time_zone_format.cc
1b9d6bc859ad8d8ccb9e258a6ba0b98f *src/time_zone_if.cc
b4b0e820dd19fe36313705820b70c75a *src/time_zone_if.h
7c8889f3d1777a0ed4b2e427f690e0d6 *src/time_zone_impl.cc
b27b5e15323d9e86fb1e78ccc6cb2a23 *src/time_zone_impl.h
9f910919ab3eef981a54e47efe9e08ac *src/time_zone_info.cc
7c8b8f35a25aab53fb76c356eb1fd17c *src/time_zone_info.h
8a1ef8211946acad2fe5eb69659a431c *src/time_zone_libc.cc
290ef8776251333c8516b88f213db785 *src/time_zone_libc.h
0784513ef3c20d3a9ffdd5fea4728c14 *src/time_zone_lookup.cc
46d9e073cfce772f8d0582134dfd4372 *src/time_zone_posix.cc
38903f4cf6c42636e9f42207b5e435d0 *src/time_zone_posix.h
0c64775d321d4487b269110006acf2a3 *src/tzfile.h
2cff1693aa06404093e1f16a5fd4dde1 *src/utilities.cpp
b902b20040c55efdc292e307cf712491 *src/zone_info_source.cc
cad3d97e1ff5fce87a342264b245bf1d *tests/tinytest.R
RcppCCTZ/R/ 0000755 0001762 0000144 00000000000 13722071251 012043 5 ustar ligges users RcppCCTZ/R/RcppExports.R 0000644 0001762 0000144 00000014673 13722071251 014472 0 ustar ligges users # Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
example0 <- function() {
invisible(.Call(`_RcppCCTZ_example0`))
}
helloMoon <- function(verbose = FALSE) {
.Call(`_RcppCCTZ_helloMoon`, verbose)
}
example1 <- function() {
invisible(.Call(`_RcppCCTZ_example1`))
}
example2 <- function() {
.Call(`_RcppCCTZ_example2`)
}
example3 <- function() {
invisible(.Call(`_RcppCCTZ_example3`))
}
example4 <- function() {
invisible(.Call(`_RcppCCTZ_example4`))
}
exampleFormat <- function() {
invisible(.Call(`_RcppCCTZ_exampleFormat`))
}
#' Difference between two given timezones at a specified date.
#'
#' Time zone offsets vary by date, and this helper function computes
#' the difference (in hours) between two time zones for a given date time.
#'
#' @title Return difference between two time zones at a given date.
#' @param tzfrom The first time zone as a character vector.
#' @param tzto The second time zone as a character vector.
#' @param dt A Datetime object specifying when the difference is to be computed.
#' @param verbose A boolean toggle indicating whether more verbose operations
#' are desired, default is \code{FALSE}.
#' @return A numeric value with the difference (in hours) between the first and
#' second time zone at the given date
#' @author Dirk Eddelbuettel
#' @examples
#' \dontrun{
#' # simple call: difference now
#' tzDiff("America/New_York", "Europe/London", Sys.time())
#' # tabulate difference for every week of the year
#' table(sapply(0:52, function(d) tzDiff("America/New_York", "Europe/London",
#' as.POSIXct(as.Date("2016-01-01") + d*7))))
#' }
tzDiff <- function(tzfrom, tzto, dt, verbose = FALSE) {
.Call(`_RcppCCTZ_tzDiff`, tzfrom, tzto, dt, verbose)
}
#' Change from one given timezone to another.
#'
#' Time zone offsets vary by date, and this helper function converts
#' a Datetime object from one given timezone to another.
#'
#' @title Shift datetime object from one timezone to another
#' @param dtv A DatetimeVector object specifying when the difference is to be computed.
#' @param tzfrom The first time zone as a character vector.
#' @param tzto The second time zone as a character vector.
#' @param verbose A boolean toggle indicating whether more verbose operations
#' are desired, default is \code{FALSE}.
#' @return A DatetimeVector object with the given (civil time) determined by the
#' incoming object (and its timezone) shifted to the target timezone.
#' @author Dirk Eddelbuettel
#' @examples
#' \dontrun{
#' toTz(Sys.time(), "America/New_York", "Europe/London")
#' # this redoes the 'Armstrong on the moon in NYC and Sydney' example
#' toTz(ISOdatetime(1969,7,20,22,56,0,tz="UTC"), "America/New_York", "Australia/Sydney", verbose=TRUE)
#' # we can also explicitly format for Sydney time
#' format(toTz(ISOdatetime(1969,7,20,22,56,0,tz="UTC"),
#' "America/New_York", "Australia/Sydney", verbose=TRUE),
#' tz="Australia/Sydney")
#' }
toTz <- function(dtv, tzfrom, tzto, verbose = FALSE) {
.Call(`_RcppCCTZ_toTz`, dtv, tzfrom, tzto, verbose)
}
#' Format a Datetime vector
#'
#' An alternative to \code{format.POSIXct} based on the CCTZ library. The
#' \code{formatDouble} variant uses two vectors for seconds since the epoch
#' and fractional nanoseconds, respectively, to provide fuller resolution.
#'
#' @title Format a Datetime vector as a string vector
#' @param dtv A Datetime vector object to be formatted
#' @param fmt A string with the format, which is based on \code{strftime} with some
#' extensions; see the CCTZ documentation for details.
#' @param lcltzstr The local timezone object for creation the CCTZ timepoint
#' @param tgttzstr The target timezone for the desired format
#' @return A string vector with the requested format of the datetime objects
#' @section Note:
#' Windows is now supported via the \code{g++-4.9} compiler, but note
#' that it provides an \emph{incomplete} C++11 library. This means we had
#' to port a time parsing routine, and that string formatting is more
#' limited. As one example, CCTZ frequently uses \code{"\%F \%T"} which do
#' not work on Windows; one has to use \code{"\%Y-\%m-\%d \%H:\%M:\%S"}.
#' @author Dirk Eddelbuettel
#' @examples
#' \dontrun{
#' now <- Sys.time()
#' formatDatetime(now) # current (UTC) time, in full precision RFC3339
#' formatDatetime(now, tgttzstr="America/New_York") # same but in NY
#' formatDatetime(now + 0:4) # vectorised
#' }
formatDatetime <- function(dtv, fmt = "%Y-%m-%dT%H:%M:%E*S%Ez", lcltzstr = "UTC", tgttzstr = "UTC") {
.Call(`_RcppCCTZ_formatDatetime`, dtv, fmt, lcltzstr, tgttzstr)
}
#' Parse a Datetime vector
#'
#' An alternative to \code{as.POSIXct} based on the CCTZ library
#'
#' @title Parse a Datetime vector from a string vector
#' @param svec A string vector from which a Datetime vector is to be parsed
#' @param fmt A string with the format, which is based on \code{strftime} with some
#' extensions; see the CCTZ documentation for details.
#' @param tzstr The local timezone for the desired format
#' @return A Datetime vector object for \code{parseDatetime}, a numeric matrix with
#' two columns for seconds and nanoseconds for \code{parseDouble}
#' @author Dirk Eddelbuettel
#' @examples
#' ds <- getOption("digits.secs")
#' options(digits.secs=6) # max value
#' parseDatetime("2016-12-07 10:11:12", "%Y-%m-%d %H:%M:%S") # full seconds
#' parseDatetime("2016-12-07 10:11:12.123456", "%Y-%m-%d %H:%M:%E*S") # fractional seconds
#' parseDatetime("2016-12-07T10:11:12.123456-00:00") ## default RFC3339 format
#' parseDatetime("20161207 101112.123456", "%E4Y%m%d %H%M%E*S") # fractional seconds
#' now <- trunc(Sys.time())
#' parseDatetime(formatDatetime(now + 0:4)) # vectorised
#' options(digits.secs=ds)
parseDatetime <- function(svec, fmt = "%Y-%m-%dT%H:%M:%E*S%Ez", tzstr = "UTC") {
.Call(`_RcppCCTZ_parseDatetime`, svec, fmt, tzstr)
}
#' @rdname formatDatetime
#' @param secv A numeric vector with seconds since the epoch
#' @param nanov A numeric vector with nanoseconds since the epoch,
#' complementing \code{secv}.
formatDouble <- function(secv, nanov, fmt = "%Y-%m-%dT%H:%M:%E*S%Ez", tgttzstr = "UTC") {
.Call(`_RcppCCTZ_formatDouble`, secv, nanov, fmt, tgttzstr)
}
#' @rdname parseDatetime
parseDouble <- function(svec, fmt = "%Y-%m-%dT%H:%M:%E*S%Ez", tzstr = "UTC") {
.Call(`_RcppCCTZ_parseDouble`, svec, fmt, tzstr)
}
now <- function() {
invisible(.Call(`_RcppCCTZ_now`))
}
RcppCCTZ/R/init.R 0000755 0001762 0000144 00000000404 13121751234 013131 0 ustar ligges users
## On Windows, set TZDIR to the zoneinfo shipped with R
.onLoad <- function(libname, pkgname) {
if (Sys.info()[["sysname"]] == "Windows" && Sys.getenv("TZDIR") == "") {
Sys.setenv("TZDIR"=file.path(R.home(), "share", "zoneinfo"))
}
}
RcppCCTZ/cleanup 0000755 0001762 0000144 00000000066 14726436444 013237 0 ustar ligges users
rm -f src/*.o src/*.so src/*.dylib src/*~ *~ src/*.d
RcppCCTZ/src/ 0000755 0001762 0000144 00000000000 14726436444 012447 5 ustar ligges users RcppCCTZ/src/time_zone_posix.cc 0000644 0001762 0000144 00000011027 14271014541 016153 0 ustar ligges users // Copyright 2016 Google Inc. All Rights Reserved.
//
// 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
//
// https://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 "time_zone_posix.h"
#include
#include
#include
#include
namespace cctz {
namespace {
const char kDigits[] = "0123456789";
const char* ParseInt(const char* p, int min, int max, int* vp) {
int value = 0;
const char* op = p;
const int kMaxInt = std::numeric_limits::max();
for (; const char* dp = strchr(kDigits, *p); ++p) {
int d = static_cast(dp - kDigits);
if (d >= 10) break; // '\0'
if (value > kMaxInt / 10) return nullptr;
value *= 10;
if (value > kMaxInt - d) return nullptr;
value += d;
}
if (p == op || value < min || value > max) return nullptr;
*vp = value;
return p;
}
// abbr = <.*?> | [^-+,\d]{3,}
const char* ParseAbbr(const char* p, std::string* abbr) {
const char* op = p;
if (*p == '<') { // special zoneinfo <...> form
while (*++p != '>') {
if (*p == '\0') return nullptr;
}
abbr->assign(op + 1, static_cast(p - op) - 1);
return ++p;
}
while (*p != '\0') {
if (strchr("-+,", *p)) break;
if (strchr(kDigits, *p)) break;
++p;
}
if (p - op < 3) return nullptr;
abbr->assign(op, static_cast(p - op));
return p;
}
// offset = [+|-]hh[:mm[:ss]] (aggregated into single seconds value)
const char* ParseOffset(const char* p, int min_hour, int max_hour, int sign,
std::int_fast32_t* offset) {
if (p == nullptr) return nullptr;
if (*p == '+' || *p == '-') {
if (*p++ == '-') sign = -sign;
}
int hours = 0;
int minutes = 0;
int seconds = 0;
p = ParseInt(p, min_hour, max_hour, &hours);
if (p == nullptr) return nullptr;
if (*p == ':') {
p = ParseInt(p + 1, 0, 59, &minutes);
if (p == nullptr) return nullptr;
if (*p == ':') {
p = ParseInt(p + 1, 0, 59, &seconds);
if (p == nullptr) return nullptr;
}
}
*offset = sign * ((((hours * 60) + minutes) * 60) + seconds);
return p;
}
// datetime = ( Jn | n | Mm.w.d ) [ / offset ]
const char* ParseDateTime(const char* p, PosixTransition* res) {
if (p != nullptr && *p == ',') {
if (*++p == 'M') {
int month = 0;
if ((p = ParseInt(p + 1, 1, 12, &month)) != nullptr && *p == '.') {
int week = 0;
if ((p = ParseInt(p + 1, 1, 5, &week)) != nullptr && *p == '.') {
int weekday = 0;
if ((p = ParseInt(p + 1, 0, 6, &weekday)) != nullptr) {
res->date.fmt = PosixTransition::M;
res->date.m.month = static_cast(month);
res->date.m.week = static_cast(week);
res->date.m.weekday = static_cast(weekday);
}
}
}
} else if (*p == 'J') {
int day = 0;
if ((p = ParseInt(p + 1, 1, 365, &day)) != nullptr) {
res->date.fmt = PosixTransition::J;
res->date.j.day = static_cast(day);
}
} else {
int day = 0;
if ((p = ParseInt(p, 0, 365, &day)) != nullptr) {
res->date.fmt = PosixTransition::N;
res->date.n.day = static_cast(day);
}
}
}
if (p != nullptr) {
res->time.offset = 2 * 60 * 60; // default offset is 02:00:00
if (*p == '/') p = ParseOffset(p + 1, -167, 167, 1, &res->time.offset);
}
return p;
}
} // namespace
// spec = std offset [ dst [ offset ] , datetime , datetime ]
bool ParsePosixSpec(const std::string& spec, PosixTimeZone* res) {
const char* p = spec.c_str();
if (*p == ':') return false;
p = ParseAbbr(p, &res->std_abbr);
p = ParseOffset(p, 0, 24, -1, &res->std_offset);
if (p == nullptr) return false;
if (*p == '\0') return true;
p = ParseAbbr(p, &res->dst_abbr);
if (p == nullptr) return false;
res->dst_offset = res->std_offset + (60 * 60); // default
if (*p != ',') p = ParseOffset(p, 0, 24, -1, &res->dst_offset);
p = ParseDateTime(p, &res->dst_start);
p = ParseDateTime(p, &res->dst_end);
return p != nullptr && *p == '\0';
}
} // namespace cctz
RcppCCTZ/src/RcppExports.cpp 0000644 0001762 0000144 00000017175 13722170466 015451 0 ustar ligges users // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include "../inst/include/RcppCCTZ_types.h"
#include
using namespace Rcpp;
// example0
void example0();
RcppExport SEXP _RcppCCTZ_example0() {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
example0();
return R_NilValue;
END_RCPP
}
// helloMoon
Rcpp::CharacterVector helloMoon(bool verbose);
RcppExport SEXP _RcppCCTZ_helloMoon(SEXP verboseSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< bool >::type verbose(verboseSEXP);
rcpp_result_gen = Rcpp::wrap(helloMoon(verbose));
return rcpp_result_gen;
END_RCPP
}
// example1
void example1();
RcppExport SEXP _RcppCCTZ_example1() {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
example1();
return R_NilValue;
END_RCPP
}
// example2
int example2();
RcppExport SEXP _RcppCCTZ_example2() {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = Rcpp::wrap(example2());
return rcpp_result_gen;
END_RCPP
}
// example3
void example3();
RcppExport SEXP _RcppCCTZ_example3() {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
example3();
return R_NilValue;
END_RCPP
}
// example4
void example4();
RcppExport SEXP _RcppCCTZ_example4() {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
example4();
return R_NilValue;
END_RCPP
}
// exampleFormat
void exampleFormat();
RcppExport SEXP _RcppCCTZ_exampleFormat() {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
exampleFormat();
return R_NilValue;
END_RCPP
}
// tzDiff
Rcpp::NumericVector tzDiff(const std::string tzfrom, const std::string tzto, const Rcpp::NumericVector& dt, bool verbose);
RcppExport SEXP _RcppCCTZ_tzDiff(SEXP tzfromSEXP, SEXP tztoSEXP, SEXP dtSEXP, SEXP verboseSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const std::string >::type tzfrom(tzfromSEXP);
Rcpp::traits::input_parameter< const std::string >::type tzto(tztoSEXP);
Rcpp::traits::input_parameter< const Rcpp::NumericVector& >::type dt(dtSEXP);
Rcpp::traits::input_parameter< bool >::type verbose(verboseSEXP);
rcpp_result_gen = Rcpp::wrap(tzDiff(tzfrom, tzto, dt, verbose));
return rcpp_result_gen;
END_RCPP
}
// toTz
Rcpp::DatetimeVector toTz(Rcpp::DatetimeVector dtv, const std::string tzfrom, const std::string tzto, bool verbose);
RcppExport SEXP _RcppCCTZ_toTz(SEXP dtvSEXP, SEXP tzfromSEXP, SEXP tztoSEXP, SEXP verboseSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::DatetimeVector >::type dtv(dtvSEXP);
Rcpp::traits::input_parameter< const std::string >::type tzfrom(tzfromSEXP);
Rcpp::traits::input_parameter< const std::string >::type tzto(tztoSEXP);
Rcpp::traits::input_parameter< bool >::type verbose(verboseSEXP);
rcpp_result_gen = Rcpp::wrap(toTz(dtv, tzfrom, tzto, verbose));
return rcpp_result_gen;
END_RCPP
}
// formatDatetime
Rcpp::CharacterVector formatDatetime(Rcpp::DatetimeVector dtv, std::string fmt, std::string lcltzstr, std::string tgttzstr);
RcppExport SEXP _RcppCCTZ_formatDatetime(SEXP dtvSEXP, SEXP fmtSEXP, SEXP lcltzstrSEXP, SEXP tgttzstrSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::DatetimeVector >::type dtv(dtvSEXP);
Rcpp::traits::input_parameter< std::string >::type fmt(fmtSEXP);
Rcpp::traits::input_parameter< std::string >::type lcltzstr(lcltzstrSEXP);
Rcpp::traits::input_parameter< std::string >::type tgttzstr(tgttzstrSEXP);
rcpp_result_gen = Rcpp::wrap(formatDatetime(dtv, fmt, lcltzstr, tgttzstr));
return rcpp_result_gen;
END_RCPP
}
// parseDatetime
Rcpp::DatetimeVector parseDatetime(Rcpp::CharacterVector svec, std::string fmt, std::string tzstr);
RcppExport SEXP _RcppCCTZ_parseDatetime(SEXP svecSEXP, SEXP fmtSEXP, SEXP tzstrSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::CharacterVector >::type svec(svecSEXP);
Rcpp::traits::input_parameter< std::string >::type fmt(fmtSEXP);
Rcpp::traits::input_parameter< std::string >::type tzstr(tzstrSEXP);
rcpp_result_gen = Rcpp::wrap(parseDatetime(svec, fmt, tzstr));
return rcpp_result_gen;
END_RCPP
}
// formatDouble
Rcpp::CharacterVector formatDouble(Rcpp::NumericVector secv, Rcpp::NumericVector nanov, std::string fmt, std::string tgttzstr);
RcppExport SEXP _RcppCCTZ_formatDouble(SEXP secvSEXP, SEXP nanovSEXP, SEXP fmtSEXP, SEXP tgttzstrSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type secv(secvSEXP);
Rcpp::traits::input_parameter< Rcpp::NumericVector >::type nanov(nanovSEXP);
Rcpp::traits::input_parameter< std::string >::type fmt(fmtSEXP);
Rcpp::traits::input_parameter< std::string >::type tgttzstr(tgttzstrSEXP);
rcpp_result_gen = Rcpp::wrap(formatDouble(secv, nanov, fmt, tgttzstr));
return rcpp_result_gen;
END_RCPP
}
// parseDouble
Rcpp::NumericMatrix parseDouble(Rcpp::CharacterVector svec, std::string fmt, std::string tzstr);
RcppExport SEXP _RcppCCTZ_parseDouble(SEXP svecSEXP, SEXP fmtSEXP, SEXP tzstrSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::CharacterVector >::type svec(svecSEXP);
Rcpp::traits::input_parameter< std::string >::type fmt(fmtSEXP);
Rcpp::traits::input_parameter< std::string >::type tzstr(tzstrSEXP);
rcpp_result_gen = Rcpp::wrap(parseDouble(svec, fmt, tzstr));
return rcpp_result_gen;
END_RCPP
}
// now
void now();
RcppExport SEXP _RcppCCTZ_now() {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
now();
return R_NilValue;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_RcppCCTZ_example0", (DL_FUNC) &_RcppCCTZ_example0, 0},
{"_RcppCCTZ_helloMoon", (DL_FUNC) &_RcppCCTZ_helloMoon, 1},
{"_RcppCCTZ_example1", (DL_FUNC) &_RcppCCTZ_example1, 0},
{"_RcppCCTZ_example2", (DL_FUNC) &_RcppCCTZ_example2, 0},
{"_RcppCCTZ_example3", (DL_FUNC) &_RcppCCTZ_example3, 0},
{"_RcppCCTZ_example4", (DL_FUNC) &_RcppCCTZ_example4, 0},
{"_RcppCCTZ_exampleFormat", (DL_FUNC) &_RcppCCTZ_exampleFormat, 0},
{"_RcppCCTZ_tzDiff", (DL_FUNC) &_RcppCCTZ_tzDiff, 4},
{"_RcppCCTZ_toTz", (DL_FUNC) &_RcppCCTZ_toTz, 4},
{"_RcppCCTZ_formatDatetime", (DL_FUNC) &_RcppCCTZ_formatDatetime, 4},
{"_RcppCCTZ_parseDatetime", (DL_FUNC) &_RcppCCTZ_parseDatetime, 3},
{"_RcppCCTZ_formatDouble", (DL_FUNC) &_RcppCCTZ_formatDouble, 4},
{"_RcppCCTZ_parseDouble", (DL_FUNC) &_RcppCCTZ_parseDouble, 3},
{"_RcppCCTZ_now", (DL_FUNC) &_RcppCCTZ_now, 0},
{NULL, NULL, 0}
};
RcppExport void R_init_RcppCCTZ(DllInfo *dll) {
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_getOffset", (DL_FUNC) &_RcppCCTZ_getOffset);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToCivilSecond", (DL_FUNC) &_RcppCCTZ_convertToCivilSecond);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToTimePoint", (DL_FUNC) &_RcppCCTZ_convertToTimePoint);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_getOffset_nothrow", (DL_FUNC) &_RcppCCTZ_getOffset_nothrow);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToCivilSecond_nothrow", (DL_FUNC) &_RcppCCTZ_convertToCivilSecond_nothrow);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToTimePoint_nothrow", (DL_FUNC) &_RcppCCTZ_convertToTimePoint_nothrow);
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
RcppCCTZ/src/tzfile.h 0000644 0001762 0000144 00000007631 14271014541 014105 0 ustar ligges users /* Layout and location of TZif files. */
#ifndef TZFILE_H
#define TZFILE_H
/*
** This file is in the public domain, so clarified as of
** 1996-06-05 by Arthur David Olson.
*/
/*
** This header is for use ONLY with the time conversion code.
** There is no guarantee that it will remain unchanged,
** or that it will remain at all.
** Do NOT copy it to any system include directory.
** Thank you!
*/
/*
** Information about time zone files.
*/
#ifndef TZDIR
#define TZDIR "/usr/share/zoneinfo" /* Time zone object file directory */
#endif /* !defined TZDIR */
#ifndef TZDEFAULT
#define TZDEFAULT "/etc/localtime"
#endif /* !defined TZDEFAULT */
#ifndef TZDEFRULES
#define TZDEFRULES "posixrules"
#endif /* !defined TZDEFRULES */
/* See Internet RFC 8536 for more details about the following format. */
/*
** Each file begins with. . .
*/
#define TZ_MAGIC "TZif"
struct tzhead {
char tzh_magic[4]; /* TZ_MAGIC */
char tzh_version[1]; /* '\0' or '2'-'4' as of 2021 */
char tzh_reserved[15]; /* reserved; must be zero */
char tzh_ttisutcnt[4]; /* coded number of trans. time flags */
char tzh_ttisstdcnt[4]; /* coded number of trans. time flags */
char tzh_leapcnt[4]; /* coded number of leap seconds */
char tzh_timecnt[4]; /* coded number of transition times */
char tzh_typecnt[4]; /* coded number of local time types */
char tzh_charcnt[4]; /* coded number of abbr. chars */
};
/*
** . . .followed by. . .
**
** tzh_timecnt (char [4])s coded transition times a la time(2)
** tzh_timecnt (unsigned char)s types of local time starting at above
** tzh_typecnt repetitions of
** one (char [4]) coded UT offset in seconds
** one (unsigned char) used to set tm_isdst
** one (unsigned char) that's an abbreviation list index
** tzh_charcnt (char)s '\0'-terminated zone abbreviations
** tzh_leapcnt repetitions of
** one (char [4]) coded leap second transition times
** one (char [4]) total correction after above
** tzh_ttisstdcnt (char)s indexed by type; if 1, transition
** time is standard time, if 0,
** transition time is local (wall clock)
** time; if absent, transition times are
** assumed to be local time
** tzh_ttisutcnt (char)s indexed by type; if 1, transition
** time is UT, if 0, transition time is
** local time; if absent, transition
** times are assumed to be local time.
** When this is 1, the corresponding
** std/wall indicator must also be 1.
*/
/*
** If tzh_version is '2' or greater, the above is followed by a second instance
** of tzhead and a second instance of the data in which each coded transition
** time uses 8 rather than 4 chars,
** then a POSIX-TZ-environment-variable-style string for use in handling
** instants after the last transition time stored in the file
** (with nothing between the newlines if there is no POSIX representation for
** such instants).
**
** If tz_version is '3' or greater, the above is extended as follows.
** First, the POSIX TZ string's hour offset may range from -167
** through 167 as compared to the POSIX-required 0 through 24.
** Second, its DST start time may be January 1 at 00:00 and its stop
** time December 31 at 24:00 plus the difference between DST and
** standard time, indicating DST all year.
*/
/*
** In the current implementation, "tzset()" refuses to deal with files that
** exceed any of the limits below.
*/
#ifndef TZ_MAX_TIMES
#define TZ_MAX_TIMES 2000
#endif /* !defined TZ_MAX_TIMES */
#ifndef TZ_MAX_TYPES
/* This must be at least 17 for Europe/Samara and Europe/Vilnius. */
#define TZ_MAX_TYPES 256 /* Limited by what (unsigned char)'s can hold */
#endif /* !defined TZ_MAX_TYPES */
#ifndef TZ_MAX_CHARS
#define TZ_MAX_CHARS 50 /* Maximum number of abbreviation characters */
/* (limited by what unsigned chars can hold) */
#endif /* !defined TZ_MAX_CHARS */
#ifndef TZ_MAX_LEAPS
#define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */
#endif /* !defined TZ_MAX_LEAPS */
#endif /* !defined TZFILE_H */
RcppCCTZ/src/time_zone_info.cc 0000644 0001762 0000144 00000115461 14271014541 015753 0 ustar ligges users // Copyright 2016 Google Inc. All Rights Reserved.
//
// 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
//
// https://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.
// This file implements the TimeZoneIf interface using the "zoneinfo"
// data provided by the IANA Time Zone Database (i.e., the only real game
// in town).
//
// TimeZoneInfo represents the history of UTC-offset changes within a time
// zone. Most changes are due to daylight-saving rules, but occasionally
// shifts are made to the time-zone's base offset. The database only attempts
// to be definitive for times since 1970, so be wary of local-time conversions
// before that. Also, rule and zone-boundary changes are made at the whim
// of governments, so the conversion of future times needs to be taken with
// a grain of salt.
//
// For more information see tzfile(5), http://www.iana.org/time-zones, or
// https://en.wikipedia.org/wiki/Zoneinfo.
//
// Note that we assume the proleptic Gregorian calendar and 60-second
// minutes throughout.
#include "time_zone_info.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "cctz/civil_time.h"
#include "time_zone_fixed.h"
#include "time_zone_posix.h"
namespace cctz {
namespace {
inline bool IsLeap(year_t year) {
return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0);
}
// The number of days in non-leap and leap years respectively.
const std::int_least32_t kDaysPerYear[2] = {365, 366};
// The day offsets of the beginning of each (1-based) month in non-leap and
// leap years respectively (e.g., 335 days before December in a leap year).
const std::int_least16_t kMonthOffsets[2][1 + 12 + 1] = {
{-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
{-1, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366},
};
// We reject leap-second encoded zoneinfo and so assume 60-second minutes.
const std::int_least32_t kSecsPerDay = 24 * 60 * 60;
// 400-year chunks always have 146097 days (20871 weeks).
const std::int_least64_t kSecsPer400Years = 146097LL * kSecsPerDay;
// Like kDaysPerYear[] but scaled up by a factor of kSecsPerDay.
const std::int_least32_t kSecsPerYear[2] = {
365 * kSecsPerDay,
366 * kSecsPerDay,
};
// Convert a cctz::weekday to a POSIX TZ weekday number (0==Sun, ..., 6=Sat).
inline int ToPosixWeekday(weekday wd) {
switch (wd) {
case weekday::sunday:
return 0;
case weekday::monday:
return 1;
case weekday::tuesday:
return 2;
case weekday::wednesday:
return 3;
case weekday::thursday:
return 4;
case weekday::friday:
return 5;
case weekday::saturday:
return 6;
}
return 0; /*NOTREACHED*/
}
// Single-byte, unsigned numeric values are encoded directly.
inline std::uint_fast8_t Decode8(const char* cp) {
return static_cast(*cp) & 0xff;
}
// Multi-byte, numeric values are encoded using a MSB first,
// twos-complement representation. These helpers decode, from
// the given address, 4-byte and 8-byte values respectively.
// Note: If int_fastXX_t == intXX_t and this machine is not
// twos complement, then there will be at least one input value
// we cannot represent.
std::int_fast32_t Decode32(const char* cp) {
std::uint_fast32_t v = 0;
for (int i = 0; i != (32 / 8); ++i) v = (v << 8) | Decode8(cp++);
const std::int_fast32_t s32max = 0x7fffffff;
const auto s32maxU = static_cast(s32max);
if (v <= s32maxU) return static_cast(v);
return static_cast(v - s32maxU - 1) - s32max - 1;
}
std::int_fast64_t Decode64(const char* cp) {
std::uint_fast64_t v = 0;
for (int i = 0; i != (64 / 8); ++i) v = (v << 8) | Decode8(cp++);
const std::int_fast64_t s64max = 0x7fffffffffffffff;
const auto s64maxU = static_cast(s64max);
if (v <= s64maxU) return static_cast(v);
return static_cast(v - s64maxU - 1) - s64max - 1;
}
// Generate a year-relative offset for a PosixTransition.
std::int_fast64_t TransOffset(bool leap_year, int jan1_weekday,
const PosixTransition& pt) {
std::int_fast64_t days = 0;
switch (pt.date.fmt) {
case PosixTransition::J: {
days = pt.date.j.day;
if (!leap_year || days < kMonthOffsets[1][3]) days -= 1;
break;
}
case PosixTransition::N: {
days = pt.date.n.day;
break;
}
case PosixTransition::M: {
const bool last_week = (pt.date.m.week == 5);
days = kMonthOffsets[leap_year][pt.date.m.month + last_week];
const std::int_fast64_t weekday = (jan1_weekday + days) % 7;
if (last_week) {
days -= (weekday + 7 - 1 - pt.date.m.weekday) % 7 + 1;
} else {
days += (pt.date.m.weekday + 7 - weekday) % 7;
days += (pt.date.m.week - 1) * 7;
}
break;
}
}
return (days * kSecsPerDay) + pt.time.offset;
}
inline time_zone::civil_lookup MakeUnique(const time_point& tp) {
time_zone::civil_lookup cl;
cl.kind = time_zone::civil_lookup::UNIQUE;
cl.pre = cl.trans = cl.post = tp;
return cl;
}
inline time_zone::civil_lookup MakeUnique(std::int_fast64_t unix_time) {
return MakeUnique(FromUnixSeconds(unix_time));
}
inline time_zone::civil_lookup MakeSkipped(const Transition& tr,
const civil_second& cs) {
time_zone::civil_lookup cl;
cl.kind = time_zone::civil_lookup::SKIPPED;
cl.pre = FromUnixSeconds(tr.unix_time - 1 + (cs - tr.prev_civil_sec));
cl.trans = FromUnixSeconds(tr.unix_time);
cl.post = FromUnixSeconds(tr.unix_time - (tr.civil_sec - cs));
return cl;
}
inline time_zone::civil_lookup MakeRepeated(const Transition& tr,
const civil_second& cs) {
time_zone::civil_lookup cl;
cl.kind = time_zone::civil_lookup::REPEATED;
cl.pre = FromUnixSeconds(tr.unix_time - 1 - (tr.prev_civil_sec - cs));
cl.trans = FromUnixSeconds(tr.unix_time);
cl.post = FromUnixSeconds(tr.unix_time + (cs - tr.civil_sec));
return cl;
}
inline civil_second YearShift(const civil_second& cs, year_t shift) {
return civil_second(cs.year() + shift, cs.month(), cs.day(),
cs.hour(), cs.minute(), cs.second());
}
} // namespace
// What (no leap-seconds) UTC+seconds zoneinfo would look like.
bool TimeZoneInfo::ResetToBuiltinUTC(const seconds& offset) {
transition_types_.resize(1);
TransitionType& tt(transition_types_.back());
tt.utc_offset = static_cast(offset.count());
tt.is_dst = false;
tt.abbr_index = 0;
// We temporarily add some redundant, contemporary (2015 through 2025)
// transitions for performance reasons. See TimeZoneInfo::LocalTime().
// TODO: Fix the performance issue and remove the extra transitions.
transitions_.clear();
transitions_.reserve(12);
for (const std::int_fast64_t unix_time : {
-(1LL << 59), // a "first half" transition
1420070400LL, // 2015-01-01T00:00:00+00:00
1451606400LL, // 2016-01-01T00:00:00+00:00
1483228800LL, // 2017-01-01T00:00:00+00:00
1514764800LL, // 2018-01-01T00:00:00+00:00
1546300800LL, // 2019-01-01T00:00:00+00:00
1577836800LL, // 2020-01-01T00:00:00+00:00
1609459200LL, // 2021-01-01T00:00:00+00:00
1640995200LL, // 2022-01-01T00:00:00+00:00
1672531200LL, // 2023-01-01T00:00:00+00:00
1704067200LL, // 2024-01-01T00:00:00+00:00
1735689600LL, // 2025-01-01T00:00:00+00:00
}) {
Transition& tr(*transitions_.emplace(transitions_.end()));
tr.unix_time = unix_time;
tr.type_index = 0;
tr.civil_sec = LocalTime(tr.unix_time, tt).cs;
tr.prev_civil_sec = tr.civil_sec - 1;
}
default_transition_type_ = 0;
abbreviations_ = FixedOffsetToAbbr(offset);
abbreviations_.append(1, '\0');
future_spec_.clear(); // never needed for a fixed-offset zone
extended_ = false;
tt.civil_max = LocalTime(seconds::max().count(), tt).cs;
tt.civil_min = LocalTime(seconds::min().count(), tt).cs;
transitions_.shrink_to_fit();
return true;
}
// Builds the in-memory header using the raw bytes from the file.
bool TimeZoneInfo::Header::Build(const tzhead& tzh) {
std::int_fast32_t v;
if ((v = Decode32(tzh.tzh_timecnt)) < 0) return false;
timecnt = static_cast(v);
if ((v = Decode32(tzh.tzh_typecnt)) < 0) return false;
typecnt = static_cast(v);
if ((v = Decode32(tzh.tzh_charcnt)) < 0) return false;
charcnt = static_cast(v);
if ((v = Decode32(tzh.tzh_leapcnt)) < 0) return false;
leapcnt = static_cast(v);
if ((v = Decode32(tzh.tzh_ttisstdcnt)) < 0) return false;
ttisstdcnt = static_cast(v);
if ((v = Decode32(tzh.tzh_ttisutcnt)) < 0) return false;
ttisutcnt = static_cast(v);
return true;
}
// How many bytes of data are associated with this header. The result
// depends upon whether this is a section with 4-byte or 8-byte times.
std::size_t TimeZoneInfo::Header::DataLength(std::size_t time_len) const {
std::size_t len = 0;
len += (time_len + 1) * timecnt; // unix_time + type_index
len += (4 + 1 + 1) * typecnt; // utc_offset + is_dst + abbr_index
len += 1 * charcnt; // abbreviations
len += (time_len + 4) * leapcnt; // leap-time + TAI-UTC
len += 1 * ttisstdcnt; // UTC/local indicators
len += 1 * ttisutcnt; // standard/wall indicators
return len;
}
// zic(8) can generate no-op transitions when a zone changes rules at an
// instant when there is actually no discontinuity. So we check whether
// two transitions have equivalent types (same offset/is_dst/abbr).
bool TimeZoneInfo::EquivTransitions(std::uint_fast8_t tt1_index,
std::uint_fast8_t tt2_index) const {
if (tt1_index == tt2_index) return true;
const TransitionType& tt1(transition_types_[tt1_index]);
const TransitionType& tt2(transition_types_[tt2_index]);
if (tt1.utc_offset != tt2.utc_offset) return false;
if (tt1.is_dst != tt2.is_dst) return false;
if (tt1.abbr_index != tt2.abbr_index) return false;
return true;
}
// Find/make a transition type with these attributes.
bool TimeZoneInfo::GetTransitionType(std::int_fast32_t utc_offset, bool is_dst,
const std::string& abbr,
std::uint_least8_t* index) {
std::size_t type_index = 0;
std::size_t abbr_index = abbreviations_.size();
for (; type_index != transition_types_.size(); ++type_index) {
const TransitionType& tt(transition_types_[type_index]);
const char* tt_abbr = &abbreviations_[tt.abbr_index];
if (tt_abbr == abbr) abbr_index = tt.abbr_index;
if (tt.utc_offset == utc_offset && tt.is_dst == is_dst) {
if (abbr_index == tt.abbr_index) break; // reuse
}
}
if (type_index > 255 || abbr_index > 255) {
// No index space (8 bits) available for a new type or abbreviation.
return false;
}
if (type_index == transition_types_.size()) {
TransitionType& tt(*transition_types_.emplace(transition_types_.end()));
tt.utc_offset = static_cast(utc_offset);
tt.is_dst = is_dst;
if (abbr_index == abbreviations_.size()) {
abbreviations_.append(abbr);
abbreviations_.append(1, '\0');
}
tt.abbr_index = static_cast(abbr_index);
}
*index = static_cast(type_index);
return true;
}
// Use the POSIX-TZ-environment-variable-style string to handle times
// in years after the last transition stored in the zoneinfo data.
bool TimeZoneInfo::ExtendTransitions() {
extended_ = false;
if (future_spec_.empty()) return true; // last transition prevails
PosixTimeZone posix;
if (!ParsePosixSpec(future_spec_, &posix)) return false;
// Find transition type for the future std specification.
std::uint_least8_t std_ti;
if (!GetTransitionType(posix.std_offset, false, posix.std_abbr, &std_ti))
return false;
if (posix.dst_abbr.empty()) { // std only
// The future specification should match the last transition, and
// that means that handling the future will fall out naturally.
return EquivTransitions(transitions_.back().type_index, std_ti);
}
// Find transition type for the future dst specification.
std::uint_least8_t dst_ti;
if (!GetTransitionType(posix.dst_offset, true, posix.dst_abbr, &dst_ti))
return false;
// Extend the transitions for an additional 400 years using the
// future specification. Years beyond those can be handled by
// mapping back to a cycle-equivalent year within that range.
// We may need two additional transitions for the current year.
transitions_.reserve(transitions_.size() + 400 * 2 + 2);
extended_ = true;
const Transition& last(transitions_.back());
const std::int_fast64_t last_time = last.unix_time;
const TransitionType& last_tt(transition_types_[last.type_index]);
last_year_ = LocalTime(last_time, last_tt).cs.year();
bool leap_year = IsLeap(last_year_);
const civil_second jan1(last_year_);
std::int_fast64_t jan1_time = jan1 - civil_second();
int jan1_weekday = ToPosixWeekday(get_weekday(jan1));
Transition dst = {0, dst_ti, civil_second(), civil_second()};
Transition std = {0, std_ti, civil_second(), civil_second()};
for (const year_t limit = last_year_ + 400;; ++last_year_) {
auto dst_trans_off = TransOffset(leap_year, jan1_weekday, posix.dst_start);
auto std_trans_off = TransOffset(leap_year, jan1_weekday, posix.dst_end);
dst.unix_time = jan1_time + dst_trans_off - posix.std_offset;
std.unix_time = jan1_time + std_trans_off - posix.dst_offset;
const auto* ta = dst.unix_time < std.unix_time ? &dst : &std;
const auto* tb = dst.unix_time < std.unix_time ? &std : &dst;
if (last_time < tb->unix_time) {
if (last_time < ta->unix_time) transitions_.push_back(*ta);
transitions_.push_back(*tb);
}
if (last_year_ == limit) break;
jan1_time += kSecsPerYear[leap_year];
jan1_weekday = (jan1_weekday + kDaysPerYear[leap_year]) % 7;
leap_year = !leap_year && IsLeap(last_year_ + 1);
}
return true;
}
bool TimeZoneInfo::Load(ZoneInfoSource* zip) {
// Read and validate the header.
tzhead tzh;
if (zip->Read(&tzh, sizeof(tzh)) != sizeof(tzh))
return false;
if (strncmp(tzh.tzh_magic, TZ_MAGIC, sizeof(tzh.tzh_magic)) != 0)
return false;
Header hdr;
if (!hdr.Build(tzh))
return false;
std::size_t time_len = 4;
if (tzh.tzh_version[0] != '\0') {
// Skip the 4-byte data.
if (zip->Skip(hdr.DataLength(time_len)) != 0)
return false;
// Read and validate the header for the 8-byte data.
if (zip->Read(&tzh, sizeof(tzh)) != sizeof(tzh))
return false;
if (strncmp(tzh.tzh_magic, TZ_MAGIC, sizeof(tzh.tzh_magic)) != 0)
return false;
if (tzh.tzh_version[0] == '\0')
return false;
if (!hdr.Build(tzh))
return false;
time_len = 8;
}
if (hdr.typecnt == 0)
return false;
if (hdr.leapcnt != 0) {
// This code assumes 60-second minutes so we do not want
// the leap-second encoded zoneinfo. We could reverse the
// compensation, but the "right" encoding is rarely used
// so currently we simply reject such data.
return false;
}
if (hdr.ttisstdcnt != 0 && hdr.ttisstdcnt != hdr.typecnt)
return false;
if (hdr.ttisutcnt != 0 && hdr.ttisutcnt != hdr.typecnt)
return false;
// Read the data into a local buffer.
std::size_t len = hdr.DataLength(time_len);
std::vector tbuf(len);
if (zip->Read(tbuf.data(), len) != len)
return false;
const char* bp = tbuf.data();
// Decode and validate the transitions.
transitions_.reserve(hdr.timecnt + 2);
transitions_.resize(hdr.timecnt);
for (std::size_t i = 0; i != hdr.timecnt; ++i) {
transitions_[i].unix_time = (time_len == 4) ? Decode32(bp) : Decode64(bp);
bp += time_len;
if (i != 0) {
// Check that the transitions are ordered by time (as zic guarantees).
if (!Transition::ByUnixTime()(transitions_[i - 1], transitions_[i]))
return false; // out of order
}
}
bool seen_type_0 = false;
for (std::size_t i = 0; i != hdr.timecnt; ++i) {
transitions_[i].type_index = Decode8(bp++);
if (transitions_[i].type_index >= hdr.typecnt)
return false;
if (transitions_[i].type_index == 0)
seen_type_0 = true;
}
// Decode and validate the transition types.
transition_types_.reserve(hdr.typecnt + 2);
transition_types_.resize(hdr.typecnt);
for (std::size_t i = 0; i != hdr.typecnt; ++i) {
transition_types_[i].utc_offset =
static_cast(Decode32(bp));
if (transition_types_[i].utc_offset >= kSecsPerDay ||
transition_types_[i].utc_offset <= -kSecsPerDay)
return false;
bp += 4;
transition_types_[i].is_dst = (Decode8(bp++) != 0);
transition_types_[i].abbr_index = Decode8(bp++);
if (transition_types_[i].abbr_index >= hdr.charcnt)
return false;
}
// Determine the before-first-transition type.
default_transition_type_ = 0;
if (seen_type_0 && hdr.timecnt != 0) {
std::uint_fast8_t index = 0;
if (transition_types_[0].is_dst) {
index = transitions_[0].type_index;
while (index != 0 && transition_types_[index].is_dst)
--index;
}
while (index != hdr.typecnt && transition_types_[index].is_dst)
++index;
if (index != hdr.typecnt)
default_transition_type_ = index;
}
// Copy all the abbreviations.
abbreviations_.reserve(hdr.charcnt + 10);
abbreviations_.assign(bp, hdr.charcnt);
bp += hdr.charcnt;
// Skip the unused portions. We've already dispensed with leap-second
// encoded zoneinfo. The ttisstd/ttisgmt indicators only apply when
// interpreting a POSIX spec that does not include start/end rules, and
// that isn't the case here (see "zic -p").
bp += (8 + 4) * hdr.leapcnt; // leap-time + TAI-UTC
bp += 1 * hdr.ttisstdcnt; // UTC/local indicators
bp += 1 * hdr.ttisutcnt; // standard/wall indicators
assert(bp == tbuf.data() + tbuf.size());
future_spec_.clear();
if (tzh.tzh_version[0] != '\0') {
// Snarf up the NL-enclosed future POSIX spec. Note
// that version '3' files utilize an extended format.
auto get_char = [](ZoneInfoSource* azip) -> int {
unsigned char ch; // all non-EOF results are positive
return (azip->Read(&ch, 1) == 1) ? ch : EOF;
};
if (get_char(zip) != '\n')
return false;
for (int c = get_char(zip); c != '\n'; c = get_char(zip)) {
if (c == EOF)
return false;
future_spec_.push_back(static_cast(c));
}
}
// We don't check for EOF so that we're forwards compatible.
// If we did not find version information during the standard loading
// process (as of tzh_version '3' that is unsupported), then ask the
// ZoneInfoSource for any out-of-bound version string it may be privy to.
if (version_.empty()) {
version_ = zip->Version();
}
// Trim redundant transitions. zic may have added these to work around
// differences between the glibc and reference implementations (see
// zic.c:dontmerge) and the Qt library (see zic.c:WORK_AROUND_QTBUG_53071).
// For us, they just get in the way when we do future_spec_ extension.
while (hdr.timecnt > 1) {
if (!EquivTransitions(transitions_[hdr.timecnt - 1].type_index,
transitions_[hdr.timecnt - 2].type_index)) {
break;
}
hdr.timecnt -= 1;
}
transitions_.resize(hdr.timecnt);
// Ensure that there is always a transition in the first half of the
// time line (the second half is handled below) so that the signed
// difference between a civil_second and the civil_second of its
// previous transition is always representable, without overflow.
if (transitions_.empty() || transitions_.front().unix_time >= 0) {
Transition& tr(*transitions_.emplace(transitions_.begin()));
tr.unix_time = -(1LL << 59); // -18267312070-10-26T17:01:52+00:00
tr.type_index = default_transition_type_;
}
// Extend the transitions using the future specification.
if (!ExtendTransitions()) return false;
// Ensure that there is always a transition in the second half of the
// time line (the first half is handled above) so that the signed
// difference between a civil_second and the civil_second of its
// previous transition is always representable, without overflow.
const Transition& last(transitions_.back());
if (last.unix_time < 0) {
const std::uint_fast8_t type_index = last.type_index;
Transition& tr(*transitions_.emplace(transitions_.end()));
tr.unix_time = 2147483647; // 2038-01-19T03:14:07+00:00
tr.type_index = type_index;
}
// Compute the local civil time for each transition and the preceding
// second. These will be used for reverse conversions in MakeTime().
const TransitionType* ttp = &transition_types_[default_transition_type_];
for (std::size_t i = 0; i != transitions_.size(); ++i) {
Transition& tr(transitions_[i]);
tr.prev_civil_sec = LocalTime(tr.unix_time, *ttp).cs - 1;
ttp = &transition_types_[tr.type_index];
tr.civil_sec = LocalTime(tr.unix_time, *ttp).cs;
if (i != 0) {
// Check that the transitions are ordered by civil time. Essentially
// this means that an offset change cannot cross another such change.
// No one does this in practice, and we depend on it in MakeTime().
if (!Transition::ByCivilTime()(transitions_[i - 1], tr))
return false; // out of order
}
}
// Compute the maximum/minimum civil times that can be converted to a
// time_point for each of the zone's transition types.
for (auto& tt : transition_types_) {
tt.civil_max = LocalTime(seconds::max().count(), tt).cs;
tt.civil_min = LocalTime(seconds::min().count(), tt).cs;
}
transitions_.shrink_to_fit();
return true;
}
namespace {
using FilePtr = std::unique_ptr;
// fopen(3) adaptor.
inline FilePtr FOpen(const char* path, const char* mode) {
#if defined(_MSC_VER)
FILE* fp;
if (fopen_s(&fp, path, mode) != 0) fp = nullptr;
return FilePtr(fp, fclose);
#else
// TODO: Enable the close-on-exec flag.
return FilePtr(fopen(path, mode), fclose);
#endif
}
// A stdio(3)-backed implementation of ZoneInfoSource.
class FileZoneInfoSource : public ZoneInfoSource {
public:
static std::unique_ptr Open(const std::string& name);
std::size_t Read(void* ptr, std::size_t size) override {
size = std::min(size, len_);
std::size_t nread = fread(ptr, 1, size, fp_.get());
len_ -= nread;
return nread;
}
int Skip(std::size_t offset) override {
offset = std::min(offset, len_);
int rc = fseek(fp_.get(), static_cast(offset), SEEK_CUR);
if (rc == 0) len_ -= offset;
return rc;
}
std::string Version() const override {
// TODO: It would nice if the zoneinfo data included the tzdb version.
return std::string();
}
protected:
explicit FileZoneInfoSource(
FilePtr fp, std::size_t len = std::numeric_limits::max())
: fp_(std::move(fp)), len_(len) {}
private:
FilePtr fp_;
std::size_t len_;
};
std::unique_ptr FileZoneInfoSource::Open(
const std::string& name) {
// Use of the "file:" prefix is intended for testing purposes only.
const std::size_t pos = (name.compare(0, 5, "file:") == 0) ? 5 : 0;
// Map the time-zone name to a path name.
std::string path;
if (pos == name.size() || name[pos] != '/') {
const char* tzdir = "/usr/share/zoneinfo";
char* tzdir_env = nullptr;
#if defined(_MSC_VER)
_dupenv_s(&tzdir_env, nullptr, "TZDIR");
#else
tzdir_env = std::getenv("TZDIR");
#endif
if (tzdir_env && *tzdir_env) tzdir = tzdir_env;
path += tzdir;
path += '/';
#if defined(_MSC_VER)
free(tzdir_env);
#endif
}
path.append(name, pos, std::string::npos);
// Open the zoneinfo file.
auto fp = FOpen(path.c_str(), "rb");
if (fp == nullptr) return nullptr;
return std::unique_ptr(new FileZoneInfoSource(std::move(fp)));
}
class AndroidZoneInfoSource : public FileZoneInfoSource {
public:
static std::unique_ptr Open(const std::string& name);
std::string Version() const override { return version_; }
private:
explicit AndroidZoneInfoSource(FilePtr fp, std::size_t len,
std::string version)
: FileZoneInfoSource(std::move(fp), len), version_(std::move(version)) {}
std::string version_;
};
std::unique_ptr AndroidZoneInfoSource::Open(
const std::string& name) {
// Use of the "file:" prefix is intended for testing purposes only.
const std::size_t pos = (name.compare(0, 5, "file:") == 0) ? 5 : 0;
// See Android's libc/tzcode/bionic.cpp for additional information.
for (const char* tzdata : {"/data/misc/zoneinfo/current/tzdata",
"/system/usr/share/zoneinfo/tzdata"}) {
auto fp = FOpen(tzdata, "rb");
if (fp == nullptr) continue;
char hbuf[24]; // covers header.zonetab_offset too
if (fread(hbuf, 1, sizeof(hbuf), fp.get()) != sizeof(hbuf)) continue;
if (strncmp(hbuf, "tzdata", 6) != 0) continue;
const char* vers = (hbuf[11] == '\0') ? hbuf + 6 : "";
const std::int_fast32_t index_offset = Decode32(hbuf + 12);
const std::int_fast32_t data_offset = Decode32(hbuf + 16);
if (index_offset < 0 || data_offset < index_offset) continue;
if (fseek(fp.get(), static_cast(index_offset), SEEK_SET) != 0)
continue;
char ebuf[52]; // covers entry.unused too
const std::size_t index_size =
static_cast(data_offset - index_offset);
const std::size_t zonecnt = index_size / sizeof(ebuf);
if (zonecnt * sizeof(ebuf) != index_size) continue;
for (std::size_t i = 0; i != zonecnt; ++i) {
if (fread(ebuf, 1, sizeof(ebuf), fp.get()) != sizeof(ebuf)) break;
const std::int_fast32_t start = data_offset + Decode32(ebuf + 40);
const std::int_fast32_t length = Decode32(ebuf + 44);
if (start < 0 || length < 0) break;
ebuf[40] = '\0'; // ensure zone name is NUL terminated
if (strcmp(name.c_str() + pos, ebuf) == 0) {
if (fseek(fp.get(), static_cast(start), SEEK_SET) != 0) break;
return std::unique_ptr(new AndroidZoneInfoSource(
std::move(fp), static_cast(length), vers));
}
}
}
return nullptr;
}
// A zoneinfo source for use inside Fuchsia components. This attempts to
// read zoneinfo files from one of several known paths in a component's
// incoming namespace. [Config data][1] is preferred, but package-specific
// resources are also supported.
//
// Fuchsia's implementation supports `FileZoneInfoSource::Version()`.
//
// [1]: https://fuchsia.dev/fuchsia-src/development/components/data#using_config_data_in_your_component
class FuchsiaZoneInfoSource : public FileZoneInfoSource {
public:
static std::unique_ptr Open(const std::string& name);
std::string Version() const override { return version_; }
private:
explicit FuchsiaZoneInfoSource(FilePtr fp, std::string version)
: FileZoneInfoSource(std::move(fp)), version_(std::move(version)) {}
std::string version_;
};
std::unique_ptr FuchsiaZoneInfoSource::Open(
const std::string& name) {
// Use of the "file:" prefix is intended for testing purposes only.
const std::size_t pos = (name.compare(0, 5, "file:") == 0) ? 5 : 0;
// Prefixes where a Fuchsia component might find zoneinfo files,
// in descending order of preference.
const auto kTzdataPrefixes = {
"/config/data/tzdata/",
"/pkg/data/tzdata/",
"/data/tzdata/",
};
const auto kEmptyPrefix = {""};
const bool name_absolute = (pos != name.size() && name[pos] == '/');
const auto prefixes = name_absolute ? kEmptyPrefix : kTzdataPrefixes;
// Fuchsia builds place zoneinfo files at "".
for (const std::string prefix : prefixes) {
std::string path = prefix;
if (!prefix.empty()) path += "zoneinfo/tzif2/"; // format
path.append(name, pos, std::string::npos);
auto fp = FOpen(path.c_str(), "rb");
if (fp == nullptr) continue;
std::string version;
if (!prefix.empty()) {
// Fuchsia builds place the version in "revision.txt".
std::ifstream version_stream(prefix + "revision.txt");
if (version_stream.is_open()) {
// revision.txt should contain no newlines, but to be
// defensive we read just the first line.
std::getline(version_stream, version);
}
}
return std::unique_ptr(
new FuchsiaZoneInfoSource(std::move(fp), std::move(version)));
}
return nullptr;
}
} // namespace
bool TimeZoneInfo::Load(const std::string& name) {
// We can ensure that the loading of UTC or any other fixed-offset
// zone never fails because the simple, fixed-offset state can be
// internally generated. Note that this depends on our choice to not
// accept leap-second encoded ("right") zoneinfo.
auto offset = seconds::zero();
if (FixedOffsetFromName(name, &offset)) {
return ResetToBuiltinUTC(offset);
}
// Find and use a ZoneInfoSource to load the named zone.
auto zip = cctz_extension::zone_info_source_factory(
name, [](const std::string& n) -> std::unique_ptr {
if (auto z = FileZoneInfoSource::Open(n)) return z;
if (auto z = AndroidZoneInfoSource::Open(n)) return z;
if (auto z = FuchsiaZoneInfoSource::Open(n)) return z;
return nullptr;
});
return zip != nullptr && Load(zip.get());
}
// BreakTime() translation for a particular transition type.
time_zone::absolute_lookup TimeZoneInfo::LocalTime(
std::int_fast64_t unix_time, const TransitionType& tt) const {
// A civil time in "+offset" looks like (time+offset) in UTC.
// Note: We perform two additions in the civil_second domain to
// sidestep the chance of overflow in (unix_time + tt.utc_offset).
return {(civil_second() + unix_time) + tt.utc_offset,
tt.utc_offset, tt.is_dst, &abbreviations_[tt.abbr_index]};
}
// BreakTime() translation for a particular transition.
time_zone::absolute_lookup TimeZoneInfo::LocalTime(
std::int_fast64_t unix_time, const Transition& tr) const {
const TransitionType& tt = transition_types_[tr.type_index];
// Note: (unix_time - tr.unix_time) will never overflow as we
// have ensured that there is always a "nearby" transition.
return {tr.civil_sec + (unix_time - tr.unix_time), // TODO: Optimize.
tt.utc_offset, tt.is_dst, &abbreviations_[tt.abbr_index]};
}
// MakeTime() translation with a conversion-preserving +N * 400-year shift.
time_zone::civil_lookup TimeZoneInfo::TimeLocal(const civil_second& cs,
year_t c4_shift) const {
assert(last_year_ - 400 < cs.year() && cs.year() <= last_year_);
time_zone::civil_lookup cl = MakeTime(cs);
if (c4_shift > seconds::max().count() / kSecsPer400Years) {
cl.pre = cl.trans = cl.post = time_point::max();
} else {
const auto offset = seconds(c4_shift * kSecsPer400Years);
const auto limit = time_point::max() - offset;
for (auto* tp : {&cl.pre, &cl.trans, &cl.post}) {
if (*tp > limit) {
*tp = time_point::max();
} else {
*tp += offset;
}
}
}
return cl;
}
time_zone::absolute_lookup TimeZoneInfo::BreakTime(
const time_point& tp) const {
std::int_fast64_t unix_time = ToUnixSeconds(tp);
const std::size_t timecnt = transitions_.size();
assert(timecnt != 0); // We always add a transition.
if (unix_time < transitions_[0].unix_time) {
return LocalTime(unix_time, transition_types_[default_transition_type_]);
}
if (unix_time >= transitions_[timecnt - 1].unix_time) {
// After the last transition. If we extended the transitions using
// future_spec_, shift back to a supported year using the 400-year
// cycle of calendaric equivalence and then compensate accordingly.
if (extended_) {
const std::int_fast64_t diff =
unix_time - transitions_[timecnt - 1].unix_time;
const year_t shift = diff / kSecsPer400Years + 1;
const auto d = seconds(shift * kSecsPer400Years);
time_zone::absolute_lookup al = BreakTime(tp - d);
al.cs = YearShift(al.cs, shift * 400);
return al;
}
return LocalTime(unix_time, transitions_[timecnt - 1]);
}
const std::size_t hint = local_time_hint_.load(std::memory_order_relaxed);
if (0 < hint && hint < timecnt) {
if (transitions_[hint - 1].unix_time <= unix_time) {
if (unix_time < transitions_[hint].unix_time) {
return LocalTime(unix_time, transitions_[hint - 1]);
}
}
}
const Transition target = {unix_time, 0, civil_second(), civil_second()};
const Transition* begin = &transitions_[0];
const Transition* tr = std::upper_bound(begin, begin + timecnt, target,
Transition::ByUnixTime());
local_time_hint_.store(static_cast(tr - begin),
std::memory_order_relaxed);
return LocalTime(unix_time, *--tr);
}
time_zone::civil_lookup TimeZoneInfo::MakeTime(const civil_second& cs) const {
const std::size_t timecnt = transitions_.size();
assert(timecnt != 0); // We always add a transition.
// Find the first transition after our target civil time.
const Transition* tr = nullptr;
const Transition* begin = &transitions_[0];
const Transition* end = begin + timecnt;
if (cs < begin->civil_sec) {
tr = begin;
} else if (cs >= transitions_[timecnt - 1].civil_sec) {
tr = end;
} else {
const std::size_t hint = time_local_hint_.load(std::memory_order_relaxed);
if (0 < hint && hint < timecnt) {
if (transitions_[hint - 1].civil_sec <= cs) {
if (cs < transitions_[hint].civil_sec) {
tr = begin + hint;
}
}
}
if (tr == nullptr) {
const Transition target = {0, 0, cs, civil_second()};
tr = std::upper_bound(begin, end, target, Transition::ByCivilTime());
time_local_hint_.store(static_cast(tr - begin),
std::memory_order_relaxed);
}
}
if (tr == begin) {
if (tr->prev_civil_sec >= cs) {
// Before first transition, so use the default offset.
const TransitionType& tt(transition_types_[default_transition_type_]);
if (cs < tt.civil_min) return MakeUnique(time_point::min());
return MakeUnique(cs - (civil_second() + tt.utc_offset));
}
// tr->prev_civil_sec < cs < tr->civil_sec
return MakeSkipped(*tr, cs);
}
if (tr == end) {
if (cs > (--tr)->prev_civil_sec) {
// After the last transition. If we extended the transitions using
// future_spec_, shift back to a supported year using the 400-year
// cycle of calendaric equivalence and then compensate accordingly.
if (extended_ && cs.year() > last_year_) {
const year_t shift = (cs.year() - last_year_ - 1) / 400 + 1;
return TimeLocal(YearShift(cs, shift * -400), shift);
}
const TransitionType& tt(transition_types_[tr->type_index]);
if (cs > tt.civil_max) return MakeUnique(time_point::max());
return MakeUnique(tr->unix_time + (cs - tr->civil_sec));
}
// tr->civil_sec <= cs <= tr->prev_civil_sec
return MakeRepeated(*tr, cs);
}
if (tr->prev_civil_sec < cs) {
// tr->prev_civil_sec < cs < tr->civil_sec
return MakeSkipped(*tr, cs);
}
if (cs <= (--tr)->prev_civil_sec) {
// tr->civil_sec <= cs <= tr->prev_civil_sec
return MakeRepeated(*tr, cs);
}
// In between transitions.
return MakeUnique(tr->unix_time + (cs - tr->civil_sec));
}
std::string TimeZoneInfo::Version() const {
return version_;
}
std::string TimeZoneInfo::Description() const {
std::ostringstream oss;
oss << "#trans=" << transitions_.size();
oss << " #types=" << transition_types_.size();
oss << " spec='" << future_spec_ << "'";
return oss.str();
}
bool TimeZoneInfo::NextTransition(const time_point& tp,
time_zone::civil_transition* trans) const {
if (transitions_.empty()) return false;
const Transition* begin = &transitions_[0];
const Transition* end = begin + transitions_.size();
if (begin->unix_time <= -(1LL << 59)) {
// Do not report the BIG_BANG found in some zoneinfo data as it is
// really a sentinel, not a transition. See pre-2018f tz/zic.c.
++begin;
}
std::int_fast64_t unix_time = ToUnixSeconds(tp);
const Transition target = {unix_time, 0, civil_second(), civil_second()};
const Transition* tr = std::upper_bound(begin, end, target,
Transition::ByUnixTime());
for (; tr != end; ++tr) { // skip no-op transitions
std::uint_fast8_t prev_type_index =
(tr == begin) ? default_transition_type_ : tr[-1].type_index;
if (!EquivTransitions(prev_type_index, tr[0].type_index)) break;
}
// When tr == end we return false, ignoring future_spec_.
if (tr == end) return false;
trans->from = tr->prev_civil_sec + 1;
trans->to = tr->civil_sec;
return true;
}
bool TimeZoneInfo::PrevTransition(const time_point& tp,
time_zone::civil_transition* trans) const {
if (transitions_.empty()) return false;
const Transition* begin = &transitions_[0];
const Transition* end = begin + transitions_.size();
if (begin->unix_time <= -(1LL << 59)) {
// Do not report the BIG_BANG found in some zoneinfo data as it is
// really a sentinel, not a transition. See pre-2018f tz/zic.c.
++begin;
}
std::int_fast64_t unix_time = ToUnixSeconds(tp);
if (FromUnixSeconds(unix_time) != tp) {
if (unix_time == std::numeric_limits::max()) {
if (end == begin) return false; // Ignore future_spec_.
trans->from = (--end)->prev_civil_sec + 1;
trans->to = end->civil_sec;
return true;
}
unix_time += 1; // ceils
}
const Transition target = {unix_time, 0, civil_second(), civil_second()};
const Transition* tr = std::lower_bound(begin, end, target,
Transition::ByUnixTime());
for (; tr != begin; --tr) { // skip no-op transitions
std::uint_fast8_t prev_type_index =
(tr - 1 == begin) ? default_transition_type_ : tr[-2].type_index;
if (!EquivTransitions(prev_type_index, tr[-1].type_index)) break;
}
// When tr == end we return the "last" transition, ignoring future_spec_.
if (tr == begin) return false;
trans->from = (--tr)->prev_civil_sec + 1;
trans->to = tr->civil_sec;
return true;
}
} // namespace cctz
RcppCCTZ/src/time_zone_if.h 0000644 0001762 0000144 00000004654 14271014541 015261 0 ustar ligges users // Copyright 2016 Google Inc. All Rights Reserved.
//
// 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
//
// https://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.
#ifndef CCTZ_TIME_ZONE_IF_H_
#define CCTZ_TIME_ZONE_IF_H_
#include
#include
#include
#include
#include "cctz/civil_time.h"
#include "cctz/time_zone.h"
namespace cctz {
// A simple interface used to hide time-zone complexities from time_zone::Impl.
// Subclasses implement the functions for civil-time conversions in the zone.
class TimeZoneIf {
public:
// A factory function for TimeZoneIf implementations.
static std::unique_ptr Load(const std::string& name);
virtual ~TimeZoneIf();
virtual time_zone::absolute_lookup BreakTime(
const time_point& tp) const = 0;
virtual time_zone::civil_lookup MakeTime(
const civil_second& cs) const = 0;
virtual bool NextTransition(const time_point& tp,
time_zone::civil_transition* trans) const = 0;
virtual bool PrevTransition(const time_point& tp,
time_zone::civil_transition* trans) const = 0;
virtual std::string Version() const = 0;
virtual std::string Description() const = 0;
protected:
TimeZoneIf() {}
};
// Convert between time_point and a count of seconds since the
// Unix epoch. We assume that the std::chrono::system_clock and the
// Unix clock are second aligned, and that the results are representable.
// (That is, that they share an epoch, which is required since C++20.)
inline std::int_fast64_t ToUnixSeconds(const time_point& tp) {
return (tp - std::chrono::time_point_cast(
std::chrono::system_clock::from_time_t(0))).count();
}
inline time_point FromUnixSeconds(std::int_fast64_t t) {
return std::chrono::time_point_cast(
std::chrono::system_clock::from_time_t(0)) + seconds(t);
}
} // namespace cctz
#endif // CCTZ_TIME_ZONE_IF_H_
RcppCCTZ/src/get_time.h 0000644 0001762 0000144 00000070406 13355642476 014425 0 ustar ligges users // =============================================================================
// The code in this file has been adapted from code in the locale header from
// the LLVM libc++ project and is licensed as follows.
//
// =============================================================================
// libc++ License
// =============================================================================
//
// The libc++ library is dual licensed under both the University of Illinois
// "BSD-Like" license and the MIT license. As a user of this code you may
// choose to use it under either license. As a contributor, you agree to allow
// your code to be used under both.
//
// Full text of the relevant licenses is included below.
//
// =============================================================================
//
// University of Illinois/NCSA
// Open Source License
//
// Copyright (c) 2009-2016 by the contributors listed in CREDITS.TXT
//
// All rights reserved.
//
// Developed by:
//
// LLVM Team
//
// University of Illinois at Urbana-Champaign
//
// http://llvm.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// with the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of the LLVM Team, University of Illinois at
// Urbana-Champaign, nor the names of its contributors may be used to
// endorse or promote products derived from this Software without specific
// prior written permission.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
// THE SOFTWARE.
//
// =============================================================================
//
// Copyright (c) 2009-2014 by the contributors listed in CREDITS.TXT
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef RCPP_CCTZ_GET_TIME
#define RCPP_CCTZ_GET_TIME
#include
#include
#include
#include
#include
#include
#include
#include
namespace std_backport
{
template
class fake_unique_ptr
{
private:
T* p_;
public:
fake_unique_ptr() : p_(NULL) {}
fake_unique_ptr(T *p) : p_(p) {}
~fake_unique_ptr()
{
if (p_) free(p_);
}
T *get() { return p_; }
void reset(T *p)
{
if (p_) free(p_);
p_ = p;
}
};
template
ForwardIterator
scan_keyword(InputIterator& b, InputIterator e,
ForwardIterator kb, ForwardIterator ke,
const Ctype& ct, std::ios_base::iostate& err,
bool case_sensitive = true)
{
typedef typename std::iterator_traits::value_type CharT;
size_t nkw = static_cast(distance(kb, ke));
const unsigned char doesnt_match = '\0';
const unsigned char might_match = '\1';
const unsigned char does_match = '\2';
unsigned char statbuf[100];
unsigned char* status = statbuf;
fake_unique_ptr< unsigned char > stat_hold;
if (nkw > sizeof(statbuf))
{
status = (unsigned char*)malloc(nkw);
if (status == 0)
{
throw std::bad_alloc();
}
stat_hold.reset(status);
}
size_t n_might_match = nkw; // At this point, any keyword might match
size_t n_does_match = 0; // but none of them definitely do
// Initialize all statuses to might_match, except for "" keywords are does_match
unsigned char* st = status;
for (ForwardIterator ky = kb; ky != ke; ++ky, (void) ++st)
{
if (!ky->empty())
*st = might_match;
else
{
*st = does_match;
--n_might_match;
++n_does_match;
}
}
// While there might be a match, test keywords against the next CharT
for (size_t indx = 0; b != e && n_might_match > 0; ++indx)
{
// Peek at the next CharT but don't consume it
CharT c = *b;
if (!case_sensitive)
c = ct.toupper(c);
bool consume = false;
// For each keyword which might match, see if the indx character is c
// If a match if found, consume c
// If a match is found, and that is the last character in the keyword,
// then that keyword matches.
// If the keyword doesn't match this character, then change the keyword
// to doesn't match
st = status;
for (ForwardIterator ky = kb; ky != ke; ++ky, (void) ++st)
{
if (*st == might_match)
{
CharT kc = (*ky)[indx];
if (!case_sensitive)
kc = ct.toupper(kc);
if (c == kc)
{
consume = true;
if (ky->size() == indx+1)
{
*st = does_match;
--n_might_match;
++n_does_match;
}
}
else
{
*st = doesnt_match;
--n_might_match;
}
}
}
// consume if we matched a character
if (consume)
{
++b;
// If we consumed a character and there might be a matched keyword that
// was marked matched on a previous iteration, then such keywords
// which are now marked as not matching.
if (n_might_match + n_does_match > 1)
{
st = status;
for (ForwardIterator ky = kb; ky != ke; ++ky, (void) ++st)
{
if (*st == does_match && ky->size() != indx+1)
{
*st = doesnt_match;
--n_does_match;
}
}
}
}
}
// We've exited the loop because we hit eof and/or we have no more "might matches".
if (b == e)
err |= std::ios_base::eofbit;
// Return the first matching result
for (st = status; kb != ke; ++kb, (void) ++st)
if (*st == does_match)
break;
if (kb == ke)
{
err |= std::ios_base::failbit;
}
return kb;
}
template
int
get_up_to_n_digits(InputIterator& b, InputIterator e,
std::ios_base::iostate& err, const std::ctype& ct, int n)
{
// Precondition: n >= 1
if (b == e)
{
err |= std::ios_base::eofbit | std::ios_base::failbit;
return 0;
}
// get first digit
CharT c = *b;
if (!ct.is(std::ctype_base::digit, c))
{
err |= std::ios_base::failbit;
return 0;
}
int r = ct.narrow(c, 0) - '0';
for (++b, (void) --n; b != e && n > 0; ++b, (void) --n)
{
// get next digit
c = *b;
if (!ct.is(std::ctype_base::digit, c))
return r;
r = r * 10 + ct.narrow(c, 0) - '0';
}
if (b == e)
err |= std::ios_base::eofbit;
return r;
}
template
class time_get_c_storage
{
protected:
typedef std::basic_string string_type;
string_type am_pm_[2];
virtual const string_type* am_pm() const;
virtual const string_type& c() const;
virtual const string_type& r() const;
virtual const string_type& x() const;
virtual const string_type& X() const;
public:
time_get_c_storage(const std::locale& loc);
~time_get_c_storage() {}
};
template<>
time_get_c_storage::time_get_c_storage(const std::locale& loc)
{
std::basic_ostringstream os;
const std::time_put &tp = std::use_facet< std::time_put >(loc);
std::tm tm;
tm.tm_sec = 0;
tm.tm_min = 0;
tm.tm_hour = 11;
tm.tm_mday = 0;
tm.tm_mon = 0;
tm.tm_year = 0;
tm.tm_wday = 0;
tm.tm_yday = 0;
tm.tm_isdst = -1;
std::ostreambuf_iterator out(os);
tp.put(out, os, ' ', &tm, 'p');
am_pm_[0] = os.str();
os.str("");
std::ostreambuf_iterator out2(os);
tm.tm_hour = 13;
tp.put(out2, os, ' ', &tm, 'p');
am_pm_[1] = os.str();
}
template<>
time_get_c_storage::time_get_c_storage(const std::locale& loc)
{
std::basic_ostringstream os;
const std::time_put &tp = std::use_facet< std::time_put< wchar_t > >(loc);
std::tm tm;
tm.tm_sec = 0;
tm.tm_min = 0;
tm.tm_hour = 11;
tm.tm_mday = 0;
tm.tm_mon = 0;
tm.tm_year = 0;
tm.tm_wday = 0;
tm.tm_yday = 0;
tm.tm_isdst = -1;
std::ostreambuf_iterator out(os);
tp.put(out, os, L' ', &tm, L'p');
am_pm_[0] = os.str();
os.str(L"");
std::ostreambuf_iterator out2(os);
tm.tm_hour = 13;
tp.put(out2, os, L' ', &tm, L'p');
am_pm_[1] = os.str();
}
template <>
const std::string*
time_get_c_storage::am_pm() const
{
return am_pm_;
}
template <>
const std::wstring*
time_get_c_storage::am_pm() const
{
return am_pm_;
}
template <>
const std::string&
time_get_c_storage::x() const
{
static std::string s("%m/%d/%y");
return s;
}
template <>
const std::wstring&
time_get_c_storage::x() const
{
static std::wstring s(L"%m/%d/%y");
return s;
}
template <>
const std::string&
time_get_c_storage::X() const
{
static std::string s("%H:%M:%S");
return s;
}
template <>
const std::wstring&
time_get_c_storage::X() const
{
static std::wstring s(L"%H:%M:%S");
return s;
}
template <>
const std::string&
time_get_c_storage::c() const
{
static std::string s("%a %b %d %H:%M:%S %Y");
return s;
}
template <>
const std::wstring&
time_get_c_storage::c() const
{
static std::wstring s(L"%a %b %d %H:%M:%S %Y");
return s;
}
template <>
const std::string&
time_get_c_storage::r() const
{
static std::string s("%I:%M:%S %p");
return s;
}
template <>
const std::wstring&
time_get_c_storage::r() const
{
static std::wstring s(L"%I:%M:%S %p");
return s;
}
template
class time_parser : public time_get_c_storage
{
private:
const std::time_get &tg_;
public:
typedef CharT char_type;
typedef InputIterator iter_type;
typedef std::time_base::dateorder dateorder;
typedef std::basic_string string_type;
time_parser(const std::locale& loc) : time_get_c_storage(loc),
tg_(std::use_facet< std::time_get >(loc))
{
}
iter_type get(iter_type b, iter_type e, std::ios_base& iob,
std::ios_base::iostate& err, tm *tm,
char fmt, char mod = 0) const
{
return do_get(b, e, iob, err, tm, fmt, mod);
}
iter_type get(iter_type b, iter_type e, std::ios_base& iob,
std::ios_base::iostate& err, tm* tm,
const char_type* fmtb, const char_type* fmte) const;
private:
InputIterator do_get(iter_type b, iter_type e,
std::ios_base& iob,
std::ios_base::iostate& err, tm* tm,
char fmt, char) const;
void get_white_space(iter_type& b, iter_type e,
std::ios_base::iostate& err, const std::ctype& ct) const;
void get_percent(iter_type& b, iter_type e, std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_day(int& d,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_month(int& m,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_year(int& y,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_year4(int& y,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_hour(int& d,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_12_hour(int& h,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_am_pm(int& h,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_minute(int& m,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_second(int& s,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_weekday(int& w,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
void get_day_year_num(int& w,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const;
};
template
void
time_parser::get_day(int& d,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 2);
if (!(err & std::ios_base::failbit) && 1 <= t && t <= 31)
d = t;
else
{
err |= std::ios_base::failbit;
}
}
template
void
time_parser::get_month(int& m,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 2) - 1;
if (!(err & std::ios_base::failbit) && t <= 11)
m = t;
else
{
err |= std::ios_base::failbit;
}
}
template
void
time_parser::get_year(int& y,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 4);
if (!(err & std::ios_base::failbit))
{
if (t < 69)
t += 2000;
else if (69 <= t && t <= 99)
t += 1900;
y = t - 1900;
}
}
template
void
time_parser::get_year4(int& y,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 4);
if (!(err & std::ios_base::failbit))
y = t - 1900;
}
template
void
time_parser::get_hour(int& h,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 2);
if (!(err & std::ios_base::failbit) && t <= 23)
h = t;
else
{
err |= std::ios_base::failbit;
}
}
template
void
time_parser::get_12_hour(int& h,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 2);
if (!(err & std::ios_base::failbit) && 1 <= t && t <= 12)
h = t;
else
{
err |= std::ios_base::failbit;
}
}
template
void
time_parser::get_minute(int& m,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 2);
if (!(err & std::ios_base::failbit) && t <= 59)
m = t;
else
{
err |= std::ios_base::failbit;
}
}
template
void
time_parser::get_second(int& s,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 2);
if (!(err & std::ios_base::failbit) && t <= 60)
s = t;
else
{
err |= std::ios_base::failbit;
}
}
template
void
time_parser::get_weekday(int& w,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 1);
if (!(err & std::ios_base::failbit) && t <= 6)
w = t;
else
err |= std::ios_base::failbit;
}
template
void
time_parser::get_day_year_num(int& d,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
int t = get_up_to_n_digits(b, e, err, ct, 3);
if (!(err & std::ios_base::failbit) && t <= 365)
d = t;
else
{
err |= std::ios_base::failbit;
}
}
template
void
time_parser::get_white_space(iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
for (; b != e && ct.is(std::ctype_base::space, *b); ++b)
;
if (b == e)
err |= std::ios_base::eofbit;
}
template
void
time_parser::get_am_pm(int& h,
iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
const string_type* ap = this->am_pm();
if (ap[0].size() + ap[1].size() == 0)
{
err |= std::ios_base::failbit;
return;
}
std::ptrdiff_t i = scan_keyword(b, e, ap, ap+2, ct, err, false) - ap;
if (i == 0 && h == 12)
h = 0;
else if (i == 1 && h < 12)
h += 12;
}
template
void
time_parser::get_percent(iter_type& b, iter_type e,
std::ios_base::iostate& err,
const std::ctype& ct) const
{
if (b == e)
{
err |= std::ios_base::eofbit | std::ios_base::failbit;
return;
}
if (ct.narrow(*b, 0) != '%')
{
err |= std::ios_base::failbit;
}
else if(++b == e)
{
err |= std::ios_base::eofbit;
}
}
template
InputIterator
time_parser::get(iter_type b, iter_type e,
std::ios_base& iob,
std::ios_base::iostate& err, tm* tm,
const char_type* fmtb, const char_type* fmte) const
{
const std::ctype& ct = std::use_facet >(iob.getloc());
err = std::ios_base::goodbit;
while (fmtb != fmte && err == std::ios_base::goodbit)
{
if (b == e)
{
err = std::ios_base::failbit;
break;
}
if (ct.narrow(*fmtb, 0) == '%')
{
if (++fmtb == fmte)
{
err = std::ios_base::failbit;
break;
}
char cmd = ct.narrow(*fmtb, 0);
char opt = '\0';
if (cmd == 'E' || cmd == '0')
{
if (++fmtb == fmte)
{
err = std::ios_base::failbit;
break;
}
opt = cmd;
cmd = ct.narrow(*fmtb, 0);
}
b = do_get(b, e, iob, err, tm, cmd, opt);
++fmtb;
}
else if (ct.is(std::ctype_base::space, *fmtb))
{
for (++fmtb; fmtb != fmte && ct.is(std::ctype_base::space, *fmtb); ++fmtb)
;
for ( ; b != e && ct.is(std::ctype_base::space, *b); ++b)
;
}
else if (ct.toupper(*b) == ct.toupper(*fmtb))
{
++b;
++fmtb;
}
else
{
err = std::ios_base::failbit;
}
}
if (b == e)
err |= std::ios_base::eofbit;
return b;
}
template
InputIterator
time_parser::do_get(iter_type b, iter_type e,
std::ios_base& iob,
std::ios_base::iostate& err, tm* tm,
char fmt, char) const
{
err = std::ios_base::goodbit;
const std::ctype& ct = std::use_facet >(iob.getloc());
switch (fmt)
{
case 'a':
case 'A':
b = tg_.get_weekday(b, e, iob, err, tm);
break;
case 'b':
case 'B':
case 'h':
b = tg_.get_monthname(b, e, iob, err, tm);
break;
case 'c':
{
const string_type& fm = this->c();
b = get(b, e, iob, err, tm, fm.data(), fm.data() + fm.size());
}
break;
case 'd':
case 'e':
get_day(tm->tm_mday, b, e, err, ct);
break;
case 'D':
{
const char_type fm[] = {'%', 'm', '/', '%', 'd', '/', '%', 'y'};
b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0]));
}
break;
case 'F':
{
const char_type fm[] = {'%', 'Y', '-', '%', 'm', '-', '%', 'd'};
b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0]));
}
break;
case 'H':
get_hour(tm->tm_hour, b, e, err, ct);
break;
case 'I':
get_12_hour(tm->tm_hour, b, e, err, ct);
break;
case 'j':
get_day_year_num(tm->tm_yday, b, e, err, ct);
break;
case 'm':
get_month(tm->tm_mon, b, e, err, ct);
break;
case 'M':
get_minute(tm->tm_min, b, e, err, ct);
break;
case 'n':
case 't':
get_white_space(b, e, err, ct);
break;
case 'p':
get_am_pm(tm->tm_hour, b, e, err, ct);
break;
case 'r':
{
const char_type fm[] = {'%', 'I', ':', '%', 'M', ':', '%', 'S', ' ', '%', 'p'};
b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0]));
}
break;
case 'R':
{
const char_type fm[] = {'%', 'H', ':', '%', 'M'};
b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0]));
}
break;
case 'S':
get_second(tm->tm_sec, b, e, err, ct);
break;
case 'T':
{
const char_type fm[] = {'%', 'H', ':', '%', 'M', ':', '%', 'S'};
b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0]));
}
break;
case 'w':
get_weekday(tm->tm_wday, b, e, err, ct);
break;
case 'x':
return tg_.get_date(b, e, iob, err, tm);
case 'X':
{
const string_type& fm = this->X();
b = get(b, e, iob, err, tm, fm.data(), fm.data() + fm.size());
}
break;
case 'y':
get_year(tm->tm_year, b, e, err, ct);
break;
case 'Y':
get_year4(tm->tm_year, b, e, err, ct);
break;
case '%':
get_percent(b, e, err, ct);
break;
default:
err |= std::ios_base::failbit;
}
return b;
}
template class iom_t9;
template
std::basic_istream&
operator>>(std::basic_istream& is, const iom_t9& x);
template
class iom_t9
{
tm* tm_;
const CharT* fmt_;
public:
iom_t9(tm* tm, const CharT* fmt)
: tm_(tm), fmt_(fmt) {}
template
friend
std::basic_istream<_Cp, Traits>&
operator>>(std::basic_istream<_Cp, Traits>& is, const iom_t9<_Cp>& x);
};
template
std::basic_istream&
operator>>(std::basic_istream& is, const iom_t9& x)
{
typename std::basic_istream::sentry s(is);
if (s)
{
typedef std::istreambuf_iterator _Ip;
typedef time_parser _Fp;
std::ios_base::iostate err = std::ios_base::goodbit;
const _Fp tf(is.getloc());
tf.get(_Ip(is), _Ip(), is, err, x.tm_,
x.fmt_, x.fmt_ + Traits::length(x.fmt_));
is.setstate(err);
}
return is;
}
template
inline
iom_t9
get_time(tm* tm, const CharT* fmt)
{
return iom_t9(tm, fmt);
}
}
#endif
RcppCCTZ/src/RcppExports_snippet.h 0000644 0001762 0000144 00000001362 13723003175 016640 0 ustar ligges users /* The following needs to be preserved in the call to R_init_RcppCCTZ:
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_getOffset", (DL_FUNC) &_RcppCCTZ_getOffset);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToCivilSecond", (DL_FUNC) &_RcppCCTZ_convertToCivilSecond);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToTimePoint", (DL_FUNC) &_RcppCCTZ_convertToTimePoint);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_getOffset_nothrow", (DL_FUNC) &_RcppCCTZ_getOffset_nothrow);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToCivilSecond_nothrow", (DL_FUNC) &_RcppCCTZ_convertToCivilSecond_nothrow);
R_RegisterCCallable("RcppCCTZ", "_RcppCCTZ_convertToTimePoint_nothrow", (DL_FUNC) &_RcppCCTZ_convertToTimePoint_nothrow);
*/
RcppCCTZ/src/Makevars.win 0000755 0001762 0000144 00000000042 14412065517 014725 0 ustar ligges users
PKG_CXXFLAGS = -I../inst/include
RcppCCTZ/src/zone_info_source.cc 0000644 0001762 0000144 00000007747 14271014541 016324 0 ustar ligges users // Copyright 2016 Google Inc. All Rights Reserved.
//
// 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
//
// https://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 "cctz/zone_info_source.h"
namespace cctz {
// Defined out-of-line to avoid emitting a weak vtable in all TUs.
ZoneInfoSource::~ZoneInfoSource() {}
std::string ZoneInfoSource::Version() const { return std::string(); }
} // namespace cctz
namespace cctz_extension {
namespace {
// A default for cctz_extension::zone_info_source_factory, which simply
// defers to the fallback factory.
std::unique_ptr DefaultFactory(
const std::string& name,
const std::function(
const std::string& name)>& fallback_factory) {
return fallback_factory(name);
}
} // namespace
// A "weak" definition for cctz_extension::zone_info_source_factory.
// The user may override this with their own "strong" definition (see
// zone_info_source.h).
#if !defined(__has_attribute)
#define __has_attribute(x) 0
#endif
// MinGW is GCC on Windows, so while it asserts __has_attribute(weak), the
// Windows linker cannot handle that. Nor does the MinGW compiler know how to
// pass "#pragma comment(linker, ...)" to the Windows linker.
#if (__has_attribute(weak) || defined(__GNUC__)) && !defined(__MINGW32__)
ZoneInfoSourceFactory zone_info_source_factory
__attribute__((weak)) = DefaultFactory;
#elif defined(_MSC_VER) && !defined(__MINGW32__) && !defined(_LIBCPP_VERSION)
extern ZoneInfoSourceFactory zone_info_source_factory;
extern ZoneInfoSourceFactory default_factory;
ZoneInfoSourceFactory default_factory = DefaultFactory;
#if defined(_M_IX86) || defined(_M_ARM)
#pragma comment( \
linker, \
"/alternatename:?zone_info_source_factory@cctz_extension@@3P6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@3@ABV?$function@$$A6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z@3@@ZA=?default_factory@cctz_extension@@3P6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@3@ABV?$function@$$A6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z@3@@ZA")
#elif defined(_M_IA_64) || defined(_M_AMD64) || defined(_M_ARM64)
#pragma comment( \
linker, \
"/alternatename:?zone_info_source_factory@cctz_extension@@3P6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@3@AEBV?$function@$$A6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z@3@@ZEA=?default_factory@cctz_extension@@3P6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@3@AEBV?$function@$$A6A?AV?$unique_ptr@VZoneInfoSource@cctz@@U?$default_delete@VZoneInfoSource@cctz@@@std@@@std@@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z@3@@ZEA")
#else
#error Unsupported MSVC platform
#endif // _M_
#else
// Make it a "strong" definition if we have no other choice.
ZoneInfoSourceFactory zone_info_source_factory = DefaultFactory;
#endif
} // namespace cctz_extension
RcppCCTZ/src/time_zone_format.cc 0000644 0001762 0000144 00000076522 14271014541 016314 0 ustar ligges users // Copyright 2016 Google Inc. All Rights Reserved.
//
// 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
//
// https://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.
#if !defined(HAS_STRPTIME)
# if !defined(_MSC_VER) && !defined(__MINGW32__)
# define HAS_STRPTIME 1 // assume everyone has strptime() except windows
# endif
#endif
#if defined(HAS_STRPTIME) && HAS_STRPTIME
# if !defined(_XOPEN_SOURCE) && !defined(__OpenBSD__)
# define _XOPEN_SOURCE // Definedness suffices for strptime.
# endif
#endif
#include "cctz/time_zone.h"
// Include time.h directly since, by C++ standards, ctime doesn't have to
// declare strptime.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#if !HAS_STRPTIME
#include
#include
#endif
#include "cctz/civil_time.h"
#include "time_zone_if.h"
namespace cctz {
namespace detail {
namespace {
#if !HAS_STRPTIME
// Build a strptime() using C++11's std::get_time().
char* strptime(const char* s, const char* fmt, std::tm* tm) {
std::istringstream input(s);
input >> std::get_time(tm, fmt);
if (input.fail()) return nullptr;
return const_cast(s) +
(input.eof() ? strlen(s) : static_cast(input.tellg()));
}
#endif
// Convert a cctz::weekday to a tm_wday value (0-6, Sunday = 0).
int ToTmWday(weekday wd) {
switch (wd) {
case weekday::sunday:
return 0;
case weekday::monday:
return 1;
case weekday::tuesday:
return 2;
case weekday::wednesday:
return 3;
case weekday::thursday:
return 4;
case weekday::friday:
return 5;
case weekday::saturday:
return 6;
}
return 0; /*NOTREACHED*/
}
// Convert a tm_wday value (0-6, Sunday = 0) to a cctz::weekday.
weekday FromTmWday(int tm_wday) {
switch (tm_wday) {
case 0:
return weekday::sunday;
case 1:
return weekday::monday;
case 2:
return weekday::tuesday;
case 3:
return weekday::wednesday;
case 4:
return weekday::thursday;
case 5:
return weekday::friday;
case 6:
return weekday::saturday;
}
return weekday::sunday; /*NOTREACHED*/
}
std::tm ToTM(const time_zone::absolute_lookup& al) {
std::tm tm{};
tm.tm_sec = al.cs.second();
tm.tm_min = al.cs.minute();
tm.tm_hour = al.cs.hour();
tm.tm_mday = al.cs.day();
tm.tm_mon = al.cs.month() - 1;
// Saturate tm.tm_year is cases of over/underflow.
if (al.cs.year() < std::numeric_limits::min() + 1900) {
tm.tm_year = std::numeric_limits::min();
} else if (al.cs.year() - 1900 > std::numeric_limits::max()) {
tm.tm_year = std::numeric_limits::max();
} else {
tm.tm_year = static_cast(al.cs.year() - 1900);
}
tm.tm_wday = ToTmWday(get_weekday(al.cs));
tm.tm_yday = get_yearday(al.cs) - 1;
tm.tm_isdst = al.is_dst ? 1 : 0;
return tm;
}
// Returns the week of the year [0:53] given a civil day and the day on
// which weeks are defined to start.
int ToWeek(const civil_day& cd, weekday week_start) {
const civil_day d(cd.year() % 400, cd.month(), cd.day());
return static_cast((d - prev_weekday(civil_year(d), week_start)) / 7);
}
const char kDigits[] = "0123456789";
// Formats a 64-bit integer in the given field width. Note that it is up
// to the caller of Format64() [and Format02d()/FormatOffset()] to ensure
// that there is sufficient space before ep to hold the conversion.
char* Format64(char* ep, int width, std::int_fast64_t v) {
bool neg = false;
if (v < 0) {
--width;
neg = true;
if (v == std::numeric_limits::min()) {
// Avoid negating minimum value.
std::int_fast64_t last_digit = -(v % 10);
v /= 10;
if (last_digit < 0) {
++v;
last_digit += 10;
}
--width;
*--ep = kDigits[last_digit];
}
v = -v;
}
do {
--width;
*--ep = kDigits[v % 10];
} while (v /= 10);
while (--width >= 0) *--ep = '0'; // zero pad
if (neg) *--ep = '-';
return ep;
}
// Formats [0 .. 99] as %02d.
char* Format02d(char* ep, int v) {
*--ep = kDigits[v % 10];
*--ep = kDigits[(v / 10) % 10];
return ep;
}
// Formats a UTC offset, like +00:00.
char* FormatOffset(char* ep, int offset, const char* mode) {
// TODO: Follow the RFC3339 "Unknown Local Offset Convention" and
// generate a "negative zero" when we're formatting a zero offset
// as the result of a failed load_time_zone().
char sign = '+';
if (offset < 0) {
offset = -offset; // bounded by 24h so no overflow
sign = '-';
}
const int seconds = offset % 60;
const int minutes = (offset /= 60) % 60;
const int hours = offset /= 60;
const char sep = mode[0];
const bool ext = (sep != '\0' && mode[1] == '*');
const bool ccc = (ext && mode[2] == ':');
if (ext && (!ccc || seconds != 0)) {
ep = Format02d(ep, seconds);
*--ep = sep;
} else {
// If we're not rendering seconds, sub-minute negative offsets
// should get a positive sign (e.g., offset=-10s => "+00:00").
if (hours == 0 && minutes == 0) sign = '+';
}
if (!ccc || minutes != 0 || seconds != 0) {
ep = Format02d(ep, minutes);
if (sep != '\0') *--ep = sep;
}
ep = Format02d(ep, hours);
*--ep = sign;
return ep;
}
// Formats a std::tm using strftime(3).
void FormatTM(std::string* out, const std::string& fmt, const std::tm& tm) {
// strftime(3) returns the number of characters placed in the output
// array (which may be 0 characters). It also returns 0 to indicate
// an error, like the array wasn't large enough. To accommodate this,
// the following code grows the buffer size from 2x the format string
// length up to 32x.
for (std::size_t i = 2; i != 32; i *= 2) {
std::size_t buf_size = fmt.size() * i;
std::vector buf(buf_size);
if (std::size_t len = strftime(&buf[0], buf_size, fmt.c_str(), &tm)) {
out->append(&buf[0], len);
return;
}
}
}
// Used for %E#S/%E#f specifiers and for data values in parse().
template
const char* ParseInt(const char* dp, int width, T min, T max, T* vp) {
if (dp != nullptr) {
const T kmin = std::numeric_limits::min();
bool erange = false;
bool neg = false;
T value = 0;
if (*dp == '-') {
neg = true;
if (width <= 0 || --width != 0) {
++dp;
} else {
dp = nullptr; // width was 1
}
}
if (const char* const bp = dp) {
while (const char* cp = strchr(kDigits, *dp)) {
int d = static_cast(cp - kDigits);
if (d >= 10) break;
if (value < kmin / 10) {
erange = true;
break;
}
value *= 10;
if (value < kmin + d) {
erange = true;
break;
}
value -= d;
dp += 1;
if (width > 0 && --width == 0) break;
}
if (dp != bp && !erange && (neg || value != kmin)) {
if (!neg || value != 0) {
if (!neg) value = -value; // make positive
if (min <= value && value <= max) {
*vp = value;
} else {
dp = nullptr;
}
} else {
dp = nullptr;
}
} else {
dp = nullptr;
}
}
}
return dp;
}
// The number of base-10 digits that can be represented by a signed 64-bit
// integer. That is, 10^kDigits10_64 <= 2^63 - 1 < 10^(kDigits10_64 + 1).
const int kDigits10_64 = 18;
// 10^n for everything that can be represented by a signed 64-bit integer.
const std::int_fast64_t kExp10[kDigits10_64 + 1] = {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000,
};
} // namespace
// Uses strftime(3) to format the given Time. The following extended format
// specifiers are also supported:
//
// - %Ez - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm)
// - %E*z - Full-resolution numeric UTC offset (+hh:mm:ss or -hh:mm:ss)
// - %E#S - Seconds with # digits of fractional precision
// - %E*S - Seconds with full fractional precision (a literal '*')
// - %E4Y - Four-character years (-999 ... -001, 0000, 0001 ... 9999)
// - %ET - The RFC3339 "date-time" separator "T"
//
// The standard specifiers from RFC3339_* (%Y, %m, %d, %H, %M, and %S) are
// handled internally for performance reasons. strftime(3) is slow due to
// a POSIX requirement to respect changes to ${TZ}.
//
// The TZ/GNU %s extension is handled internally because strftime() has
// to use mktime() to generate it, and that assumes the local time zone.
//
// We also handle the %z and %Z specifiers to accommodate platforms that do
// not support the tm_gmtoff and tm_zone extensions to std::tm.
//
// Requires that zero() <= fs < seconds(1).
std::string format(const std::string& format, const time_point& tp,
const detail::femtoseconds& fs, const time_zone& tz) {
std::string result;
result.reserve(format.size()); // A reasonable guess for the result size.
const time_zone::absolute_lookup al = tz.lookup(tp);
const std::tm tm = ToTM(al);
// Scratch buffer for internal conversions.
char buf[3 + kDigits10_64]; // enough for longest conversion
char* const ep = buf + sizeof(buf);
char* bp; // works back from ep
// Maintain three, disjoint subsequences that span format.
// [format.begin() ... pending) : already formatted into result
// [pending ... cur) : formatting pending, but no special cases
// [cur ... format.end()) : unexamined
// Initially, everything is in the unexamined part.
const char* pending = format.c_str(); // NUL terminated
const char* cur = pending;
const char* end = pending + format.length();
while (cur != end) { // while something is unexamined
// Moves cur to the next percent sign.
const char* start = cur;
while (cur != end && *cur != '%') ++cur;
// If the new pending text is all ordinary, copy it out.
if (cur != start && pending == start) {
result.append(pending, static_cast(cur - pending));
pending = start = cur;
}
// Span the sequential percent signs.
const char* percent = cur;
while (cur != end && *cur == '%') ++cur;
// If the new pending text is all percents, copy out one
// percent for every matched pair, then skip those pairs.
if (cur != start && pending == start) {
std::size_t escaped = static_cast(cur - pending) / 2;
result.append(pending, escaped);
pending += escaped * 2;
// Also copy out a single trailing percent.
if (pending != cur && cur == end) {
result.push_back(*pending++);
}
}
// Loop unless we have an unescaped percent.
if (cur == end || (cur - percent) % 2 == 0) continue;
// Simple specifiers that we handle ourselves.
if (strchr("YmdeUuWwHMSzZs%", *cur)) {
if (cur - 1 != pending) {
FormatTM(&result, std::string(pending, cur - 1), tm);
}
switch (*cur) {
case 'Y':
// This avoids the tm.tm_year overflow problem for %Y, however
// tm.tm_year will still be used by other specifiers like %D.
bp = Format64(ep, 0, al.cs.year());
result.append(bp, static_cast(ep - bp));
break;
case 'm':
bp = Format02d(ep, al.cs.month());
result.append(bp, static_cast(ep - bp));
break;
case 'd':
case 'e':
bp = Format02d(ep, al.cs.day());
if (*cur == 'e' && *bp == '0') *bp = ' '; // for Windows
result.append(bp, static_cast(ep - bp));
break;
case 'U':
bp = Format02d(ep, ToWeek(civil_day(al.cs), weekday::sunday));
result.append(bp, static_cast(ep - bp));
break;
case 'u':
bp = Format64(ep, 0, tm.tm_wday ? tm.tm_wday : 7);
result.append(bp, static_cast(ep - bp));
break;
case 'W':
bp = Format02d(ep, ToWeek(civil_day(al.cs), weekday::monday));
result.append(bp, static_cast(ep - bp));
break;
case 'w':
bp = Format64(ep, 0, tm.tm_wday);
result.append(bp, static_cast(ep - bp));
break;
case 'H':
bp = Format02d(ep, al.cs.hour());
result.append(bp, static_cast(ep - bp));
break;
case 'M':
bp = Format02d(ep, al.cs.minute());
result.append(bp, static_cast(ep - bp));
break;
case 'S':
bp = Format02d(ep, al.cs.second());
result.append(bp, static_cast