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 __ANDROID__ // Layoutlib does not 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
readFloat()42 float ScopedParcel::readFloat() {
43 float temp = 0.;
44 if (AParcel_readFloat(mParcel, &temp) != STATUS_OK) {
45 temp = 0.;
46 }
47 return temp;
48 }
49
readData()50 std::optional<sk_sp<SkData>> ScopedParcel::readData() {
51 struct Data {
52 void* ptr = nullptr;
53 size_t size = 0;
54 } data;
55 auto error = AParcel_readByteArray(
56 mParcel, &data, [](void* arrayData, int32_t length, int8_t** outBuffer) -> bool {
57 Data* data = reinterpret_cast<Data*>(arrayData);
58 if (length > 0) {
59 data->ptr = sk_malloc_canfail(length);
60 if (!data->ptr) {
61 return false;
62 }
63 *outBuffer = reinterpret_cast<int8_t*>(data->ptr);
64 data->size = length;
65 }
66 return true;
67 });
68 if (error != STATUS_OK || data.size <= 0) {
69 sk_free(data.ptr);
70 return std::nullopt;
71 } else {
72 return SkData::MakeFromMalloc(data.ptr, data.size);
73 }
74 }
75
writeData(const std::optional<sk_sp<SkData>> & optData)76 void ScopedParcel::writeData(const std::optional<sk_sp<SkData>>& optData) {
77 if (optData) {
78 const auto& data = *optData;
79 AParcel_writeByteArray(mParcel, reinterpret_cast<const int8_t*>(data->data()),
80 data->size());
81 } else {
82 AParcel_writeByteArray(mParcel, nullptr, -1);
83 }
84 }
85 #endif // __ANDROID__ // Layoutlib does not support parcel
86