-
Notifications
You must be signed in to change notification settings - Fork 34
/
genutils.c
1853 lines (1630 loc) · 55.4 KB
/
genutils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Generic utility routines
*
* This file is part of the miniSEED Library.
*
* Copyright (c) 2024 Chad Trabant, EarthScope Data Services
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "gmtime64.h"
#include "libmseed.h"
static nstime_t ms_time2nstime_int (int year, int day, int hour,
int min, int sec, uint32_t nsec);
/** @cond UNDOCUMENTED */
/* Global set of allocation functions, defaulting to system malloc(), realloc() and free() */
LIBMSEED_MEMORY libmseed_memory = { .malloc = malloc, .realloc = realloc, .free = free };
/* Global pre-allocation block size, default 1 MiB on Windows, disabled otherwise */
#if defined(LMP_WIN)
size_t libmseed_prealloc_block_size = 1048576;
#else
size_t libmseed_prealloc_block_size = 0;
#endif
/* Internal realloc() wrapper that allocates in libmseed_prealloc_block_size blocks */
void *
libmseed_memory_prealloc (void *ptr, size_t size, size_t *currentsize)
{
size_t newsize;
void *newptr;
if (!currentsize)
return NULL;
if (libmseed_prealloc_block_size == 0)
return NULL;
/* No additional memory needed if request already satisfied */
if (size < *currentsize)
return ptr;
/* Calculate new size needed for request by adding blocks */
newsize = *currentsize + libmseed_prealloc_block_size;
while (newsize < size)
newsize += libmseed_prealloc_block_size;
newptr = libmseed_memory.realloc (ptr, newsize);
if (newptr)
*currentsize = newsize;
return newptr;
}
/* A constant number of seconds between the NTP and POSIX/Unix time epoch */
#define NTPPOSIXEPOCHDELTA 2208988800LL
#define NTPEPOCH2NSTIME(X) (MS_EPOCH2NSTIME (X - NTPPOSIXEPOCHDELTA))
/* Embedded leap second list, good through: 28 December 2023 */
static LeapSecond embedded_leapsecondlist[] = {
{.leapsecond = NTPEPOCH2NSTIME (2272060800), .TAIdelta = 10, .next = &embedded_leapsecondlist[1]},
{.leapsecond = NTPEPOCH2NSTIME (2287785600), .TAIdelta = 11, .next = &embedded_leapsecondlist[2]},
{.leapsecond = NTPEPOCH2NSTIME (2303683200), .TAIdelta = 12, .next = &embedded_leapsecondlist[3]},
{.leapsecond = NTPEPOCH2NSTIME (2335219200), .TAIdelta = 13, .next = &embedded_leapsecondlist[4]},
{.leapsecond = NTPEPOCH2NSTIME (2366755200), .TAIdelta = 14, .next = &embedded_leapsecondlist[5]},
{.leapsecond = NTPEPOCH2NSTIME (2398291200), .TAIdelta = 15, .next = &embedded_leapsecondlist[6]},
{.leapsecond = NTPEPOCH2NSTIME (2429913600), .TAIdelta = 16, .next = &embedded_leapsecondlist[7]},
{.leapsecond = NTPEPOCH2NSTIME (2461449600), .TAIdelta = 17, .next = &embedded_leapsecondlist[8]},
{.leapsecond = NTPEPOCH2NSTIME (2492985600), .TAIdelta = 18, .next = &embedded_leapsecondlist[9]},
{.leapsecond = NTPEPOCH2NSTIME (2524521600), .TAIdelta = 19, .next = &embedded_leapsecondlist[10]},
{.leapsecond = NTPEPOCH2NSTIME (2571782400), .TAIdelta = 20, .next = &embedded_leapsecondlist[11]},
{.leapsecond = NTPEPOCH2NSTIME (2603318400), .TAIdelta = 21, .next = &embedded_leapsecondlist[12]},
{.leapsecond = NTPEPOCH2NSTIME (2634854400), .TAIdelta = 22, .next = &embedded_leapsecondlist[13]},
{.leapsecond = NTPEPOCH2NSTIME (2698012800), .TAIdelta = 23, .next = &embedded_leapsecondlist[14]},
{.leapsecond = NTPEPOCH2NSTIME (2776982400), .TAIdelta = 24, .next = &embedded_leapsecondlist[15]},
{.leapsecond = NTPEPOCH2NSTIME (2840140800), .TAIdelta = 25, .next = &embedded_leapsecondlist[16]},
{.leapsecond = NTPEPOCH2NSTIME (2871676800), .TAIdelta = 26, .next = &embedded_leapsecondlist[17]},
{.leapsecond = NTPEPOCH2NSTIME (2918937600), .TAIdelta = 27, .next = &embedded_leapsecondlist[18]},
{.leapsecond = NTPEPOCH2NSTIME (2950473600), .TAIdelta = 28, .next = &embedded_leapsecondlist[19]},
{.leapsecond = NTPEPOCH2NSTIME (2982009600), .TAIdelta = 29, .next = &embedded_leapsecondlist[20]},
{.leapsecond = NTPEPOCH2NSTIME (3029443200), .TAIdelta = 30, .next = &embedded_leapsecondlist[21]},
{.leapsecond = NTPEPOCH2NSTIME (3076704000), .TAIdelta = 31, .next = &embedded_leapsecondlist[22]},
{.leapsecond = NTPEPOCH2NSTIME (3124137600), .TAIdelta = 32, .next = &embedded_leapsecondlist[23]},
{.leapsecond = NTPEPOCH2NSTIME (3345062400), .TAIdelta = 33, .next = &embedded_leapsecondlist[24]},
{.leapsecond = NTPEPOCH2NSTIME (3439756800), .TAIdelta = 34, .next = &embedded_leapsecondlist[25]},
{.leapsecond = NTPEPOCH2NSTIME (3550089600), .TAIdelta = 35, .next = &embedded_leapsecondlist[26]},
{.leapsecond = NTPEPOCH2NSTIME (3644697600), .TAIdelta = 36, .next = &embedded_leapsecondlist[27]},
{.leapsecond = NTPEPOCH2NSTIME (3692217600), .TAIdelta = 37, .next = NULL}};
/* Global variable to hold a leap second list */
LeapSecond *leapsecondlist = &embedded_leapsecondlist[0];
/* Days in each month, for non-leap and leap years */
static const int monthdays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static const int monthdays_leap[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/* Determine if year is a leap year */
#define LEAPYEAR(year) (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
/* Check that a year is in a valid range */
#define VALIDYEAR(year) (year >= 1678 && year <= 2262)
/* Check that a month is in a valid range */
#define VALIDMONTH(month) (month >= 1 && month <= 12)
/* Check that a day-of-month is in a valid range */
#define VALIDMONTHDAY(year, month, mday) (mday >= 0 && mday <= (LEAPYEAR (year) ? monthdays_leap[month - 1] : monthdays[month - 1]))
/* Check that a day-of-year is in a valid range */
#define VALIDYEARDAY(year, yday) (yday >= 1 && yday <= (365 + (LEAPYEAR (year) ? 1 : 0)))
/* Check that an hour is in a valid range */
#define VALIDHOUR(hour) (hour >= 0 && hour <= 23)
/* Check that a minute is in a valid range */
#define VALIDMIN(min) (min >= 0 && min <= 59)
/* Check that a second is in a valid range */
#define VALIDSEC(sec) (sec >= 0 && sec <= 60)
/* Check that a nanosecond is in a valid range */
#define VALIDNANOSEC(nanosec) (nanosec <= 999999999)
/** @endcond */
/**********************************************************************/ /**
* @brief Parse network, station, location and channel from an FDSN Source ID
*
* FDSN Source Identifiers are defined at:
* https://docs.fdsn.org/projects/source-identifiers/
*
* Parse a source identifier into separate components, expecting:
* \c "FDSN:NET_STA_LOC_CHAN", where \c CHAN="BAND_SOURCE_POSITION"
*
* The CHAN value will be converted to a SEED channel code if
* possible. Meaning, if the BAND, SOURCE, and POSITION are single
* characters, the underscore delimiters will not be included in the
* returned channel.
*
* Identifiers may contain additional namespace identifiers, e.g.:
* \c "FDSN:AGENCY:NET_STA_LOC_CHAN"
*
* Such additional namespaces are not part of the Source ID standard
* as of this writing and support is included for specialized usage or
* future identifier changes.
*
* Memory for each component must already be allocated. If a specific
* component is not desired set the appropriate argument to NULL.
*
* @param[in] sid Source identifier
* @param[out] net Network code
* @param[out] sta Station code
* @param[out] loc Location code
* @param[out] chan Channel code
*
* @retval 0 on success
* @retval -1 on error
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
ms_sid2nslc (const char *sid, char *net, char *sta, char *loc, char *chan)
{
size_t idlen;
const char *cid;
char *id;
char *ptr, *top, *next;
int sepcnt = 0;
if (!sid)
{
ms_log (2, "%s(): Required input not defined: 'sid'\n", __func__);
return -1;
}
/* Handle the FDSN: namespace identifier */
if (!strncmp (sid, "FDSN:", 5))
{
/* Advance sid pointer to last ':', skipping all namespace identifiers */
sid = strrchr (sid, ':') + 1;
/* Verify 5 delimiters */
cid = sid;
while ((cid = strchr (cid, '_')))
{
cid++;
sepcnt++;
}
if (sepcnt != 5)
{
ms_log (2, "Incorrect number of identifier delimiters (%d): %s\n", sepcnt, sid);
return -1;
}
idlen = strlen (sid) + 1;
if (!(id = libmseed_memory.malloc (idlen)))
{
ms_log (2, "Error duplicating identifier\n");
return -1;
}
memcpy (id, sid, idlen);
/* Network */
top = id;
if ((ptr = strchr (top, '_')))
{
next = ptr + 1;
*ptr = '\0';
if (net)
strcpy (net, top);
top = next;
}
/* Station */
if ((ptr = strchr (top, '_')))
{
next = ptr + 1;
*ptr = '\0';
if (sta)
strcpy (sta, top);
top = next;
}
/* Location, potentially empty */
if ((ptr = strchr (top, '_')))
{
next = ptr + 1;
*ptr = '\0';
if (loc)
strcpy (loc, top);
top = next;
}
/* Channel */
if (*top && chan)
{
/* Map extended channel to SEED channel if possible, otherwise direct copy */
if (ms_xchan2seedchan(chan, top))
{
strcpy (chan, top);
}
}
/* Free duplicated ID */
if (id)
libmseed_memory.free (id);
}
else
{
ms_log (2, "Unrecognized identifier: %s\n", sid);
return -1;
}
return 0;
} /* End of ms_sid2nslc() */
/**********************************************************************/ /**
* @brief Convert network, station, location and channel to an FDSN Source ID
*
* FDSN Source Identifiers are defined at:
* https://docs.fdsn.org/projects/source-identifiers/
*
* Create a source identifier from individual network,
* station, location and channel codes with the form:
* \c FDSN:NET_STA_LOC_CHAN, where \c CHAN="BAND_SOURCE_POSITION"
*
* Memory for the source identifier must already be allocated.
*
* If the \a loc value is NULL it will be empty in the resulting Source ID.
*
* The \a chan value will be converted to extended channel format if
* it appears to be in SEED channel form. Meaning, if the \a chan is
* 3 characters with no delimiters, it will be converted to \c
* "BAND_SOURCE_POSITION" form by adding delimiters between the codes.
*
* @param[out] sid Destination string for source identifier
* @param sidlen Maximum length of \a sid
* @param flags Currently unused, set to 0
* @param[in] net Network code
* @param[in] sta Station code
* @param[in] loc Location code
* @param[in] chan Channel code
*
* @returns length of source identifier
* @retval -1 on error
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
ms_nslc2sid (char *sid, int sidlen, uint16_t flags,
const char *net, const char *sta, const char *loc, const char *chan)
{
(void)flags; /* Unused */
char *sptr = sid;
char xchan[6] = {0};
int needed = 0;
if (!sid || !net || !sta || !chan)
{
ms_log (2, "%s(): Required input not defined: sid,net,sta,chan\n", __func__);
return -1;
}
if (sidlen < 16)
{
ms_log (2, "Length of destination SID buffer must be at least 16 bytes\n");
return -1;
}
*sptr++ = 'F';
*sptr++ = 'D';
*sptr++ = 'S';
*sptr++ = 'N';
*sptr++ = ':';
needed = 5;
/* Network code */
while (*net)
{
if ((sptr - sid) < sidlen)
*sptr++ = *net;
net++;
needed++;
}
if ((sptr - sid) < sidlen)
*sptr++ = '_';
needed++;
/* Station code */
while (*sta)
{
if ((sptr - sid) < sidlen)
*sptr++ = *sta;
sta++;
needed++;
}
if ((sptr - sid) < sidlen)
*sptr++ = '_';
needed++;
/* Location code, may be empty */
if (loc)
{
while (*loc)
{
if ((sptr - sid) < sidlen)
*sptr++ = *loc;
loc++;
needed++;
}
}
if ((sptr - sid) < sidlen)
*sptr++ = '_';
needed++;
/* Map SEED channel to extended channel if possible, otherwise direct copy */
if (!ms_seedchan2xchan (xchan, chan))
{
chan = xchan;
}
/* Channel code */
while (*chan)
{
if ((sptr - sid) < sidlen)
*sptr++ = *chan;
chan++;
needed++;
}
/* Terminate: at the end of the ID or end of the buffer */
if ((sptr - sid) < sidlen)
*sptr = '\0';
else
*--sptr = '\0';
/* A byte is needed for the terminator */
needed++;
if (needed > sidlen)
{
ms_log (2, "Provided SID destination (%d bytes) is not big enough for the needed %d bytes\n",
sidlen, needed);
return -1;
}
return (int)(sptr - sid);
} /* End of ms_nslc2sid() */
/**********************************************************************/ /**
* @brief Convert SEED 2.x channel to extended channel
*
* The SEED 2.x channel at \a seedchan must be a 3-character string.
* The \a xchan buffer must be at least 6 bytes, for the extended
* channel (band,source,position) and the terminating NULL.
*
* This functionality simply maps patterns, it does not check the
* validity of any codes.
*
* @param[out] xchan Destination for extended channel string, must be at least 6 bytes
* @param[in] seedchan Source string, must be a 3-character string
*
* @retval 0 on successful mapping of channel
* @retval -1 on error
***************************************************************************/
int
ms_seedchan2xchan (char *xchan, const char *seedchan)
{
if (!seedchan || !xchan)
return -1;
if (seedchan[0] &&
seedchan[1] &&
seedchan[2] &&
seedchan[3] == '\0')
{
xchan[0] = seedchan[0]; /* Band code */
xchan[1] = '_';
xchan[2] = seedchan[1]; /* Source (aka instrument) code */
xchan[3] = '_';
xchan[4] = seedchan[2]; /* Position (aka orientation) code */
xchan[5] = '\0';
return 0;
}
return -1;
} /* End of ms_seedchan2xchan() */
/**********************************************************************/ /**
* @brief Convert extended channel to SEED 2.x channel
*
* The extended channel at \a xchan must be a 5-character string.
*
* The \a seedchan buffer must be at least 4 bytes, for the SEED
* channel and the terminating NULL. Alternatively, \a seedchan may
* be set to NULL in which case this function becomes a test for
* whether the \a xchan _could_ be mapped without actually doing the
* conversion. Finally, \a seedchan can be the same buffer as \a
* xchan for an in-place conversion.
*
* This routine simply maps patterns, it does not check the validity
* of any specific codes.
*
* @param[out] seedchan Destination for SEED channel string, must be at least 4 bytes
* @param[in] xchan Source string, must be a 5-character string
*
* @retval 0 on successful mapping of channel
* @retval -1 on error
***************************************************************************/
int
ms_xchan2seedchan (char *seedchan, const char *xchan)
{
if (!xchan)
return -1;
if (xchan[0] &&
xchan[1] == '_' &&
xchan[2] &&
xchan[3] == '_' &&
xchan[4] &&
xchan[5] == '\0')
{
if (seedchan)
{
seedchan[0] = xchan[0]; /* Band code */
seedchan[1] = xchan[2]; /* Source (aka instrument) code */
seedchan[2] = xchan[4]; /* Position (aka orientation) code */
seedchan[3] = '\0';
}
return 0;
}
return -1;
} /* End of ms_xchan2seedchan() */
// For utf8d table and utf8length_int() basics:
// Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
static const uint8_t utf8d[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df
0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef
0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff
0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2
1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4
1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6
1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8
};
/***************************************************************************
* Determine length of UTF-8 bytes in string.
*
* Calculate the length of the string until either the maximum length,
* terminating NULL, or an invalid UTF-8 codepoint are reached.
*
* To determine if the length calculated stopped due to invalid UTF-8
* codepoint, the return value can be tested for maximum length and
* used to test for a terminating NULL, ala:
*
* length = utf8length_int (str, maxlength);
*
* if (length < maxlength && str[length])
* String contains invalid UTF-8 within maxlength bytes
*
* Returns the number of UTF-8 codepoint bytes (not including the null terminator).
***************************************************************************/
static int
utf8length_int (const char *str, int maxlength)
{
uint32_t state = 0;
uint32_t type;
int length = 0;
int offset;
for (offset = 0; str[offset] && offset < maxlength; offset++)
{
type = utf8d[(uint8_t)str[offset]];
state = utf8d[256 + state * 16 + type];
/* A valid codepoint was found, update length */
if (state == 0)
length = offset + 1;
}
return length;
} /* End of utf8length_int() */
/**********************************************************************/ /**
* @brief Copy string, removing spaces, always terminated
*
* Copy up to \a length bytes of UTF-8 characters from \a source to \a
* dest while removing all spaces. The result is left justified and
* always null terminated.
*
* The destination string must have enough room needed for the
* non-space characters within \a length and the null terminator, a
* maximum of \a length + 1.
*
* @param[out] dest Destination for terminated string
* @param[in] source Source string
* @param[in] length Length of characters for destination string in bytes
*
* @returns the number of characters (not including the null terminator) in
* the destination string
***************************************************************************/
int
ms_strncpclean (char *dest, const char *source, int length)
{
int sidx;
int didx;
if (!dest)
return 0;
if (!source)
{
*dest = '\0';
return 0;
}
length = utf8length_int (source, length);
for (sidx = 0, didx = 0; sidx < length; sidx++)
{
if (*(source + sidx) == '\0')
{
break;
}
if (*(source + sidx) != ' ')
{
*(dest + didx) = *(source + sidx);
didx++;
}
}
*(dest + didx) = '\0';
return didx;
} /* End of ms_strncpclean() */
/**********************************************************************/ /**
* @brief Copy string, removing trailing spaces, always terminated
*
* Copy up to \a length bytes of UTF-8 characters from \a source to \a
* dest without any trailing spaces. The result is left justified and
* always null terminated.
*
* The destination string must have enough room needed for the
* characters within \a length and the null terminator, a maximum of
* \a length + 1.
*
* @param[out] dest Destination for terminated string
* @param[in] source Source string
* @param[in] length Length of characters for destination string in bytes
*
* @returns The number of characters (not including the null terminator) in
* the destination string
***************************************************************************/
int
ms_strncpcleantail (char *dest, const char *source, int length)
{
int idx;
int pretail;
if (!dest)
return 0;
if (!source)
{
*dest = '\0';
return 0;
}
length = utf8length_int (source, length);
*(dest + length) = '\0';
pretail = 0;
for (idx = length - 1; idx >= 0; idx--)
{
if (!pretail && *(source + idx) == ' ')
{
*(dest + idx) = '\0';
}
else
{
pretail++;
*(dest + idx) = *(source + idx);
}
}
return pretail;
} /* End of ms_strncpcleantail() */
/**********************************************************************/ /**
* @brief Copy fixed number of characters into unterminated string
*
* Copy \a length bytes of UTF-8 characters from \a source to \a dest,
* padding the right side with spaces and leave open-ended, aka
* un-terminated. The result is left justified and \e never null
* terminated.
*
* The destination string must have enough room for \a length characters.
*
* @param[out] dest Destination for unterminated string
* @param[in] source Source string
* @param[in] length Length of characters for destination string in bytes
*
* @returns the number of characters copied from the source string
***************************************************************************/
int
ms_strncpopen (char *dest, const char *source, int length)
{
int didx;
int dcnt = 0;
int utf8max;
if (!dest)
return 0;
if (!source)
{
for (didx = 0; didx < length; didx++)
{
*(dest + didx) = ' ';
}
return 0;
}
utf8max = utf8length_int (source, length);
for (didx = 0; didx < length; didx++)
{
if (didx < utf8max)
{
*(dest + didx) = *(source + didx);
dcnt++;
}
else
{
*(dest + didx) = ' ';
}
}
return dcnt;
} /* End of ms_strncpopen() */
/**********************************************************************/ /**
* @brief Compute the month and day-of-month from a year and day-of-year
*
* @param[in] year Year in range 1000-2262
* @param[in] yday Day of year in range 1-365 or 366 for leap year
* @param[out] month Month in range 1-12
* @param[out] mday Day of month in range 1-31
*
* @retval 0 on success
* @retval -1 on error
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
ms_doy2md (int year, int yday, int *month, int *mday)
{
int idx;
const int(*days)[12];
if (!month || !mday)
{
ms_log (2, "%s(): Required input not defined: 'month' or 'mday'\n", __func__);
return -1;
}
if (!VALIDYEAR (year))
{
ms_log (2, "year (%d) is out of range\n", year);
return -1;
}
if (!VALIDYEARDAY (year, yday))
{
ms_log (2, "day-of-year (%d) is out of range for year %d\n", yday, year);
return -1;
}
days = (LEAPYEAR (year)) ? &monthdays_leap : &monthdays;
for (idx = 0; idx < 12; idx++)
{
yday -= (*days)[idx];
if (yday <= 0)
{
*month = idx + 1;
*mday = (*days)[idx] + yday;
break;
}
}
return 0;
} /* End of ms_doy2md() */
/**********************************************************************/ /**
* @brief Compute the day-of-year from a year, month and day-of-month
*
* @param[in] year Year in range 1000-2262
* @param[in] month Month in range 1-12
* @param[in] mday Day of month in range 1-31 (or appropriate last day)
* @param[out] yday Day of year in range 1-366 or 366 for leap year
*
* @retval 0 on success
* @retval -1 on error
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
ms_md2doy (int year, int month, int mday, int *yday)
{
int idx;
const int(*days)[12];
if (!yday)
{
ms_log (2, "%s(): Required input not defined: 'yday'\n", __func__);
return -1;
}
if (!VALIDYEAR (year))
{
ms_log (2, "year (%d) is out of range\n", year);
return -1;
}
if (!VALIDMONTH (month))
{
ms_log (2, "month (%d) is out of range\n", month);
return -1;
}
if (!VALIDMONTHDAY (year, month, mday))
{
ms_log (2, "day-of-month (%d) is out of range for year %d and month %d\n", mday, year, month);
return -1;
}
days = (LEAPYEAR (year)) ? &monthdays_leap : &monthdays;
*yday = 0;
month--;
for (idx = 0; idx < 12; idx++)
{
if (idx == month)
{
*yday += mday;
break;
}
*yday += (*days)[idx];
}
return 0;
} /* End of ms_md2doy() */
/**********************************************************************/ /**
* @brief Convert an ::nstime_t to individual date-time components
*
* Each of the destination date-time are optional, pass NULL if the
* value is not desired.
*
* @param[in] nstime Time value to convert
* @param[out] year Year with century, like 2018
* @param[out] yday Day of year, 1 - 366
* @param[out] hour Hour, 0 - 23
* @param[out] min Minute, 0 - 59
* @param[out] sec Second, 0 - 60, where 60 is a leap second
* @param[out] nsec Nanoseconds, 0 - 999999999
*
* @retval 0 on success
* @retval -1 on error
***************************************************************************/
int
ms_nstime2time (nstime_t nstime, uint16_t *year, uint16_t *yday,
uint8_t *hour, uint8_t *min, uint8_t *sec, uint32_t *nsec)
{
struct tm tms;
int64_t isec;
int32_t ifract;
/* Reduce to Unix/POSIX epoch time and fractional seconds */
isec = MS_NSTIME2EPOCH (nstime);
ifract = (int)(nstime - (isec * NSTMODULUS));
/* Adjust for negative epoch times */
if (nstime < 0 && ifract != 0)
{
isec -= 1;
ifract = NSTMODULUS - (-ifract);
}
if (year || yday || hour || min || sec)
if (!(ms_gmtime64_r (&isec, &tms)))
return -1;
if (year)
*year = tms.tm_year + 1900;
if (yday)
*yday = tms.tm_yday + 1;
if (hour)
*hour = tms.tm_hour;
if (min)
*min = tms.tm_min;
if (sec)
*sec = tms.tm_sec;
if (nsec)
*nsec = ifract;
return 0;
} /* End of ms_nstime2time() */
/**********************************************************************/ /**
* @brief Convert an ::nstime_t to a time string
*
* Create a time string representation of a high precision epoch time
* in ISO 8601 and SEED formats.
*
* The provided \a timestr buffer must have enough room for the
* resulting time string, a maximum of 36 characters + terminating NULL.
*
* The \a subseconds flag controls whether the subsecond portion of
* the time is included or not. The value of \a subseconds is ignored
* when the \a format is \c NANOSECONDEPOCH. When non-zero subseconds
* are "trimmed" using these flags there is no rounding, instead it is
* simple truncation.
*
* @param[in] nstime Time value to convert
* @param[out] timestr Buffer for ISO time string
* @param timeformat Time string format, one of @ref ms_timeformat_t
* @param subseconds Inclusion of subseconds, one of @ref ms_subseconds_t
*
* @returns Pointer to the resulting string or NULL on error.
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
char *
ms_nstime2timestr (nstime_t nstime, char *timestr,
ms_timeformat_t timeformat, ms_subseconds_t subseconds)
{
struct tm tms = {0};
int64_t rawisec;
int rawnanosec;
int64_t isec;
int nanosec;
int microsec;
int submicro;
int printed = 0;
int expected = 0;
if (!timestr)
{
ms_log (2, "%s(): Required input not defined: 'timestr'\n", __func__);
return NULL;
}
/* Reduce to Unix/POSIX epoch time and fractional nanoseconds */
isec = rawisec = MS_NSTIME2EPOCH (nstime);
nanosec = rawnanosec = (int)(nstime - (isec * NSTMODULUS));
/* Adjust for negative epoch times */
if (nstime < 0 && nanosec != 0)
{
isec -= 1;
nanosec = NSTMODULUS - (-nanosec);
rawnanosec *= -1;
}
/* Determine microsecond and sub-microsecond values */
microsec = nanosec / 1000;
submicro = nanosec - (microsec * 1000);
/* Calculate date-time parts if needed by format */
if (timeformat == ISOMONTHDAY || timeformat == ISOMONTHDAY_Z ||
timeformat == ISOMONTHDAY_DOY || timeformat == ISOMONTHDAY_DOY_Z ||
timeformat == ISOMONTHDAY_SPACE || timeformat == ISOMONTHDAY_SPACE_Z ||
timeformat == SEEDORDINAL)
{
if (!(ms_gmtime64_r (&isec, &tms)))
{
ms_log (2, "Error converting epoch-time of (%" PRId64 ") to date-time components\n", isec);
return NULL;
}
}
/* Print no subseconds */
if (subseconds == NONE ||
(subseconds == MICRO_NONE && microsec == 0) ||
(subseconds == NANO_NONE && nanosec == 0) ||
(subseconds == NANO_MICRO_NONE && nanosec == 0))
{
switch (timeformat)
{
case ISOMONTHDAY:
case ISOMONTHDAY_Z:
case ISOMONTHDAY_SPACE:
case ISOMONTHDAY_SPACE_Z:
expected = (timeformat == ISOMONTHDAY_Z || timeformat == ISOMONTHDAY_SPACE_Z) ? 20 : 19;
printed = snprintf (timestr, expected + 1, "%4d-%02d-%02d%c%02d:%02d:%02d%s",
tms.tm_year + 1900, tms.tm_mon + 1, tms.tm_mday,
(timeformat == ISOMONTHDAY_SPACE || timeformat == ISOMONTHDAY_SPACE_Z) ? ' ' : 'T',
tms.tm_hour, tms.tm_min, tms.tm_sec,
(timeformat == ISOMONTHDAY_Z || timeformat == ISOMONTHDAY_SPACE_Z) ? "Z" : "");
break;
case ISOMONTHDAY_DOY:
case ISOMONTHDAY_DOY_Z:
expected = (timeformat == ISOMONTHDAY_DOY_Z) ? 26 : 25;
printed = snprintf (timestr, expected + 1, "%4d-%02d-%02dT%02d:%02d:%02d%s (%03d)",
tms.tm_year + 1900, tms.tm_mon + 1, tms.tm_mday,
tms.tm_hour, tms.tm_min, tms.tm_sec,
(timeformat == ISOMONTHDAY_DOY_Z) ? "Z" : "",