1#ifndef AWS_COMMON_CLOCK_INL
2#define AWS_COMMON_CLOCK_INL
3
4/*
5 * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License").
8 * You may not use this file except in compliance with the License.
9 * A copy of the License is located at
10 *
11 * http://aws.amazon.com/apache2.0
12 *
13 * or in the "license" file accompanying this file. This file is distributed
14 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
15 * express or implied. See the License for the specific language governing
16 * permissions and limitations under the License.
17 */
18
19#include <aws/common/clock.h>
20#include <aws/common/common.h>
21#include <aws/common/math.h>
22
23AWS_EXTERN_C_BEGIN
24
25/**
26 * Converts 'timestamp' from unit 'convert_from' to unit 'convert_to', if the units are the same then 'timestamp' is
27 * returned. If 'remainder' is NOT NULL, it will be set to the remainder if convert_from is a more precise unit than
28 * convert_to. To avoid unnecessary branching, 'remainder' is not zero initialized in this function, be sure to set it
29 * to 0 first if you care about that kind of thing. If conversion would lead to integer overflow, the timestamp
30 * returned will be the highest possible time that is representable, i.e. UINT64_MAX.
31 */
32AWS_STATIC_IMPL uint64_t aws_timestamp_convert(
33 uint64_t timestamp,
34 enum aws_timestamp_unit convert_from,
35 enum aws_timestamp_unit convert_to,
36 uint64_t *remainder) {
37 uint64_t diff = 0;
38
39 if (convert_to > convert_from) {
40 diff = convert_to / convert_from;
41 return aws_mul_u64_saturating(timestamp, diff);
42 } else if (convert_to < convert_from) {
43 diff = convert_from / convert_to;
44
45 if (remainder) {
46 *remainder = timestamp % diff;
47 }
48
49 return timestamp / diff;
50 } else {
51 return timestamp;
52 }
53}
54
55AWS_EXTERN_C_END
56
57#endif /* AWS_COMMON_CLOCK_INL */
58