1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef FLUTTER_FML_BASE32_H_
6#define FLUTTER_FML_BASE32_H_
7
8#include <string_view>
9#include <utility>
10
11#include "flutter/fml/logging.h"
12
13namespace fml {
14
15template <int from_length, int to_length, int buffer_length>
16class BitConverter {
17 public:
18 void Append(int bits) {
19 FML_DCHECK(bits < (1 << from_length));
20 FML_DCHECK(CanAppend());
21 lower_free_bits_ -= from_length;
22 buffer_ |= (bits << lower_free_bits_);
23 }
24
25 int Extract() {
26 FML_DCHECK(CanExtract());
27 int result = Peek();
28 buffer_ = (buffer_ << to_length) & mask_;
29 lower_free_bits_ += to_length;
30 return result;
31 }
32
33 int Peek() const { return (buffer_ >> (buffer_length - to_length)); }
34 int BitsAvailable() const { return buffer_length - lower_free_bits_; }
35 bool CanAppend() const { return lower_free_bits_ >= from_length; }
36 bool CanExtract() const { return BitsAvailable() >= to_length; }
37
38 private:
39 static_assert(buffer_length >= 2 * from_length);
40 static_assert(buffer_length >= 2 * to_length);
41 static_assert(buffer_length < sizeof(int) * 8);
42
43 static constexpr int mask_ = (1 << buffer_length) - 1;
44
45 int buffer_ = 0;
46 int lower_free_bits_ = buffer_length;
47};
48
49using Base32DecodeConverter = BitConverter<5, 8, 16>;
50using Base32EncodeConverter = BitConverter<8, 5, 16>;
51
52std::pair<bool, std::string> Base32Encode(std::string_view input);
53std::pair<bool, std::string> Base32Decode(const std::string& input);
54
55} // namespace fml
56
57#endif // FLUTTER_FML_BASE32_H_
58