misc_utils.h revision 6ca7b54de22e93958b79bae0a4428107e08cb778
1/*
2 * hidl interface for wpa_supplicant daemon
3 * Copyright (c) 2004-2016, Jouni Malinen <j@w1.fi>
4 * Copyright (c) 2004-2016, Roshan Pius <rpius@google.com>
5 *
6 * This software may be distributed under the terms of the BSD license.
7 * See README for more details.
8 */
9
10#ifndef MISC_UTILS_H_
11#define MISC_UTILS_H_
12
13extern "C" {
14#include "wpabuf.h"
15}
16
17namespace {
18constexpr size_t kWpsPinNumDigits = 8;
19// Custom deleter for wpabuf.
20void freeWpaBuf(wpabuf *ptr) { wpabuf_free(ptr); }
21}  // namespace
22
23namespace android {
24namespace hardware {
25namespace wifi {
26namespace supplicant {
27namespace V1_1 {
28namespace implementation {
29namespace misc_utils {
30using wpabuf_unique_ptr = std::unique_ptr<wpabuf, void (*)(wpabuf *)>;
31
32// Creates a unique_ptr for wpabuf ptr with a custom deleter.
33inline wpabuf_unique_ptr createWpaBufUniquePtr(struct wpabuf *raw_ptr)
34{
35	return {raw_ptr, freeWpaBuf};
36}
37
38// Creates a wpabuf ptr with a custom deleter copying the data from the provided
39// vector.
40inline wpabuf_unique_ptr convertVectorToWpaBuf(const std::vector<uint8_t> &data)
41{
42	return createWpaBufUniquePtr(
43	    wpabuf_alloc_copy(data.data(), data.size()));
44}
45
46// Copies the provided wpabuf contents to a std::vector.
47inline std::vector<uint8_t> convertWpaBufToVector(const struct wpabuf *buf)
48{
49	if (buf) {
50		return std::vector<uint8_t>(
51		    wpabuf_head_u8(buf), wpabuf_head_u8(buf) + wpabuf_len(buf));
52	} else {
53		return std::vector<uint8_t>();
54	}
55}
56
57// Returns a string holding the wps pin.
58inline std::string convertWpsPinToString(int pin)
59{
60	char pin_str[kWpsPinNumDigits + 1];
61	snprintf(pin_str, sizeof(pin_str), "%08d", pin);
62	return pin_str;
63}
64
65}  // namespace misc_utils
66}  // namespace implementation
67}  // namespace V1_1
68}  // namespace supplicant
69}  // namespace wifi
70}  // namespace hardware
71}  // namespace android
72#endif  // MISC_UTILS_H_
73