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 <lib/core/CHIPError.h>
22 : #include <lib/core/TLV.h>
23 :
24 : namespace chip {
25 : namespace app {
26 : namespace DataModel {
27 :
28 : /// Defines an abstract class of something that can be encoded
29 : /// into a TLV with a given data tag
30 : class EncodableToTLV
31 : {
32 : public:
33 17 : virtual ~EncodableToTLV() = default;
34 :
35 : virtual CHIP_ERROR EncodeTo(TLV::TLVWriter & writer, TLV::Tag tag) const = 0;
36 : };
37 :
38 : /// An `EncodableToTLV` that uses `DataModel::Encode` to encode things in one call.
39 : ///
40 : /// Applicable to any type for which `chip::app::DataModel::Encode` works. In
41 : /// particular, types like <ClusterName>::Commands::<CommandName>::Type
42 : /// can be used as a type here.
43 : template <typename T>
44 : class EncodableType : public EncodableToTLV
45 : {
46 : public:
47 : /// Encodes the given value via `DataModel::Encode` when the underlying
48 : /// encode is called.
49 : ///
50 : /// LIFETIME NOTE: uses a reference to value, so value must live longer than
51 : /// this object.
52 0 : EncodableType(const T & value) : mValue(value) {}
53 :
54 0 : CHIP_ERROR EncodeTo(TLV::TLVWriter & writer, TLV::Tag tag) const override { return DataModel::Encode(writer, tag, mValue); }
55 :
56 : private:
57 : const T & mValue;
58 : };
59 :
60 : } // namespace DataModel
61 : } // namespace app
62 : } // namespace chip
|