blob: c72489a7b36c0b4e685f87f35a925d18e7ee7a7f [file] [log] [blame]
Yi Tseng82512da2017-08-16 19:46:36 -07001/*
Carmelo Cascone4c289b72019-01-22 15:30:45 -08002 * Copyright 2019-present Open Networking Foundation
Yi Tseng82512da2017-08-16 19:46:36 -07003 *
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
Carmelo Cascone4c289b72019-01-22 15:30:45 -080017package org.onosproject.p4runtime.ctl.codec;
Yi Tseng82512da2017-08-16 19:46:36 -070018
19import com.google.protobuf.ByteString;
20
21import static java.lang.String.format;
22
23/**
Carmelo Cascone4c289b72019-01-22 15:30:45 -080024 * Codec utilities.
Yi Tseng82512da2017-08-16 19:46:36 -070025 */
Carmelo Cascone4c289b72019-01-22 15:30:45 -080026final class Utils {
Yi Tseng82512da2017-08-16 19:46:36 -070027
Carmelo Cascone4c289b72019-01-22 15:30:45 -080028 private Utils() {
Yi Tseng82512da2017-08-16 19:46:36 -070029 // Hide default construction
30 }
31
32 static void assertSize(String entityDescr, ByteString value, int bitWidth)
Carmelo Cascone99c59db2019-01-17 15:39:35 -080033 throws CodecException {
Yi Tseng82512da2017-08-16 19:46:36 -070034
35 int byteWidth = (int) Math.ceil((float) bitWidth / 8);
36 if (value.size() != byteWidth) {
Carmelo Cascone99c59db2019-01-17 15:39:35 -080037 throw new CodecException(format(
38 "Wrong size for %s, expected %d bytes, but found %d",
39 entityDescr, byteWidth, value.size()));
Yi Tseng82512da2017-08-16 19:46:36 -070040 }
41 }
42
43 static void assertPrefixLen(String entityDescr, int prefixLength, int bitWidth)
Carmelo Cascone99c59db2019-01-17 15:39:35 -080044 throws CodecException {
Yi Tseng82512da2017-08-16 19:46:36 -070045
46 if (prefixLength > bitWidth) {
Carmelo Cascone99c59db2019-01-17 15:39:35 -080047 throw new CodecException(format(
Yi Tseng82512da2017-08-16 19:46:36 -070048 "wrong prefix length for %s, field size is %d bits, but found one is %d",
49 entityDescr, bitWidth, prefixLength));
50 }
51 }
Yi Tseng82512da2017-08-16 19:46:36 -070052}