DAW JSON Link
Loading...
Searching...
No Matches
daw_json_parse_iso8601_utils.h
Go to the documentation of this file.
1// Copyright (c) Darrell Wright
2//
3// Distributed under the Boost Software License, Version 1.0. (See accompanying
4// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
5//
6// Official repository: https://github.com/beached/daw_json_link
7//
8
9#pragma once
10
12
16
17#include <daw/daw_arith_traits.h>
18#include <daw/daw_attributes.h>
19#include <daw/daw_cpp_feature_check.h>
20#include <daw/daw_cxmath.h>
21#include <daw/daw_not_null.h>
22#include <daw/daw_string_view.h>
23#include <daw/daw_traits.h>
24#include <daw/daw_uint_buffer.h>
25
26#include <cassert>
27#include <chrono>
28#include <cstdint>
29#include <type_traits>
30
31namespace daw::json {
32 inline namespace DAW_JSON_VER {
33 namespace parse_utils {
34 template<typename Result, std::size_t count>
35 constexpr Result parse_unsigned( daw::not_null<char const *> digit_str ) {
36 auto result = UInt64( );
37 for( std::size_t n = 0; n < count; ++n ) {
38 auto const dig =
39 to_uint64( json_details::parse_digit( digit_str[n] ) );
40 if( dig >= 10 ) {
41 break;
42 }
43 result *= 10U;
44 result += dig;
45 }
46 return static_cast<Result>( result );
47 }
48
49 template<typename Result>
50 constexpr Result
51 parse_unsigned2( daw::not_null<char const *> digit_str ) {
52 auto result = UInt64( );
53 unsigned dig = json_details::parse_digit( *digit_str );
54 while( dig < 10 ) {
55 result *= 10U;
56 result += dig;
57 ++digit_str;
58 dig = json_details::parse_digit( *digit_str );
59 }
60 return static_cast<Result>( result );
61 }
62
63 DAW_ATTRIB_FLATINLINE constexpr bool is_number( char c ) {
64 return json_details::parse_digit( c ) < 10U;
65 }
66 } // namespace parse_utils
67
68 namespace datetime {
69 using attoseconds = std::chrono::duration<std::int64_t, std::atto>;
70
71 namespace datetime_details {
72 template<typename Result>
73 constexpr Result parse_number( daw::string_view sv ) {
74 static_assert( daw::digits10<Result> >= 4 );
75 daw_json_ensure( not sv.empty( ), ErrorReason::InvalidNumber );
76 Result result = 0;
77 Result sign = 1;
78 if( sv.front( ) == '-' ) {
79 if constexpr( daw::is_signed_v<Result> ) {
80 sign = -1;
81 }
82 sv.remove_prefix( );
83 } else if( sv.front( ) == '+' ) {
84 sv.remove_prefix( );
85 }
86 while( not sv.empty( ) ) {
87 auto const dig = json_details::parse_digit( sv.pop_front( ) );
88 daw_json_ensure( dig < 10U, ErrorReason::InvalidNumber );
89 result *= 10;
90 result += static_cast<Result>( dig );
91 }
92 return result * sign;
93 }
94 } // namespace datetime_details
95 // See:
96 // https://stackoverflow.com/questions/16773285/how-to-convert-stdchronotime-point-to-stdtm-without-using-time-t
97 template<typename TP = std::chrono::time_point<std::chrono::system_clock,
98 std::chrono::milliseconds>>
99 constexpr TP civil_to_time_point( std::int32_t yr, std::uint32_t mo,
100 std::uint32_t dy, std::uint32_t hr,
101 std::uint32_t mn, std::uint32_t se,
102 std::uint64_t attosecond ) {
103 using Clock = typename TP::clock;
104 using Duration = typename TP::duration;
105 DAW_CPP23_STATIC_LOCAL constexpr auto calc =
106 []( std::int32_t y,
107 std::uint32_t m,
108 std::uint32_t d,
109 std::uint32_t h,
110 std::uint32_t min,
111 std::uint32_t s,
112 std::uint64_t atto ) DAW_JSON_CPP23_STATIC_CALL_OP {
113 y -= static_cast<std::int32_t>( m ) <= 2;
114 std::int32_t const era = ( y >= 0 ? y : y - 399 ) / 400;
115 auto const yoe = static_cast<std::uint32_t>(
116 static_cast<std::int32_t>( y ) - era * 400 ); // [0, 399]
117 auto const doy = static_cast<std::uint32_t>(
118 ( 153 * ( static_cast<std::int32_t>( m ) +
119 ( static_cast<std::int32_t>( m ) > 2 ? -3 : 9 ) ) +
120 2 ) /
121 5 +
122 static_cast<std::int32_t>( d ) - 1 ); // [0, 365]
123 std::uint32_t const doe =
124 yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
125 auto const days_since_epoch =
126 static_cast<int64_t>( era ) * 146097LL +
127 static_cast<std::int64_t>( doe ) - 719468LL;
128
129 auto const dur = std::chrono::floor<Duration>(
130 attoseconds( static_cast<std::int64_t>( atto ) ) );
131 auto const whole_seconds =
132 std::chrono::seconds( days_since_epoch * 86400LL +
133 static_cast<std::int64_t>( h ) * 3600LL +
134 static_cast<std::int64_t>( min ) * 60LL +
135 static_cast<std::int64_t>( s ) );
136 return std::chrono::time_point<std::chrono::system_clock,
137 Duration>{ } +
138 ( std::chrono::duration_cast<Duration>( whole_seconds ) +
139 dur );
140 };
141 // Not all clocks have the same epoch. This should account for the
142 // offset and adjust the time_point so that the days prior are in
143 // relation to unix epoch. If system_clock is used, as is the default
144 // for the return value, it will be zero and should be removed by the
145 // compiler
146 auto result = calc( yr, mo, dy, hr, mn, se, attosecond );
147
148 if constexpr( std::is_same_v<Clock, std::chrono::system_clock> ) {
149 return result;
150 } else {
151#if defined( __cpp_lib_chrono ) and __cpp_lib_chrono >= 201907
152 // We have clock_cast
153 auto const match_duration =
154 std::chrono::time_point_cast<Duration>( result );
155 auto const match_clock =
156 std::chrono::clock_cast<Clock>( match_duration );
157 return match_clock;
158#else
159 // This is a guess and will not be constexpr
160
161 // System epoch is unix epoch on(gcc/clang/msvc)
162 auto const system_epoch = std::chrono::floor<std::chrono::hours>(
163 std::chrono::system_clock::now( ).time_since_epoch( ) +
164 std::chrono::minutes( 30 ) );
165 auto const clock_epoch = std::chrono::floor<std::chrono::hours>(
166 Clock::now( ).time_since_epoch( ) + std::chrono::minutes( 30 ) );
167
168 DAW_CPP23_STATIC_LOCAL constexpr auto offset =
169 std::chrono::duration_cast<std::chrono::milliseconds>(
170 clock_epoch - system_epoch );
171 return std::chrono::duration_cast<Duration>( result + offset );
172#endif
173 }
174 }
175
176 struct date_parts {
177 std::int32_t year;
178 std::uint32_t month;
179 std::uint32_t day;
180 };
181
182 constexpr date_parts
183 parse_iso_8601_date( daw::string_view timestamp_str ) {
184 auto result = date_parts{ 0, 0, 0 };
185 result.day = parse_utils::parse_unsigned<std::uint_least32_t, 2>(
186 std::data( timestamp_str.pop_back( 2U ) ) );
187 daw_json_ensure( result.day >= 1 and result.day <= 31,
188 ErrorReason::InvalidTimestamp );
189 if( not parse_utils::is_number( timestamp_str.back( ) ) ) {
190 timestamp_str.remove_suffix( );
191 }
192 result.month = parse_utils::parse_unsigned<std::uint_least32_t, 2>(
193 std::data( timestamp_str.pop_back( 2U ) ) );
194 daw_json_ensure( result.month >= 1 and result.month <= 12,
195 ErrorReason::InvalidTimestamp );
196 if( not parse_utils::is_number( timestamp_str.back( ) ) ) {
197 timestamp_str.remove_suffix( );
198 }
199 result.year =
200 datetime_details::parse_number<std::int_least32_t>( timestamp_str );
201 return result;
202 }
203
204 struct time_parts {
205 std::uint_least32_t hour;
206 std::uint_least32_t minute;
207 std::uint_least32_t second;
208 std::uint64_t attosecond;
209 };
210
211 constexpr time_parts
212 parse_iso_8601_time( daw::string_view timestamp_str ) {
213 auto result = time_parts{ 0, 0, 0, 0 };
214 result.hour = parse_utils::parse_unsigned<std::uint_least32_t, 2>(
215 std::data( timestamp_str.pop_front( 2 ) ) );
216 daw_json_ensure( result.hour <= 24, ErrorReason::InvalidTimestamp );
217 if( not parse_utils::is_number( timestamp_str.front( ) ) ) {
218 timestamp_str.remove_prefix( );
219 }
220 result.minute = parse_utils::parse_unsigned<std::uint_least32_t, 2>(
221 std::data( timestamp_str.pop_front( 2 ) ) );
222 daw_json_ensure( result.minute <= 59, ErrorReason::InvalidTimestamp );
223 if( timestamp_str.empty( ) ) {
224 return result;
225 }
226 if( not parse_utils::is_number( timestamp_str.front( ) ) ) {
227 timestamp_str.remove_prefix( );
228 }
229 result.second = parse_utils::parse_unsigned<std::uint_least32_t, 2>(
230 std::data( timestamp_str.pop_front( 2 ) ) );
231 daw_json_ensure( result.second <= 60, ErrorReason::InvalidTimestamp );
232 if( timestamp_str.empty( ) ) {
233 return result;
234 }
235 daw_json_ensure( timestamp_str.front( ) == '.',
236 ErrorReason::InvalidTimestamp );
237 timestamp_str.remove_prefix( );
238 daw_json_ensure( not timestamp_str.empty( ),
239 ErrorReason::InvalidTimestamp );
240 for( char const c : timestamp_str ) {
241 daw_json_ensure( parse_utils::is_number( c ),
242 ErrorReason::InvalidTimestamp );
243 }
244 auto const precision =
245 std::min( timestamp_str.size( ), std::size_t{ 18 } );
246 auto const attosecond_str = timestamp_str.substr( 0, precision );
247 result.attosecond =
248 datetime_details::parse_number<std::uint64_t>( attosecond_str );
249 result.attosecond *= daw::cxmath::pow10( 18 - precision );
250 return result;
251 }
252
253 template<typename TP>
254 constexpr TP parse_iso8601_timestamp( daw::string_view ts ) {
255 DAW_CPP23_STATIC_LOCAL constexpr daw::string_view t_str = "T";
256 auto const date_str = ts.pop_front_until( t_str );
257 if( ts.empty( ) ) {
259 true,
260 ErrorReason::InvalidTimestamp ); // Invalid timestamp,
261 // missing T separator
262 }
263
264 date_parts const ymd = parse_iso_8601_date( date_str );
265 auto time_str =
266 ts.pop_front_until( []( char c ) DAW_JSON_CPP23_STATIC_CALL_OP {
267 return not( parse_utils::is_number( c ) | ( c == ':' ) |
268 ( c == '.' ) );
269 } );
270 // TODO: verify or parse timezone
271 auto hms = parse_iso_8601_time( time_str );
272 if( not( ts.empty( ) or ts.front( ) == 'Z' ) ) {
273 daw_json_ensure( std::size( ts ) == 5 or std::size( ts ) == 6,
274 ErrorReason::InvalidTimestamp );
275 // The format will be (+|-)hh[:]mm
276 bool sign = false;
277 daw_json_ensure( not ts.empty( ), ErrorReason::InvalidTimestamp );
278 switch( ts.front( ) ) {
279 case '+':
280 sign = true;
281 break;
282 case '-':
283 break;
284 default:
285 daw_json_error( true, daw::json::ErrorReason::InvalidTimestamp );
286 }
287 ts.remove_prefix( );
288 auto hr_offset = parse_utils::parse_unsigned<std::uint_least32_t, 2>(
289 std::data( ts ) );
290 daw_json_ensure( hr_offset <= 24,
291 daw::json::ErrorReason::InvalidTimestamp );
292 if( ts.front( ) == ':' ) {
293 ts.remove_prefix( );
294 }
295 auto mn_offset = parse_utils::parse_unsigned<std::uint_least32_t, 2>(
296 std::data( ts ) );
297 daw_json_ensure( mn_offset <= 61,
298 daw::json::ErrorReason::InvalidTimestamp );
299 // Want to subtract offset from current time, we are converting to UTC
300 if( sign ) {
301 // Positive offset
302 hms.hour -= hr_offset;
303 hms.minute -= mn_offset;
304 } else {
305 // Negative offset
306 hms.hour += hr_offset;
307 hms.minute += mn_offset;
308 }
309 }
310 return civil_to_time_point<TP>( ymd.year,
311 ymd.month,
312 ymd.day,
313 hms.hour,
314 hms.minute,
315 hms.second,
316 hms.attosecond );
317 }
318 struct ymdhms {
319 std::int_least32_t year;
320 std::uint_least32_t month;
321 std::uint_least32_t day;
322 std::uint_least32_t hour;
323 std::uint_least32_t minute;
324 std::uint_least32_t second;
325 std::uint64_t attosecond;
326 };
327
328 template<typename Clock, typename Duration>
329 constexpr ymdhms
330 time_point_to_civil( std::chrono::time_point<Clock, Duration> const tp ) {
331 auto dur_from_epoch = tp.time_since_epoch( );
332 using Days =
333 std::chrono::duration<std::int_least32_t, std::ratio<86400>>;
334 auto const whole_seconds =
335 std::chrono::floor<std::chrono::seconds>( dur_from_epoch );
336 auto const days_since_epoch = std::chrono::floor<Days>( whole_seconds );
337 std::int_least32_t z = days_since_epoch.count( );
338 z += 719468;
339 std::int_least32_t const era = ( z >= 0 ? z : z - 146096 ) / 146097;
340 auto const doe =
341 static_cast<std::uint_least32_t>( z - era * 146097 ); // [0, 146096]
342 std::uint_least32_t const yoe =
343 ( doe - doe / 1460 + doe / 36524 - doe / 146096 ) / 365; // [0, 399]
344 std::int_least32_t const y =
345 static_cast<std::int_least32_t>( yoe ) + era * 400;
346 std::uint_least32_t const doy =
347 doe - ( 365 * yoe + yoe / 4 - yoe / 100 ); // [0, 365]
348 std::uint_least32_t const mp = ( 5 * doy + 2 ) / 153; // [0, 11]
349 std::uint_least32_t const d = doy - ( 153 * mp + 2 ) / 5 + 1; // [1, 31]
350 auto const m = static_cast<std::uint_least32_t>(
351 static_cast<std::int_least32_t>( mp ) +
352 ( static_cast<std::int_least32_t>( mp ) < 10 ? 3 : -9 ) ); // [1, 12]
353
354 auto dur_in_day =
355 whole_seconds -
356 std::chrono::duration_cast<std::chrono::seconds>( days_since_epoch );
357 auto const hrs =
358 std::chrono::duration_cast<std::chrono::hours>( dur_in_day );
359 dur_in_day -= hrs;
360 auto const min =
361 std::chrono::duration_cast<std::chrono::minutes>( dur_in_day );
362 dur_in_day -= min;
363 auto const sec =
364 std::chrono::duration_cast<std::chrono::seconds>( dur_in_day );
365 auto const subseconds =
366 dur_from_epoch -
367 std::chrono::duration_cast<Duration>( whole_seconds );
368 auto const dur = std::chrono::duration_cast<attoseconds>( subseconds );
369 return ymdhms{ y + ( m <= 2 ),
370 m,
371 d,
372 static_cast<std::uint_least32_t>( hrs.count( ) ),
373 static_cast<std::uint_least32_t>( min.count( ) ),
374 static_cast<std::uint_least32_t>( sec.count( ) ),
375 static_cast<std::uint64_t>( dur.count( ) ) };
376 }
377
378 constexpr std::string_view month_short_name( unsigned m ) {
379 switch( m ) {
380 case 1:
381 return { "Jan" };
382 case 2:
383 return { "Feb" };
384 case 3:
385 return { "Mar" };
386 case 4:
387 return { "Apr" };
388 case 5:
389 return { "May" };
390 case 6:
391 return { "Jun" };
392 case 7:
393 return { "Jul" };
394 case 8:
395 return { "Aug" };
396 case 9:
397 return { "Sep" };
398 case 10:
399 return { "Oct" };
400 case 11:
401 return { "Nov" };
402 case 12:
403 return { "Dec" };
404 default:
405 DAW_UNLIKELY_BRANCH
406 daw_json_error( true,
407 ErrorReason::InvalidTimestamp ); // Invalid month
408 }
409 }
410
411 // Formula from
412 // http://howardhinnant.github.io/date_algorithms.html#weekday_from_days
413 template<typename Duration>
414 constexpr std::string_view short_day_of_week(
415 std::chrono::time_point<std::chrono::system_clock, Duration> tp ) {
416 using days = std::chrono::duration<long, std::ratio<86400>>;
417 auto const z =
418 std::chrono::duration_cast<days>( tp.time_since_epoch( ) ).count( );
419 auto const dow = z >= -4L ? ( z + 4L ) % 7L : ( z + 5L ) % 7L + 6L;
420 switch( dow ) {
421 case 0:
422 return { "Sun" };
423 case 1:
424 return { "Mon" };
425 case 2:
426 return { "Tue" };
427 case 3:
428 return { "Wed" };
429 case 4:
430 return { "Thu" };
431 case 5:
432 return { "Fri" };
433 case 6:
434 return { "Sat" };
435 default:
436 DAW_UNLIKELY_BRANCH
437 daw_json_error( true,
438 ErrorReason::InvalidTimestamp ); // Invalid month
439 }
440 }
441
442 namespace datetime_details {
443 constexpr std::uint_least32_t month2num( std::string_view ts ) {
444 daw_json_ensure( std::size( ts ) >= 3,
445 ErrorReason::InvalidTimestamp );
446 auto const b0 = static_cast<std::uint_least32_t>(
447 static_cast<unsigned char>( ts[0] ) );
448 auto const b1 = static_cast<std::uint_least32_t>(
449 static_cast<unsigned char>( ts[1] ) );
450 auto const b2 = static_cast<std::uint_least32_t>(
451 static_cast<unsigned char>( ts[2] ) );
452 return ( b0 << 16U ) | ( b1 << 8U ) | b2;
453 }
454 } // namespace datetime_details
455
456 constexpr unsigned parse_short_month( std::string_view ts ) {
457 // Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
458 switch( datetime_details::month2num( ts ) ) {
459 case datetime_details::month2num( "Jan" ):
460 return 1;
461 case datetime_details::month2num( "Feb" ):
462 return 2;
463 case datetime_details::month2num( "Mar" ):
464 return 3;
465 case datetime_details::month2num( "Apr" ):
466 return 4;
467 case datetime_details::month2num( "May" ):
468 return 5;
469 case datetime_details::month2num( "Jun" ):
470 return 6;
471 case datetime_details::month2num( "Jul" ):
472 return 7;
473 case datetime_details::month2num( "Aug" ):
474 return 8;
475 case datetime_details::month2num( "Sep" ):
476 return 9;
477 case datetime_details::month2num( "Oct" ):
478 return 10;
479 case datetime_details::month2num( "Nov" ):
480 return 11;
481 case datetime_details::month2num( "Dec" ):
482 return 12;
483 default:
484 DAW_UNLIKELY_BRANCH
485 daw_json_error( true,
486 ErrorReason::InvalidTimestamp ); // Invalid month
487 }
488 }
489 } // namespace datetime
490 } // namespace DAW_JSON_VER
491} // namespace daw::json
#define daw_json_ensure(Bool,...)
Ensure that Bool is true. If false pass rest of args to daw_json_error.
#define DAW_JSON_CPP23_STATIC_CALL_OP
DAW_ATTRIB_NOINLINE void daw_json_error(bool b, ErrorReason reason)
constexpr std::string_view short_day_of_week(std::chrono::time_point< std::chrono::system_clock, Duration > tp)
constexpr ymdhms time_point_to_civil(std::chrono::time_point< Clock, Duration > const tp)
constexpr TP civil_to_time_point(std::int32_t yr, std::uint32_t mo, std::uint32_t dy, std::uint32_t hr, std::uint32_t mn, std::uint32_t se, std::uint64_t attosecond)
constexpr Result parse_unsigned(daw::not_null< char const * > digit_str)
constexpr Result parse_unsigned2(daw::not_null< char const * > digit_str)
Customization point traits.
#define DAW_JSON_VER
The version string used in namespace definitions. Must be a valid namespace name.
Definition version.h:20