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 
17 package com.android.adservices.service.common.bhttp;
18 
19 import static com.android.adservices.service.common.bhttp.Frc9000VariableLengthIntegerUtil.toFrc9000Int;
20 
21 import android.annotation.NonNull;
22 
23 import com.google.auto.value.AutoValue;
24 
25 import java.nio.charset.StandardCharsets;
26 import java.util.Locale;
27 
28 /** Represents a header or trailer field line. */
29 @AutoValue
30 public abstract class Field extends BinaryHttpSerializableComponent {
31     static final int KNOWN_LENGTH_SERIALIZED_ARRAY_LENGTH = 4;
32 
33     /** Returns the name of the field. */
34     @NonNull
getName()35     public abstract String getName();
36 
37     /** Returns the value of the field. */
38     @NonNull
getValue()39     public abstract String getValue();
40 
41     /** Creates a {@link Field} object. */
42     @NonNull
create(@onNull final String name, @NonNull final String value)43     public static Field create(@NonNull final String name, @NonNull final String value) {
44         return new AutoValue_Field(name.toLowerCase(Locale.ENGLISH), value);
45     }
46 
47     /**
48      * {@inheritDoc}
49      *
50      * @return [name length][name][value length][value]
51      */
52     @NonNull
53     @Override
knownLengthSerialize()54     byte[][] knownLengthSerialize() {
55         byte[] name = getName().getBytes(StandardCharsets.UTF_8);
56         byte[] value = getValue().getBytes(StandardCharsets.UTF_8);
57         return new byte[][] {toFrc9000Int(name.length), name, toFrc9000Int(value.length), value};
58     }
59 
60     @Override
getKnownLengthSerializedSectionsCount()61     int getKnownLengthSerializedSectionsCount() {
62         return KNOWN_LENGTH_SERIALIZED_ARRAY_LENGTH;
63     }
64 }
65