1 /*
2 * Copyright (C) 2023 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 #include "ScopedParcel.h"
17
18 #ifdef __linux__ // Only Linux support parcel
19
20 using namespace android;
21
readInt32()22 int32_t ScopedParcel::readInt32() {
23 int32_t temp = 0;
24 // TODO: This behavior-matches what android::Parcel does
25 // but this should probably be better
26 if (AParcel_readInt32(mParcel, &temp) != STATUS_OK) {
27 temp = 0;
28 }
29 return temp;
30 }
31
readUint32()32 uint32_t ScopedParcel::readUint32() {
33 uint32_t temp = 0;
34 // TODO: This behavior-matches what android::Parcel does
35 // but this should probably be better
36 if (AParcel_readUint32(mParcel, &temp) != STATUS_OK) {
37 temp = 0;
38 }
39 return temp;
40 }
41
readInt64()42 int64_t ScopedParcel::readInt64() {
43 int64_t temp = 0;
44 // TODO: This behavior-matches what android::Parcel does
45 // but this should probably be better
46 if (AParcel_readInt64(mParcel, &temp) != STATUS_OK) {
47 temp = 0;
48 }
49 return temp;
50 }
51
readFloat()52 float ScopedParcel::readFloat() {
53 float temp = 0.;
54 if (AParcel_readFloat(mParcel, &temp) != STATUS_OK) {
55 temp = 0.;
56 }
57 return temp;
58 }
59
readData()60 std::optional<sk_sp<SkData>> ScopedParcel::readData() {
61 struct Data {
62 void* ptr = nullptr;
63 size_t size = 0;
64 } data;
65 auto error = AParcel_readByteArray(
66 mParcel, &data, [](void* arrayData, int32_t length, int8_t** outBuffer) -> bool {
67 Data* data = reinterpret_cast<Data*>(arrayData);
68 if (length > 0) {
69 data->ptr = sk_malloc_canfail(length);
70 if (!data->ptr) {
71 return false;
72 }
73 *outBuffer = reinterpret_cast<int8_t*>(data->ptr);
74 data->size = length;
75 }
76 return true;
77 });
78 if (error != STATUS_OK || data.size <= 0) {
79 sk_free(data.ptr);
80 return std::nullopt;
81 } else {
82 return SkData::MakeFromMalloc(data.ptr, data.size);
83 }
84 }
85
writeData(const std::optional<sk_sp<SkData>> & optData)86 void ScopedParcel::writeData(const std::optional<sk_sp<SkData>>& optData) {
87 if (optData) {
88 const auto& data = *optData;
89 AParcel_writeByteArray(mParcel, reinterpret_cast<const int8_t*>(data->data()),
90 data->size());
91 } else {
92 AParcel_writeByteArray(mParcel, nullptr, -1);
93 }
94 }
95 #endif // __linux__ // Only Linux support parcel
96