1/*
2 * Copyright (c) 2021-2023 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
16import util from '@ohos.util'
17
18/**
19 * 字符串工具类
20 */
21namespace StringUtil {
22
23/**
24 * 字符串是否为空
25 * @param str 字符串
26 * @return 是否为空
27 */
28    export function isEmpty(str: string): boolean {
29        return!str || str.length === 0
30    }
31
32    /**
33     * 将字符串转换成Uint8Array类型
34     * @param str 字符串
35     * @return 无符号整型数组
36     */
37    export function convert2Uint8Array(str: string): Uint8Array {
38        if (isEmpty(str)) {
39            return new Uint8Array()
40        }
41        return new util.TextEncoder().encode(str)
42    }
43
44    /**
45     * 将字符串做base64编码
46     * @param str 字符串
47     * @return Base64字符串
48     */
49    export function convert2Base64(str: string): string {
50        if (isEmpty(str)) {
51            return ''
52        }
53        const array = convert2Uint8Array(str)
54        return new util.Base64().encodeToStringSync(array)
55    }
56
57    /**
58     * 字符串头部补全
59     * @param num 待补全字符串
60     * @param maxLen 补全后字符串的最大长度
61     * @param placeholder 占位符
62     * @return 不全后的字符串,如:1=>01
63     */
64    export function padStart(num: number | string, maxLen = 2, placeholder = '0') {
65        return num.toString().padStart(maxLen, placeholder)
66    }
67
68    /**
69     * 获得字符串字节长度
70     * @param str 字符串
71     * @return 字节长度
72     */
73    export function getBytesCount(str: string): number {
74        let bytesCount = 0
75        if (str) {
76            for (let i = 0; i < str.length; i++) {
77                const char = str.charAt(i)
78                if (char.match(/[^\x00-\xff]/ig) != null) {
79                    // 汉字占用字节数和编码有关,utf-8编码:占3个字节,GB2312编码:占2个字节
80                    bytesCount += 3
81                } else {
82                    bytesCount += 1
83                }
84            }
85        }
86        return bytesCount
87    }
88}
89
90export default StringUtil
91