summaryrefslogtreecommitdiff
path: root/okhttp/src/main/kotlin/okhttp3/internal/-UtilCommon.kt
blob: 16d1321b5afbdb0b5ad3b6b8b07299f172ae2e14 (plain)
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
/*
 * Copyright (C) 2021 Square, Inc.
 *
 * 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.
 */
@file:Suppress("ktlint:standard:filename")

package okhttp3.internal

import okhttp3.Headers
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.ArrayIndexOutOfBoundsException
import okio.Buffer
import okio.BufferedSink
import okio.BufferedSource
import okio.ByteString.Companion.decodeHex
import okio.Closeable
import okio.FileNotFoundException
import okio.FileSystem
import okio.IOException
import okio.Options
import okio.Path
import okio.use

// TODO: migrate callers to [Regex.matchAt] when that API is not experimental.
internal fun Regex.matchAtPolyfill(
  input: CharSequence,
  index: Int,
): MatchResult? {
  val candidate = find(input, index) ?: return null
  if (candidate.range.first != index) return null // Didn't match where it should have.
  return candidate
}

@JvmField
val EMPTY_BYTE_ARRAY: ByteArray = ByteArray(0)

/** Byte order marks. */
internal val UNICODE_BOMS =
  Options.of(
    // UTF-8.
    "efbbbf".decodeHex(),
    // UTF-16BE.
    "feff".decodeHex(),
    // UTF-32LE.
    "fffe0000".decodeHex(),
    // UTF-16LE.
    "fffe".decodeHex(),
    // UTF-32BE.
    "0000feff".decodeHex(),
  )

/**
 * Returns an array containing only elements found in this array and also in [other]. The returned
 * elements are in the same order as in this.
 */
internal fun Array<String>.intersect(
  other: Array<String>,
  comparator: Comparator<in String>,
): Array<String> {
  val result = mutableListOf<String>()
  for (a in this) {
    for (b in other) {
      if (comparator.compare(a, b) == 0) {
        result.add(a)
        break
      }
    }
  }
  return result.toTypedArray()
}

/**
 * Returns true if there is an element in this array that is also in [other]. This method terminates
 * if any intersection is found. The sizes of both arguments are assumed to be so small, and the
 * likelihood of an intersection so great, that it is not worth the CPU cost of sorting or the
 * memory cost of hashing.
 */
internal fun Array<String>.hasIntersection(
  other: Array<String>?,
  comparator: Comparator<in String>,
): Boolean {
  if (isEmpty() || other == null || other.isEmpty()) {
    return false
  }
  for (a in this) {
    for (b in other) {
      if (comparator.compare(a, b) == 0) {
        return true
      }
    }
  }
  return false
}

internal fun Array<String>.indexOf(
  value: String,
  comparator: Comparator<String>,
): Int = indexOfFirst { comparator.compare(it, value) == 0 }

@Suppress("UNCHECKED_CAST")
internal fun Array<String>.concat(value: String): Array<String> {
  val result = copyOf(size + 1)
  result[result.lastIndex] = value
  return result as Array<String>
}

/** Increments [startIndex] until this string is not ASCII whitespace. Stops at [endIndex]. */
internal fun String.indexOfFirstNonAsciiWhitespace(
  startIndex: Int = 0,
  endIndex: Int = length,
): Int {
  for (i in startIndex until endIndex) {
    when (this[i]) {
      '\t', '\n', '\u000C', '\r', ' ' -> Unit
      else -> return i
    }
  }
  return endIndex
}

/**
 * Decrements [endIndex] until `input[endIndex - 1]` is not ASCII whitespace. Stops at [startIndex].
 */
internal fun String.indexOfLastNonAsciiWhitespace(
  startIndex: Int = 0,
  endIndex: Int = length,
): Int {
  for (i in endIndex - 1 downTo startIndex) {
    when (this[i]) {
      '\t', '\n', '\u000C', '\r', ' ' -> Unit
      else -> return i + 1
    }
  }
  return startIndex
}

