aboutsummaryrefslogtreecommitdiff
path: root/src/common/io/Stream.cpp
blob: b2a67a1833f22301ca5978e1e3dd0f977866c234 (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
#include "cru/common/io/Stream.h"
#include "cru/common/Exception.h"
#include "cru/common/Format.h"

#include <utility>

namespace cru::io {
StreamOperationNotSupportedException::StreamOperationNotSupportedException(
    String operation)
    : operation_(std::move(operation)) {
  SetMessage(Format(u"Stream operation {} not supported.", operation_));
}

void StreamOperationNotSupportedException::CheckSeek(bool seekable) {
  if (!seekable) throw StreamOperationNotSupportedException(u"seek");
}

void StreamOperationNotSupportedException::CheckRead(bool readable) {
  if (!readable) throw StreamOperationNotSupportedException(u"read");
}

void StreamOperationNotSupportedException::CheckWrite(bool writable) {
  if (!writable) throw StreamOperationNotSupportedException(u"write");
}

StreamAlreadyClosedException::StreamAlreadyClosedException()
    : Exception(u"Stream is already closed.") {}

void StreamAlreadyClosedException::Check(bool closed) {
  if (closed) throw StreamAlreadyClosedException();
}

Index Stream::Tell() { return Seek(0, SeekOrigin::Current); }

void Stream::Rewind() { Seek(0, SeekOrigin::Begin); }

Index Stream::GetSize() {
  Index current_position = Tell();
  Seek(0, SeekOrigin::End);
  Index size = Tell();
  Seek(current_position, SeekOrigin::Begin);
  return size;
}

Index Stream::Read(std::byte* buffer, Index size) {
  return Read(buffer, 0, size);
}

Index Stream::Write(const std::byte* buffer, Index size) {
  return Write(buffer, 0, size);
}

Index Stream::Write(const char* buffer, Index offset, Index size) {
  return Write(reinterpret_cast<const std::byte*>(buffer), offset, size);
}

Index Stream::Write(const char* buffer, Index size) {
  return Write(reinterpret_cast<const std::byte*>(buffer), size);
}

Buffer Stream::ReadToEnd(Index grow_size) {
  Buffer buffer(grow_size);
  while (true) {
    auto read = Read(buffer.GetUsedEndPtr(), buffer.GetBackFree());
    if (read == 0) {
      break;
    }
    if (buffer.IsUsedReachEnd()) {
      buffer.ResizeBuffer(buffer.GetBufferSize() + grow_size, true);
    }
  }
  return buffer;
}

String Stream::ReadToEndAsUtf8String() {
  auto buffer = ReadToEnd();
  return String::FromUtf8(buffer);
}

void Stream::Flush() {}

void Stream::Close() {}
}  // namespace cru::io