summaryrefslogtreecommitdiffstats
path: root/runtime/base/unix_file/string_file.cc
blob: ff0d0fa3c460fdd9235b8674cc57f4979e905766 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
 * Copyright (C) 2009 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 "base/unix_file/string_file.h"
#include <errno.h>
#include <algorithm>
#include "base/logging.h"

namespace unix_file {

StringFile::StringFile() {
}

StringFile::~StringFile() {
}

int StringFile::Close() {
  return 0;
}

int StringFile::Flush() {
  return 0;
}

int64_t StringFile::Read(char *buf, int64_t byte_count, int64_t offset) const {
  CHECK(buf);
  CHECK_GE(byte_count, 0);

  if (offset < 0) {
    return -EINVAL;
  }

  const int64_t available_bytes = std::min(byte_count, GetLength() - offset);
  if (available_bytes < 0) {
    return 0;  // Not an error, but nothing for us to do, either.
  }
  memcpy(buf, data_.data() + offset, available_bytes);
  return available_bytes;
}

int StringFile::SetLength(int64_t new_length) {
  if (new_length < 0) {
    return -EINVAL;
  }
  data_.resize(new_length);
  return 0;
}

int64_t StringFile::GetLength() const {
  return data_.size();
}

int64_t StringFile::Write(const char *buf, int64_t byte_count, int64_t offset) {
  CHECK(buf);
  CHECK_GE(byte_count, 0);

  if (offset < 0) {
    return -EINVAL;
  }

  if (byte_count == 0) {
    return 0;
  }

  // FUSE seems happy to allow writes past the end. (I'd guess it doesn't
  // synthesize a write of zero bytes so that we're free to implement sparse
  // files.) GNU as(1) seems to require such writes. Those files are small.
  const int64_t bytes_past_end = offset - GetLength();
  if (bytes_past_end > 0) {
    data_.append(bytes_past_end, '\0');
  }

  data_.replace(offset, byte_count, buf, byte_count);
  return byte_count;
}

void StringFile::Assign(const art::StringPiece &new_data) {
  data_.assign(new_data.data(), new_data.size());
}

const art::StringPiece StringFile::ToStringPiece() const {
  return data_;
}

}  // namespace unix_file