/** Equivalent to `string.substring(startIndex, endIndex).trim()`. */
fun String.trimSubstring(
  startIndex: Int = 0,
  endIndex: Int = length,
): String {
  val start = indexOfFirstNonAsciiWhitespace(startIndex, endIndex)
  val end = indexOfLastNonAsciiWhitespace(start, endIndex)
  return substring(start, end)
}

/**
 * Returns the index of the first character in this string that contains a character in
 * [delimiters]. Returns endIndex if there is no such character.
 */
fun String.delimiterOffset(
  delimiters: String,
  startIndex: Int = 0,
  endIndex: Int = length,
): Int {
  for (i in startIndex until endIndex) {
    if (this[i] in delimiters) return i
  }
  return endIndex
}

/**
 * Returns the index of the first character in this string that is [delimiter]. Returns [endIndex]
 * if there is no such character.
 */
fun String.delimiterOffset(
  delimiter: Char,
  startIndex: Int = 0,
  endIndex: Int = length,
): Int {
  for (i in startIndex until endIndex) {
    if (this[i] == delimiter) return i
  }
  return endIndex
}

/**
 * Returns the index of the first character in this string that is either a control character (like
 * `\u0000` or `\n`) or a non-ASCII character. Returns -1 if this string has no such characters.
 */
internal fun String.indexOfControlOrNonAscii(): Int {
  for (i in 0 until length) {
    val c = this[i]
    if (c <= '\u001f' || c >= '\u007f') {
      return i
    }
  }
  return -1
}

/** Returns true if we should void putting this this header in an exception or toString(). */
internal fun isSensitiveHeader(name: String): Boolean {
  return name.equals("Authorization", ignoreCase = true) ||
    name.equals("Cookie", ignoreCase = true) ||
    name.equals("Proxy-Authorization", ignoreCase = true) ||
    name.equals("Set-Cookie", ignoreCase = true)
}

internal fun Char.parseHexDigit(): Int =
  when (this) {
    in '0'..'9' -> this - '0'
    in 'a'..'f' -> this - 'a' + 10
    in 'A'..'F' -> this - 'A' + 10
    else -> -1
  }

internal infix fun Byte.and(mask: Int): Int = toInt() and mask

internal infix fun Short.and(mask: Int): Int = toInt() and mask

internal infix fun Int.and(mask: Long): Long = toLong() and mask

@Throws(IOException::class)
internal fun BufferedSink.writeMedium(medium: Int) {
  writeByte(medium.ushr(16) and 0xff)
  writeByte(medium.ushr(8) and 0xff)
  writeByte(medium and 0xff)
}

@Throws(IOException::class)
internal fun BufferedSource.readMedium(): Int {
  return (
    readByte() and 0xff shl 16
      or (readByte() and 0xff shl 8)
      or (readByte() and 0xff)
  )
}

/** Run [block] until it either throws an [IOException] or completes. */
internal inline fun ignoreIoExceptions(block: () -> Unit) {
  try {
    block()
  } catch (_: IOException) {
  }
}

internal fun Buffer.skipAll(b: Byte): Int {
  var count = 0
  while (!exhausted() && this[0] == b) {
    count++
    readByte()
  }
  return count
}

/**
 * Returns the index of the next non-whitespace character in this. Result is undefined if input
 * contains newline characters.
 */
internal fun String.indexOfNonWhitespace(startIndex: Int = 0): Int {
  for (i in startIndex until length) {
    val c = this[i]
    if (c != ' ' && c != '\t') {
      return i
    }
  }
  return length
}

fun String.toLongOrDefault(defaultValue: Long): Long {
  return try {
    toLong()
  } catch (_: NumberFormatException) {
    defaultValue
  }
}

/**
 * Returns this as a non-negative integer, or 0 if it is negative, or [Int.MAX_VALUE] if it is too
 * large, or [defaultValue] if it cannot be parsed.
 */
