1 /* 2 * Hunt - A refined core library for D programming language. 3 * 4 * Copyright (C) 2018-2019 HuntLabs 5 * 6 * Website: https://www.huntlabs.net/ 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module hunt.io.PipedStream; 13 14 import hunt.io.Common; 15 import hunt.io.ByteArrayInputStream; 16 import hunt.io.ByteArrayOutputStream; 17 import hunt.io.BufferedInputStream; 18 import hunt.io.BufferedOutputStream; 19 import hunt.io.FileInputStream; 20 import hunt.io.FileOutputStream; 21 import hunt.util.Common; 22 23 // import hunt.logging; 24 25 import std.path; 26 import std.file; 27 28 interface PipedStream : Closeable { 29 30 InputStream getInputStream(); 31 32 OutputStream getOutputStream(); 33 } 34 35 /** 36 */ 37 class ByteArrayPipedStream : PipedStream { 38 39 private ByteArrayOutputStream outStream; 40 private ByteArrayInputStream inStream; 41 private int size; 42 43 this(int size) { 44 this.size = size; 45 } 46 47 void close() { 48 inStream = null; 49 outStream = null; 50 } 51 52 InputStream getInputStream() { 53 if (inStream is null) { 54 inStream = new ByteArrayInputStream(outStream.toByteArray()); 55 outStream = null; 56 } 57 return inStream; 58 } 59 60 OutputStream getOutputStream() { 61 if (outStream is null) { 62 outStream = new ByteArrayOutputStream(size); 63 } 64 return outStream; 65 } 66 } 67 68 /** 69 */ 70 class FilePipedStream : PipedStream { 71 72 private OutputStream output; 73 private InputStream input; 74 private string temp; 75 76 this() { 77 import std.uuid; 78 this(tempDir() ~ dirSeparator ~ randomUUID().toString()); 79 } 80 81 this(string tempdir) { 82 temp = tempdir; 83 } 84 85 void close() { 86 import std.array; 87 if (temp.empty()) 88 return; 89 90 try { 91 temp.remove(); 92 } finally { 93 if (input !is null) 94 input.close(); 95 96 if (output !is null) 97 output.close(); 98 } 99 100 input = null; 101 output = null; 102 temp = null; 103 } 104 105 106 InputStream getInputStream() { 107 if (input is null) { 108 input = new BufferedInputStream(new FileInputStream(temp)); 109 } 110 return input; 111 } 112 113 OutputStream getOutputStream() { 114 if (output is null) { 115 output = new BufferedOutputStream(new FileOutputStream(temp)); 116 } 117 return output; 118 } 119 } 120