io.c++ 10.1 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 47
size_t InputStream::read(void* buffer, size_t minBytes, size_t maxBytes) {
  size_t n = tryRead(buffer, minBytes, maxBytes);
  KJ_REQUIRE(n >= minBytes, "Premature EOF") {
    // Pretend we read zeros from the input.
    memset(reinterpret_cast<byte*>(buffer) + n, 0, minBytes - n);
    return minBytes;
  }
  return n;
}

48 49 50 51 52 53 54 55 56
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;
  }
}

57
void OutputStream::write(ArrayPtr<const ArrayPtr<const byte>> pieces) {
58 59 60 61 62
  for (auto piece: pieces) {
    write(piece.begin(), piece.size());
  }
}

63 64 65 66 67 68
ArrayPtr<const byte> BufferedInputStream::getReadBuffer() {
  auto result = tryGetReadBuffer();
  KJ_REQUIRE(result.size() > 0, "Premature EOF");
  return result;
}

69 70
// =======================================================================================

71
BufferedInputStreamWrapper::BufferedInputStreamWrapper(InputStream& inner, ArrayPtr<byte> buffer)
Kenton Varda's avatar
Kenton Varda committed
72
    : inner(inner), ownedBuffer(buffer == nullptr ? heapArray<byte>(8192) : nullptr),
73 74
      buffer(buffer == nullptr ? ownedBuffer : buffer) {}

75
BufferedInputStreamWrapper::~BufferedInputStreamWrapper() noexcept(false) {}
76

77
ArrayPtr<const byte> BufferedInputStreamWrapper::tryGetReadBuffer() {
78
  if (bufferAvailable.size() == 0) {
79
    size_t n = inner.tryRead(buffer.begin(), 1, buffer.size());
80 81 82 83 84 85
    bufferAvailable = buffer.slice(0, n);
  }

  return bufferAvailable;
}

86
size_t BufferedInputStreamWrapper::tryRead(void* dst, size_t minBytes, size_t maxBytes) {
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
  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());
    }
  }
}

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

136
BufferedOutputStreamWrapper::BufferedOutputStreamWrapper(OutputStream& inner, ArrayPtr<byte> buffer)
137
    : inner(inner),
Kenton Varda's avatar
Kenton Varda committed
138
      ownedBuffer(buffer == nullptr ? heapArray<byte>(8192) : nullptr),
139 140 141
      buffer(buffer == nullptr ? ownedBuffer : buffer),
      bufferPos(this->buffer.begin()) {}

142 143 144 145
BufferedOutputStreamWrapper::~BufferedOutputStreamWrapper() noexcept(false) {
  unwindDetector.catchExceptionsIfUnwinding([&]() {
    flush();
  });
146 147 148 149 150 151 152 153 154
}

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

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

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);
    }
  }
}

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

190
ArrayInputStream::ArrayInputStream(ArrayPtr<const byte> array): array(array) {}
191
ArrayInputStream::~ArrayInputStream() noexcept(false) {}
192

193
ArrayPtr<const byte> ArrayInputStream::tryGetReadBuffer() {
194 195 196
  return array;
}

197
size_t ArrayInputStream::tryRead(void* dst, size_t minBytes, size_t maxBytes) {
198 199 200
  size_t n = std::min(maxBytes, array.size());
  memcpy(dst, array.begin(), n);
  array = array.slice(n, array.size());
201
  return n;
202 203 204
}

void ArrayInputStream::skip(size_t bytes) {
205
  KJ_REQUIRE(array.size() >= bytes, "ArrayInputStream ended prematurely.") {
206
    bytes = array.size();
207
    break;
208 209 210 211 212 213
  }
  array = array.slice(bytes, array.size());
}

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

214
ArrayOutputStream::ArrayOutputStream(ArrayPtr<byte> array): array(array), fillPos(array.begin()) {}
215
ArrayOutputStream::~ArrayOutputStream() noexcept(false) {}
216

217 218
ArrayPtr<byte> ArrayOutputStream::getWriteBuffer() {
  return arrayPtr(fillPos, array.end());
219 220 221 222 223 224 225
}

void ArrayOutputStream::write(const void* src, size_t size) {
  if (src == fillPos) {
    // Oh goody, the caller wrote directly into our buffer.
    fillPos += size;
  } else {
226
    KJ_REQUIRE(size <= (size_t)(array.end() - fillPos),
227
            "ArrayOutputStream's backing array was not large enough for the data written.");
228 229 230 231 232 233 234
    memcpy(fillPos, src, size);
    fillPos += size;
  }
}

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

235
AutoCloseFd::~AutoCloseFd() noexcept(false) {
236 237 238 239 240 241 242
  if (fd >= 0) {
    unwindDetector.catchExceptionsIfUnwinding([&]() {
      // Don't use SYSCALL() here because close() should not be repeated on EINTR.
      if (close(fd) < 0) {
        KJ_FAIL_SYSCALL("close", errno, fd) {
          break;
        }
243
      }
244 245
    });
  }
246 247
}

248
FdInputStream::~FdInputStream() noexcept(false) {}
249

250
size_t FdInputStream::tryRead(void* buffer, size_t minBytes, size_t maxBytes) {
251 252 253 254 255
  byte* pos = reinterpret_cast<byte*>(buffer);
  byte* min = pos + minBytes;
  byte* max = pos + maxBytes;

  while (pos < min) {
256 257
    ssize_t n;
    KJ_SYSCALL(n = ::read(fd, pos, max - pos), fd);
258 259
    if (n == 0) {
      break;
260 261 262 263 264 265 266
    }
    pos += n;
  }

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

267
FdOutputStream::~FdOutputStream() noexcept(false) {}
268 269 270 271 272

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

  while (size > 0) {
273 274
    ssize_t n;
    KJ_SYSCALL(n = ::write(fd, pos, size), fd);
275
    KJ_ASSERT(n > 0, "write() returned zero.");
276 277 278 279 280
    pos += n;
    size -= n;
  }
}

281
void FdOutputStream::write(ArrayPtr<const ArrayPtr<const byte>> pieces) {
282
  KJ_STACK_ARRAY(struct iovec, iov, pieces.size(), 16, 128);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

  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()) {
298 299
    ssize_t n;
    KJ_SYSCALL(n = ::writev(fd, current, iov.end() - current), fd);
300
    KJ_ASSERT(n > 0, "writev() returned zero.");
301 302 303 304 305 306 307 308 309 310 311 312 313

    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;
    }
  }
}

314
}  // namespace kj