internal fun String?.toNonNegativeInt(defaultValue: Int): Int {
  try {
    val value = this?.toLong() ?: return defaultValue
    return when {
      value > Int.MAX_VALUE -> Int.MAX_VALUE
      value < 0 -> 0
      else -> value.toInt()
    }
  } catch (_: NumberFormatException) {
    return defaultValue
  }
}

/** Closes this, ignoring any checked exceptions. */
fun Closeable.closeQuietly() {
  try {
    close()
  } catch (rethrown: RuntimeException) {
    throw rethrown
  } catch (_: Exception) {
  }
}

/**
 * Returns true if file streams can be manipulated independently of their paths. This is typically
 * true for systems like Mac, Unix, and Linux that use inodes in their file system interface. It is
 * typically false on Windows.
 *
 * If this returns false we won't permit simultaneous reads and writes. When writes commit we need
 * to delete the previous snapshots, and that won't succeed if the file is open. (We do permit
 * multiple simultaneous reads.)
 *
 * @param file a file in the directory to check. This file shouldn't already exist!
 */
internal fun FileSystem.isCivilized(file: Path): Boolean {
  sink(file).use {
    try {
      delete(file)
      return true
    } catch (_: IOException) {
    }
  }
  delete(file)
  return false
}

/** Delete file we expect but don't require to exist. */
internal fun FileSystem.deleteIfExists(path: Path) {
  try {
    delete(path)
  } catch (fnfe: FileNotFoundException) {
    return
  }
}

/** Tolerant delete, try to clear as many files as possible even after a failure. */
internal fun FileSystem.deleteContents(directory: Path) {
  var exception: IOException? = null
  val files =
    try {
      list(directory)
    } catch (fnfe: FileNotFoundException) {
      return
    }
  for (file in files) {
    try {
      if (metadata(file).isDirectory) {
        deleteContents(file)
      }

      delete(file)
    } catch (ioe: IOException) {
      if (exception == null) {
        exception = ioe
      }
    }
  }
  if (exception != null) {
    throw exception
  }
}

internal fun <E> MutableList<E>.addIfAbsent(element: E) {
  if (!contains(element)) add(element)
}

internal fun Exception.withSuppressed(suppressed: List<Exception>): Throwable =
  apply {
    for (e in suppressed) addSuppressed(e)
  }

internal inline fun <T> Iterable<T>.filterList(predicate: T.() -> Boolean): List<T> {
  var result: List<T> = emptyList()
  for (i in this) {
    if (predicate(i)) {
      if (result.isEmpty()) result = mutableListOf()
      (result as MutableList<T>).add(i)
    }
  }
  return result
}

internal const val USER_AGENT: String = "okhttp/${CONST_VERSION}"

internal fun checkOffsetAndCount(
  arrayLength: Long,
  offset: Long,
  count: Long,
) {
  if (offset or count < 0L || offset > arrayLength || arrayLength - offset < count) {
    throw ArrayIndexOutOfBoundsException("length=$arrayLength, offset=$offset, count=$offset")
  }
}

val commonEmptyHeaders: Headers = Headers.headersOf()
val commonEmptyRequestBody: RequestBody = EMPTY_BYTE_ARRAY.toRequestBody()
val commonEmptyResponse: ResponseBody = EMPTY_BYTE_ARRAY.toResponseBody()

internal fun <T> interleave(
  a: Iterable<T>,
  b: Iterable<T>,
): List<T> {
  val ia = a.iterator()
  val ib = b.iterator()

  return buildList {
    while (ia.hasNext() || ib.hasNext()) {
      if (ia.hasNext()) {
        add(ia.next())
      }
      if (ib.hasNext()) {
        add(ib.next())
      }
    }
  }
}

// TODO check read only options for creating lists
public fun <T> List<T>.readOnly() = this.toList()

// TODO check read only options for creating lists
public fun <T> Set<T>.readOnly() = this.toSet()