NumberParser.hxx 2.6 KB
Newer Older
1
/*
2
 * Copyright 2009-2019 Max Kellermann <max.kellermann@gmail.com>
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 * http://www.musicpd.org
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef NUMBER_PARSER_HXX
#define NUMBER_PARSER_HXX

34
#include <cassert>
35
#include <cstdint>
36

37 38
#include <stdlib.h>

39 40
struct StringView;

41
static inline unsigned
42
ParseUnsigned(const char *p, char **endptr=nullptr, int base=10) noexcept
43
{
44
	assert(p != nullptr);
45

46
	return (unsigned)strtoul(p, endptr, base);
47 48 49
}

static inline int
50
ParseInt(const char *p, char **endptr=nullptr, int base=10) noexcept
51
{
52
	assert(p != nullptr);
53

54
	return (int)strtol(p, endptr, base);
55 56 57
}

static inline uint64_t
58
ParseUint64(const char *p, char **endptr=nullptr, int base=10) noexcept
59
{
60
	assert(p != nullptr);
61

62
	return strtoull(p, endptr, base);
63 64 65
}

static inline int64_t
66
ParseInt64(const char *p, char **endptr=nullptr, int base=10) noexcept
67
{
68
	assert(p != nullptr);
69

70
	return strtoll(p, endptr, base);
71 72
}

73 74 75
int64_t
ParseInt64(StringView s, const char **endptr_r=nullptr, int base=10) noexcept;

76
static inline double
77
ParseDouble(const char *p, char **endptr=nullptr) noexcept
78
{
79
	assert(p != nullptr);
80

81
	return (double)strtod(p, endptr);
82 83
}

84
static inline float
85
ParseFloat(const char *p, char **endptr=nullptr) noexcept
86
{
87 88
#if defined(__BIONIC__) && __ANDROID_API__ < 21
	/* strtof() requires API level 21 */
89
	return (float)ParseDouble(p, endptr);
90 91 92
#else
	return strtof(p, endptr);
#endif
93 94
}

95
#endif