Loading...
/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
 *
 * Copyright (c) 2021 Apple Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef BitUtils_h
#define BitUtils_h

// TODO: This can be removed once <bit> works completely in Driverkit builds

#include <bit>
#include <cstdint>

namespace lsl {
inline
__attribute__ ((__const__))
uint64_t bit_ceil(uint64_t value) {
    value--;
    value |= value >> 1;
    value |= value >> 2;
    value |= value >> 4;
    value |= value >> 8;
    value |= value >> 16;
    value |= value >> 32;
    value++;
    return value;
}

inline
__attribute__ ((__const__))
uint64_t bit_width(uint64_t value) {
    return std::numeric_limits<uint64_t>::digits - std::countl_zero(value);
}

template<uint64_t SIZE>
inline
__attribute__((__const__))
uint64_t roundDownToAligned(uint64_t value) {
    static_assert(std::popcount(SIZE) == 1);
    return (value & ~(SIZE-1));
}

template<uint64_t SIZE>
inline
__attribute__((__const__))
uint64_t roundToNextAligned(uint64_t value) {
    static_assert(std::popcount(SIZE) == 1);
    return (value+(SIZE-1) & (-1*SIZE));
}

inline
uint64_t roundDownToAligned(uint64_t alignment, uint64_t value) {
    return (value & ~(alignment-1));
}

inline
uint64_t roundToNextAligned(uint64_t alignment, uint64_t value) {
    return (value+(alignment-1) & (-1*alignment));
}

};

#endif /* BitUtils_h */