Line data Source code
1 : /*
2 : * Copyright (c) 2024 Project CHIP Authors
3 : * All rights reserved.
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 :
18 : #pragma once
19 :
20 : #include <app/data-model/Encode.h>
21 : #include <app/data-model/FabricScoped.h>
22 : #include <lib/core/CHIPError.h>
23 : #include <lib/core/TLV.h>
24 :
25 : namespace chip {
26 : namespace app {
27 : namespace DataModel {
28 :
29 : /// Defines an abstract class of something that can be encoded
30 : /// into a TLV with a given data tag
31 : class EncodableToTLV
32 : {
33 : public:
34 17 : virtual ~EncodableToTLV() = default;
35 :
36 11 : virtual CHIP_ERROR EncodeTo(FabricAwareTLVWriter & writer, TLV::Tag tag) const
37 : {
38 : // By default, just ignore the fabric index. Implementations that care
39 : // about it should override as needed.
40 11 : return EncodeTo(writer.mTLVWriter, tag);
41 : }
42 : virtual CHIP_ERROR EncodeTo(TLV::TLVWriter & writer, TLV::Tag tag) const = 0;
43 : };
44 :
45 : /// An `EncodableToTLV` that uses `DataModel::Encode` to encode things in one call.
46 : ///
47 : /// Applicable to any type for which `chip::app::DataModel::Encode` works. In
48 : /// particular, types like <ClusterName>::Commands::<CommandName>::Type
49 : /// can be used as a type here.
50 : template <typename T>
51 : class EncodableType : public EncodableToTLV
52 : {
53 : public:
54 : /// Encodes the given value via `DataModel::Encode` when the underlying
55 : /// encode is called.
56 : ///
57 : /// LIFETIME NOTE: uses a reference to value, so value must live longer than
58 : /// this object.
59 0 : EncodableType(const T & value) : mValue(value) {}
60 :
61 0 : CHIP_ERROR EncodeTo(TLV::TLVWriter & writer, TLV::Tag tag) const override { return DataModel::Encode(writer, tag, mValue); }
62 :
63 : private:
64 : const T & mValue;
65 : };
66 :
67 : } // namespace DataModel
68 : } // namespace app
69 : } // namespace chip
|