1 /*
2 * Copyright (c) 2020 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "time_util.h"
17 #include <stdlib.h>
18 #include <string.h>
19 #include "ace_mem_base.h"
20 #include "js_fwk_common.h"
21
22 namespace OHOS {
23 namespace ACELite {
24 constexpr char CHAR_M = 'm';
25 constexpr char CHAR_S = 's';
26 constexpr int32_t MILLIONS_PER_SECOND = 1000;
27 constexpr uint8_t IDX_PENULT = 2;
ParseToMilliseconds(const char * time)28 int32_t ParseToMilliseconds(const char *time)
29 {
30 if ((time == nullptr) || (strlen(time) == 0)) {
31 return 0;
32 }
33 size_t size = strlen(time);
34 if (size >= UINT8_MAX) {
35 return 0;
36 }
37 int32_t milliseconds = 0;
38 if (size == 1) {
39 milliseconds = strtol(time, nullptr, DEC);
40 return (milliseconds < 0) ? 0 : milliseconds;
41 }
42
43 size_t bufSize = size;
44 char last = time[size - 1];
45 char penult = time[size - IDX_PENULT];
46 bool isSecond = false;
47 if (penult == CHAR_M && last == CHAR_S) {
48 bufSize = size - IDX_PENULT;
49 } else if (last == CHAR_S) {
50 bufSize = size - 1;
51 isSecond = true;
52 }
53 if (bufSize == 0) {
54 return 0;
55 }
56
57 char *buffer = static_cast<char *>(ace_malloc(bufSize + 1));
58 if (buffer == nullptr) {
59 return 0;
60 }
61 if (strncpy_s(buffer, bufSize + 1, time, bufSize) == 0) {
62 buffer[bufSize] = '\0';
63 milliseconds = isSecond ? (int32_t)((strtod(buffer, nullptr) * MILLIONS_PER_SECOND)) :
64 (int32_t)(strtol(buffer, nullptr, DEC));
65 }
66 ace_free(buffer);
67 buffer = nullptr;
68 return (milliseconds < 0) ? 0 : milliseconds;
69 }
70 } // namespace ACELite
71 } // namespace OHOS
72