aboutsummaryrefslogtreecommitdiffstats
path: root/openpgp-ktx/src/main/java/me/msfjarvis/openpgpktx/util/ParcelFileDescriptorUtil.kt
blob: 1229b95cb042f9f2b15084c02169b921a22c7839 (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
/*
 * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
@file:Suppress("BlockingMethodInNonBlockingContext")

package me.msfjarvis.openpgpktx.util

import android.os.ParcelFileDescriptor
import android.os.ParcelFileDescriptor.AutoCloseInputStream
import android.os.ParcelFileDescriptor.AutoCloseOutputStream
import android.util.Log
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

internal object ParcelFileDescriptorUtil {

  private const val TAG = "PFDUtils"

  internal suspend fun pipeFrom(inputStream: InputStream): ParcelFileDescriptor {
    val pipe = ParcelFileDescriptor.createPipe()
    val readSide = pipe[0]
    val writeSide = pipe[1]
    transferStreams(inputStream, AutoCloseOutputStream(writeSide))
    return readSide
  }

  internal suspend fun pipeTo(outputStream: OutputStream, output: ParcelFileDescriptor?) {
    transferStreams(AutoCloseInputStream(output), outputStream)
  }

  private suspend fun transferStreams(`in`: InputStream, `out`: OutputStream) {
    withContext(Dispatchers.IO) {
      val buf = ByteArray(4096)
      var len: Int
      try {
        while (`in`.read(buf).also { len = it } > 0) {
          out.write(buf, 0, len)
        }
      } catch (e: IOException) {
        Log.e(TAG, "IOException when writing to out", e)
      } finally {
        try {
          `in`.close()
        } catch (ignored: IOException) {}
        try {
          out.close()
        } catch (ignored: IOException) {}
      }
    }
  }
}