io.c++ 9.76 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "io.h"
Kenton Varda's avatar
Kenton Varda committed
25
#include "debug.h"
26 27
#include <unistd.h>
#include <sys/uio.h>
Kenton Varda's avatar
Kenton Varda committed
28
#include <algorithm>
29
#include <errno.h>
30

31
namespace kj {
32

33 34 35 36
InputStream::~InputStream() noexcept(false) {}
OutputStream::~OutputStream() noexcept(false) {}
BufferedInputStream::~BufferedInputStream() noexcept(false) {}
BufferedOutputStream::~BufferedOutputStream() noexcept(false) {}
37 38 39 40 41 42 43 44 45 46

void InputStream::skip(size_t bytes) {
  char scratch[8192];
  while (bytes > 0) {
    size_t amount = std::min(bytes, sizeof(scratch));
    read(scratch, amount);
    bytes -= amount;
  }
}

47
void OutputStream::write(ArrayPtr<const ArrayPtr<const byte>> pieces) {
48 49 50 51 52 53 54
  for (auto piece: pieces) {
    write(piece.begin(), piece.size());
  }
}

// =======================================================================================

55
BufferedInputStreamWrapper::BufferedInputStreamWrapper(InputStream& inner, ArrayPtr<byte> buffer)
Kenton Varda's avatar
Kenton Varda committed
56
    : inner(inner), ownedBuffer(buffer == nullptr ? heapArray<byte>(8192) : nullptr),
57 58
      buffer(buffer == nullptr ? ownedBuffer : buffer) {}

59
BufferedInputStreamWrapper::~BufferedInputStreamWrapper() noexcept(false) {}
60

61
ArrayPtr<const byte> BufferedInputStreamWrapper::getReadBuffer() {
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
  if (bufferAvailable.size() == 0) {
    size_t n = inner.read(buffer.begin(), 1, buffer.size());
    bufferAvailable = buffer.slice(0, n);
  }

  return bufferAvailable;
}

size_t BufferedInputStreamWrapper::read(void* dst, size_t minBytes, size_t maxBytes) {
  if (minBytes <= bufferAvailable.size()) {
    // Serve from current buffer.
    size_t n = std::min(bufferAvailable.size(), maxBytes);
    memcpy(dst, bufferAvailable.begin(), n);
    bufferAvailable = bufferAvailable.slice(n, bufferAvailable.size());
    return n;
  } else {
    // Copy current available into destination.
    memcpy(dst, bufferAvailable.begin(), bufferAvailable.size());
    size_t fromFirstBuffer = bufferAvailable.size();

    dst = reinterpret_cast<byte*>(dst) + fromFirstBuffer;
    minBytes -= fromFirstBuffer;
    maxBytes -= fromFirstBuffer;

    if (maxBytes <= buffer.size()) {
      // Read the next buffer-full.
      size_t n = inner.read(buffer.begin(), minBytes, buffer.size());
      size_t fromSecondBuffer = std::min(n, maxBytes);
      memcpy(dst, buffer.begin(), fromSecondBuffer);
      bufferAvailable = buffer.slice(fromSecondBuffer, n);
      return fromFirstBuffer + fromSecondBuffer;
    } else {
      // Forward large read to the underlying stream.
      bufferAvailable = nullptr;
      return fromFirstBuffer + inner.read(dst, minBytes, maxBytes);
    }
  }
}

void BufferedInputStreamWrapper::skip(size_t bytes) {
  if (bytes <= bufferAvailable.size()) {
    bufferAvailable = bufferAvailable.slice(bytes, bufferAvailable.size());
  } else {
    bytes -= bufferAvailable.size();
    if (bytes <= buffer.size()) {
      // Read the next buffer-full.
      size_t n = inner.read(buffer.begin(), bytes, buffer.size());
      bufferAvailable = buffer.slice(bytes, n);
    } else {
      // Forward large skip to the underlying stream.
      bufferAvailable = nullptr;
      inner.skip(bytes - bufferAvailable.size());
    }
  }
}

// -------------------------------------------------------------------

120
BufferedOutputStreamWrapper::BufferedOutputStreamWrapper(OutputStream& inner, ArrayPtr<byte> buffer)
121
    : inner(inner),
Kenton Varda's avatar
Kenton Varda committed
122
      ownedBuffer(buffer == nullptr ? heapArray<byte>(8192) : nullptr),
123 124 125
      buffer(buffer == nullptr ? ownedBuffer : buffer),
      bufferPos(this->buffer.begin()) {}

126 127 128 129
BufferedOutputStreamWrapper::~BufferedOutputStreamWrapper() noexcept(false) {
  unwindDetector.catchExceptionsIfUnwinding([&]() {
    flush();
  });
130 131 132 133 134 135 136 137 138
}

void BufferedOutputStreamWrapper::flush() {
  if (bufferPos > buffer.begin()) {
    inner.write(buffer.begin(), bufferPos - buffer.begin());
    bufferPos = buffer.begin();
  }
}

139 140
ArrayPtr<byte> BufferedOutputStreamWrapper::getWriteBuffer() {
  return arrayPtr(bufferPos, buffer.end());
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
}

void BufferedOutputStreamWrapper::write(const void* src, size_t size) {
  if (src == bufferPos) {
    // Oh goody, the caller wrote directly into our buffer.
    bufferPos += size;
  } else {
    size_t available = buffer.end() - bufferPos;

    if (size <= available) {
      memcpy(bufferPos, src, size);
      bufferPos += size;
    } else if (size <= buffer.size()) {
      // Too much for this buffer, but not a full buffer's worth, so we'll go ahead and copy.
      memcpy(bufferPos, src, available);
      inner.write(buffer.begin(), buffer.size());

      size -= available;
      src = reinterpret_cast<const byte*>(src) + available;

      memcpy(buffer.begin(), src, size);
      bufferPos = buffer.begin() + size;
    } else {
      // Writing so much data that we might as well write directly to avoid a copy.
      inner.write(buffer.begin(), bufferPos - buffer.begin());
      bufferPos = buffer.begin();
      inner.write(src, size);
    }
  }
}

// =======================================================================================

174
ArrayInputStream::ArrayInputStream(ArrayPtr<const byte> array): array(array) {}
175
ArrayInputStream::~ArrayInputStream() noexcept(false) {}
176

177
ArrayPtr<const byte> ArrayInputStream::getReadBuffer() {
178 179 180 181 182
  return array;
}

size_t ArrayInputStream::read(void* dst, size_t minBytes, size_t maxBytes) {
  size_t n = std::min(maxBytes, array.size());
183
  size_t result = n;
184
  KJ_REQUIRE(n >= minBytes, "ArrayInputStream ended prematurely.") {
185
    result = minBytes;  // garbage
186
    break;
187 188 189
  }
  memcpy(dst, array.begin(), n);
  array = array.slice(n, array.size());
190
  return result;
191 192 193
}

void ArrayInputStream::skip(size_t bytes) {
194
  KJ_REQUIRE(array.size() >= bytes, "ArrayInputStream ended prematurely.") {
195
    bytes = array.size();
196
    break;
197 198 199 200 201 202
  }
  array = array.slice(bytes, array.size());
}

// -------------------------------------------------------------------

203
ArrayOutputStream::ArrayOutputStream(ArrayPtr<byte> array): array(array), fillPos(array.begin()) {}
204
ArrayOutputStream::~ArrayOutputStream() noexcept(false) {}
205

206 207
ArrayPtr<byte> ArrayOutputStream::getWriteBuffer() {
  return arrayPtr(fillPos, array.end());
208 209 210 211 212 213 214
}

void ArrayOutputStream::write(const void* src, size_t size) {
  if (src == fillPos) {
    // Oh goody, the caller wrote directly into our buffer.
    fillPos += size;
  } else {
215
    KJ_REQUIRE(size <= (size_t)(array.end() - fillPos),
216
            "ArrayOutputStream's backing array was not large enough for the data written.");
217 218 219 220 221 222 223
    memcpy(fillPos, src, size);
    fillPos += size;
  }
}

// =======================================================================================

224 225 226 227
AutoCloseFd::~AutoCloseFd() noexcept(false) {
  unwindDetector.catchExceptionsIfUnwinding([&]() {
    // Don't use SYSCALL() here because close() should not be repeated on EINTR.
    if (fd >= 0 && close(fd) < 0) {
228
      KJ_FAIL_SYSCALL("close", errno, fd) {
229 230
        break;
      }
231
    }
232
  });
233 234
}

235
FdInputStream::~FdInputStream() noexcept(false) {}
236 237 238 239 240 241 242

size_t FdInputStream::read(void* buffer, size_t minBytes, size_t maxBytes) {
  byte* pos = reinterpret_cast<byte*>(buffer);
  byte* min = pos + minBytes;
  byte* max = pos + maxBytes;

  while (pos < min) {
243 244 245
    ssize_t n;
    KJ_SYSCALL(n = ::read(fd, pos, max - pos), fd);
    KJ_REQUIRE(n > 0, "Premature EOF") {
246
      return minBytes;
247 248 249 250 251 252 253
    }
    pos += n;
  }

  return pos - reinterpret_cast<byte*>(buffer);
}

254
FdOutputStream::~FdOutputStream() noexcept(false) {}
255 256 257 258 259

void FdOutputStream::write(const void* buffer, size_t size) {
  const char* pos = reinterpret_cast<const char*>(buffer);

  while (size > 0) {
260 261
    ssize_t n;
    KJ_SYSCALL(n = ::write(fd, pos, size), fd);
262
    KJ_ASSERT(n > 0, "write() returned zero.");
263 264 265 266 267
    pos += n;
    size -= n;
  }
}

268
void FdOutputStream::write(ArrayPtr<const ArrayPtr<const byte>> pieces) {
269
  KJ_STACK_ARRAY(struct iovec, iov, pieces.size(), 16, 128);
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284

  for (uint i = 0; i < pieces.size(); i++) {
    // writev() interface is not const-correct.  :(
    iov[i].iov_base = const_cast<byte*>(pieces[i].begin());
    iov[i].iov_len = pieces[i].size();
  }

  struct iovec* current = iov.begin();

  // Make sure we don't do anything on an empty write.
  while (current < iov.end() && current->iov_len == 0) {
    ++current;
  }

  while (current < iov.end()) {
285 286
    ssize_t n;
    KJ_SYSCALL(n = ::writev(fd, current, iov.end() - current), fd);
287
    KJ_ASSERT(n > 0, "writev() returned zero.");
288 289 290 291 292 293 294 295 296 297 298 299 300

    while (static_cast<size_t>(n) >= current->iov_len) {
      n -= current->iov_len;
      ++current;
    }

    if (n > 0) {
      current->iov_base = reinterpret_cast<byte*>(current->iov_base) + n;
      current->iov_len -= n;
    }
  }
}

301
}  // namespace kj