PcmUtils.hxx 1.79 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2013 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20 21
#ifndef MPD_PCM_UTILS_H
#define MPD_PCM_UTILS_H
Warren Dukes's avatar
Warren Dukes committed
22

23
#include "Compiler.h"
24

25 26
#include <limits>

27
#include <stdint.h>
28

29 30 31 32 33
/**
 * Add a byte count to the specified pointer.  This is a utility
 * function to convert a source pointer and a byte count to an "end"
 * pointer for use in loops.
 */
Max Kellermann's avatar
Max Kellermann committed
34 35 36
template<typename T>
static inline const T *
pcm_end_pointer(const T *p, size_t size)
37
{
Max Kellermann's avatar
Max Kellermann committed
38
	return (const T *)((const uint8_t *)p + size);
39 40
}

41 42 43 44
/**
 * Check if the value is within the range of the provided bit size,
 * and caps it if necessary.
 */
45
template<typename T, typename U, unsigned bits>
46
gcc_const
47 48
static inline T
PcmClamp(U x)
49
{
50 51
	constexpr U MIN_VALUE = -(U(1) << (bits - 1));
	constexpr U MAX_VALUE = (U(1) << (bits - 1)) - 1;
52 53 54 55

	typedef std::numeric_limits<T> limits;
	static_assert(MIN_VALUE >= limits::min(), "out of range");
	static_assert(MAX_VALUE <= limits::max(), "out of range");
56

57
	if (gcc_unlikely(x < MIN_VALUE))
58 59
		return T(MIN_VALUE);

60
	if (gcc_unlikely(x > MAX_VALUE))
61 62 63 64 65
		return T(MAX_VALUE);

	return T(x);
}

Warren Dukes's avatar
Warren Dukes committed
66
#endif