blob: 71ac2b33fd982c016dead17a9deb4d70ab533df0 [file] [log] [blame]
Martijn Coenen72110162016-08-19 14:28:25 +02001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <hidl/HidlSupport.h>
18
19namespace android {
20namespace hardware {
21
22static const char *const kEmptyString = "";
23
24hidl_string::hidl_string()
25 : mBuffer(const_cast<char *>(kEmptyString)),
26 mSize(0),
27 mOwnsBuffer(true) {
28}
29
30hidl_string::~hidl_string() {
31 clear();
32}
33
34hidl_string::hidl_string(const hidl_string &other)
35 : mBuffer(const_cast<char *>(kEmptyString)),
36 mSize(0),
37 mOwnsBuffer(true) {
38 setTo(other.c_str(), other.size());
39}
40
41hidl_string &hidl_string::operator=(const hidl_string &other) {
42 if (this != &other) {
43 setTo(other.c_str(), other.size());
44 }
45
46 return *this;
47}
48
49hidl_string &hidl_string::operator=(const char *s) {
50 return setTo(s, strlen(s));
51}
52
53hidl_string &hidl_string::setTo(const char *data, size_t size) {
54 clear();
55
56 mBuffer = (char *)malloc(size + 1);
57 memcpy(mBuffer, data, size);
58 mBuffer[size] = '\0';
59
60 mSize = size;
61 mOwnsBuffer = true;
62
63 return *this;
64}
65
66void hidl_string::clear() {
67 if (mOwnsBuffer && (mBuffer != kEmptyString)) {
68 free(mBuffer);
69 }
70
71 mBuffer = const_cast<char *>(kEmptyString);
72 mSize = 0;
73 mOwnsBuffer = true;
74}
75
76void hidl_string::setToExternal(const char *data, size_t size) {
77 clear();
78
79 mBuffer = const_cast<char *>(data);
80 mSize = size;
81 mOwnsBuffer = false;
82}
83
84const char *hidl_string::c_str() const {
85 return mBuffer ? mBuffer : "";
86}
87
88size_t hidl_string::size() const {
89 return mSize;
90}
91
92bool hidl_string::empty() const {
93 return mSize == 0;
94}
95
96status_t hidl_string::readEmbeddedFromParcel(
97 const Parcel &parcel, size_t parentHandle, size_t parentOffset) {
98 const void *ptr = parcel.readEmbeddedBuffer(
99 nullptr /* buffer_handle */,
100 parentHandle,
101 parentOffset + offsetof(hidl_string, mBuffer));
102
103 return ptr != NULL ? OK : UNKNOWN_ERROR;
104}
105
106status_t hidl_string::writeEmbeddedToParcel(
107 Parcel *parcel, size_t parentHandle, size_t parentOffset) const {
108 return parcel->writeEmbeddedBuffer(
109 mBuffer,
110 mSize + 1,
111 nullptr /* handle */,
112 parentHandle,
113 parentOffset + offsetof(hidl_string, mBuffer));
114}
115
116} // namespace hardware
117} // namespace android
118
119