summaryrefslogtreecommitdiff
path: root/common/libs/fs/shared_buf.cc
blob: 84397a076895a048fd622646295e3c0db69afa58 (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
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <sstream>
#include <string>
#include <thread>
#include <vector>

#include "common/libs/fs/shared_buf.h"
#include "common/libs/fs/shared_fd.h"

namespace cvd {

namespace {

const size_t BUFF_SIZE = 1 << 14;

} // namespace

ssize_t ReadAll(SharedFD fd, std::string* buf) {
  char buff[BUFF_SIZE];
  std::stringstream ss;
  ssize_t read;
  while ((read = fd->Read(buff, BUFF_SIZE - 1)) > 0) {
    // this is necessary to avoid problems with having a '\0' in the middle of the buffer
    ss << std::string(buff, read);
  }
  if (read < 0) {
    errno = fd->GetErrno();
    return read;
  }
  *buf = ss.str();
  return buf->size();
}

ssize_t ReadExact(SharedFD fd, std::string* buf) {
  size_t total_read = 0;
  ssize_t read = 0;
  while ((read = fd->Read((void*)&((*buf)[total_read]), buf->size() - total_read)) > 0) {
    if (read < 0) {
      errno = fd->GetErrno();
      return read;
    }
    total_read += read;
    if (total_read == buf->size()) {
      break;
    }
  }
  return total_read;
}

ssize_t WriteAll(SharedFD fd, const std::string& buf) {
  size_t total_written = 0;
  ssize_t written = 0;
  while ((written = fd->Write((void*)&(buf[total_written]), buf.size() - total_written)) > 0) {
    if (written < 0) {
      errno = fd->GetErrno();
      return written;
    }
    total_written += written;
    if (total_written == buf.size()) {
      break;
    }
  }
  return total_written;
}

} // namespace cvd