2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <type_traits>
21 #include <folly/Bits.h>
22 #include <folly/io/Cursor.h>
23 #include <folly/io/IOBuf.h>
26 * Helper functions for compression codecs.
30 namespace compression {
34 * Reads sizeof(T) bytes, and returns false if not enough bytes are available.
35 * Returns true if the first n bytes are equal to prefix when interpreted as
39 typename std::enable_if<std::is_unsigned<T>::value, bool>::type
40 dataStartsWithLE(const IOBuf* data, T prefix, uint64_t n = sizeof(T)) {
42 DCHECK_LE(n, sizeof(T));
45 if (!cursor.tryReadLE(value)) {
48 const T mask = n == sizeof(T) ? T(-1) : (T(1) << (8 * n)) - 1;
49 return prefix == (value & mask);
53 typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type
54 prefixToStringLE(T prefix, uint64_t n = sizeof(T)) {
56 DCHECK_LE(n, sizeof(T));
57 prefix = Endian::little(prefix);
60 memcpy(&result[0], &prefix, n);
65 } // namespace compression