termux-app

Форк
0
258 строк · 8.5 Кб
1
package com.termux.shared.data;
2

3
import android.os.Bundle;
4

5
import androidx.annotation.NonNull;
6
import androidx.annotation.Nullable;
7

8
import com.google.common.base.Strings;
9

10
import java.io.ByteArrayOutputStream;
11
import java.io.ObjectOutputStream;
12
import java.io.Serializable;
13
import java.util.Collections;
14

15
public class DataUtils {
16

17
    /** Max safe limit of data size to prevent TransactionTooLargeException when transferring data
18
     * inside or to other apps via transactions. */
19
    public static final int TRANSACTION_SIZE_LIMIT_IN_BYTES = 100 * 1024; // 100KB
20

21
    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
22

23
    public static String getTruncatedCommandOutput(String text, int maxLength, boolean fromEnd, boolean onNewline, boolean addPrefix) {
24
        if (text == null) return null;
25

26
        String prefix = "(truncated) ";
27

28
        if (addPrefix)
29
            maxLength = maxLength - prefix.length();
30

31
        if (maxLength < 0 || text.length() < maxLength) return text;
32

33
        if (fromEnd) {
34
            text = text.substring(0, maxLength);
35
        } else {
36
            int cutOffIndex = text.length() - maxLength;
37

38
            if (onNewline) {
39
                int nextNewlineIndex = text.indexOf('\n', cutOffIndex);
40
                if (nextNewlineIndex != -1 && nextNewlineIndex != text.length() - 1) {
41
                    cutOffIndex = nextNewlineIndex + 1;
42
                }
43
            }
44
            text = text.substring(cutOffIndex);
45
        }
46

47
        if (addPrefix)
48
            text = prefix + text;
49

50
        return text;
51
    }
52

53
    /**
54
     * Replace a sub string in each item of a {@link String[]}.
55
     *
56
     * @param array The {@link String[]} to replace in.
57
     * @param find The sub string to replace.
58
     * @param replace The sub string to replace with.
59
     */
60
    public static void replaceSubStringsInStringArrayItems(String[] array, String find, String replace) {
61
        if(array == null || array.length == 0) return;
62

63
        for (int i = 0; i < array.length; i++) {
64
            array[i] = array[i].replace(find, replace);
65
        }
66
    }
67

68
    /**
69
     * Get the {@code float} from a {@link String}.
70
     *
71
     * @param value The {@link String} value.
72
     * @param def The default value if failed to read a valid value.
73
     * @return Returns the {@code float} value after parsing the {@link String} value, otherwise
74
     * returns default if failed to read a valid value, like in case of an exception.
75
     */
76
    public static float getFloatFromString(String value, float def) {
77
        if (value == null) return def;
78

79
        try {
80
            return Float.parseFloat(value);
81
        }
82
        catch (Exception e) {
83
            return def;
84
        }
85
    }
86

87
    /**
88
     * Get the {@code int} from a {@link String}.
89
     *
90
     * @param value The {@link String} value.
91
     * @param def The default value if failed to read a valid value.
92
     * @return Returns the {@code int} value after parsing the {@link String} value, otherwise
93
     * returns default if failed to read a valid value, like in case of an exception.
94
     */
95
    public static int getIntFromString(String value, int def) {
96
        if (value == null) return def;
97

98
        try {
99
            return Integer.parseInt(value);
100
        }
101
        catch (Exception e) {
102
            return def;
103
        }
104
    }
105

106
    /**
107
     * Get the {@code String} from an {@link Integer}.
108
     *
109
     * @param value The {@link Integer} value.
110
     * @param def The default {@link String} value.
111
     * @return Returns {@code value} if it is not {@code null}, otherwise returns {@code def}.
112
     */
113
    public static String getStringFromInteger(Integer value, String def) {
114
        return (value == null) ? def : String.valueOf((int) value);
115
    }
116

117
    /**
118
     * Get the {@code hex string} from a {@link byte[]}.
119
     *
120
     * @param bytes The {@link byte[]} value.
121
     * @return Returns the {@code hex string} value.
122
     */
123
    public static String bytesToHex(byte[] bytes) {
124
        char[] hexChars = new char[bytes.length * 2];
125
        for (int j = 0; j < bytes.length; j++) {
126
            int v = bytes[j] & 0xFF;
127
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
128
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
129
        }
130
        return new String(hexChars);
131
    }
132

133
    /**
134
     * Get an {@code int} from {@link Bundle} that is stored as a {@link String}.
135
     *
136
     * @param bundle The {@link Bundle} to get the value from.
137
     * @param key The key for the value.
138
     * @param def The default value if failed to read a valid value.
139
     * @return Returns the {@code int} value after parsing the {@link String} value stored in
140
     * {@link Bundle}, otherwise returns default if failed to read a valid value,
141
     * like in case of an exception.
142
     */
143
    public static int getIntStoredAsStringFromBundle(Bundle bundle, String key, int def) {
144
        if (bundle == null) return def;
145
        return getIntFromString(bundle.getString(key, Integer.toString(def)), def);
146
    }
147

148

149

150
    /**
151
     * If value is not in the range [min, max], set it to either min or max.
152
     */
153
    public static int clamp(int value, int min, int max) {
154
        return Math.min(Math.max(value, min), max);
155
    }
156

157
    /**
158
     * If value is not in the range [min, max], set it to default.
159
     */
160
    public static float rangedOrDefault(float value, float def, float min, float max) {
161
        if (value < min || value > max)
162
            return def;
163
        else
164
            return value;
165
    }
166

167

168

169
    /**
170
     * Add a space indent to a {@link String}. Each indent is 4 space characters long.
171
     *
172
     * @param string The {@link String} to add indent to.
173
     * @param count The indent count.
174
     * @return Returns the indented {@link String}.
175
     */
176
    public static String getSpaceIndentedString(String string, int count) {
177
        if (string == null || string.isEmpty())
178
            return string;
179
        else
180
            return getIndentedString(string, "    ", count);
181
    }
182

183
    /**
184
     * Add a tab indent to a {@link String}. Each indent is 1 tab character long.
185
     *
186
     * @param string The {@link String} to add indent to.
187
     * @param count The indent count.
188
     * @return Returns the indented {@link String}.
189
     */
190
    public static String getTabIndentedString(String string, int count) {
191
        if (string == null || string.isEmpty())
192
            return string;
193
        else
194
            return getIndentedString(string, "\t", count);
195
    }
196

197
    /**
198
     * Add an indent to a {@link String}.
199
     *
200
     * @param string The {@link String} to add indent to.
201
     * @param indent The indent characters.
202
     * @param count The indent count.
203
     * @return Returns the indented {@link String}.
204
     */
205
    public static String getIndentedString(String string, @NonNull String indent, int count) {
206
        if (string == null || string.isEmpty())
207
            return string;
208
        else
209
            return string.replaceAll("(?m)^", Strings.repeat(indent, Math.max(count, 1)));
210
    }
211

212

213

214
    /**
215
     * Get the object itself if it is not {@code null}, otherwise default.
216
     *
217
     * @param object The {@link Object} to check.
218
     * @param def The default {@link Object}.
219
     * @return Returns {@code object} if it is not {@code null}, otherwise returns {@code def}.
220
     */
221
    public static <T> T getDefaultIfNull(@Nullable T object, @Nullable T def) {
222
        return (object == null) ? def : object;
223
    }
224

225
    /**
226
     * Get the {@link String} itself if it is not {@code null} or empty, otherwise default.
227
     *
228
     * @param value The {@link String} to check.
229
     * @param def The default {@link String}.
230
     * @return Returns {@code value} if it is not {@code null} or empty, otherwise returns {@code def}.
231
     */
232
    public static String getDefaultIfUnset(@Nullable String value, String def) {
233
        return (value == null || value.isEmpty()) ? def : value;
234
    }
235

236
    /** Check if a string is null or empty. */
237
    public static boolean isNullOrEmpty(String string) {
238
        return string == null || string.isEmpty();
239
    }
240

241

242

243
    /** Get size of a serializable object. */
244
    public static long getSerializedSize(Serializable object) {
245
        if (object == null) return 0;
246
        try {
247
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
248
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);
249
            objectOutputStream.writeObject(object);
250
            objectOutputStream.flush();
251
            objectOutputStream.close();
252
            return byteOutputStream.toByteArray().length;
253
        } catch (Exception e) {
254
            return -1;
255
        }
256
    }
257

258
}
259

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.