1 /*
2  * Copyright 2019 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 "fields/count_field.h"
18 #include "util.h"
19 
20 const std::string CountField::kFieldType = "CountField";
21 
CountField(std::string name,int size,ParseLocation loc)22 CountField::CountField(std::string name, int size, ParseLocation loc)
23     : ScalarField(name + "_count", size, loc), sized_field_name_(name) {}
24 
GetFieldType() const25 const std::string& CountField::GetFieldType() const {
26   return CountField::kFieldType;
27 }
28 
GenGetter(std::ostream & s,Size start_offset,Size end_offset) const29 void CountField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) const {
30   s << "protected:";
31   ScalarField::GenGetter(s, start_offset, end_offset);
32   s << "public:\n";
33 }
34 
GenBuilderParameter(std::ostream &) const35 bool CountField::GenBuilderParameter(std::ostream&) const {
36   // There is no builder parameter for a size field
37   return false;
38 }
39 
HasParameterValidator() const40 bool CountField::HasParameterValidator() const {
41   return false;
42 }
43 
GenParameterValidator(std::ostream &) const44 void CountField::GenParameterValidator(std::ostream&) const {
45   // There is no builder parameter for a size field
46   // TODO: Check if the payload fits in the packet?
47 }
48 
GenInserter(std::ostream &) const49 void CountField::GenInserter(std::ostream&) const {
50   ERROR(this) << __func__ << ": This should not be called for count fields";
51 }
52 
GenValidator(std::ostream &) const53 void CountField::GenValidator(std::ostream&) const {
54   // Do nothing since the fixed count fields will be handled specially.
55 }
56 
GetSizedFieldName() const57 std::string CountField::GetSizedFieldName() const {
58   return sized_field_name_;
59 }
60 
GenRustWriter(std::ostream & s,Size start_offset,Size) const61 void CountField::GenRustWriter(std::ostream& s, Size start_offset, Size) const {
62   s << "buffer[" << start_offset.bytes() << "..";
63   s << start_offset.bytes() + GetSize().bytes() << "].copy_from_slice(&";
64   s << "(self." << GetSizedFieldName() << ".len() as u8).to_le_bytes());";
65 }
66