1 /* @(#)type_val.h	1.2 19/08/17 Copyright 2002-2019 J. Schilling */
2 /*
3  *	Definitions to define the maximum and minimum values
4  *	for all scalar types.
5  *
6  *	Copyright (c) 2002-2019 J. Schilling
7  */
8 /*
9  * The contents of this file are subject to the terms of the
10  * Common Development and Distribution License, Version 1.0 only
11  * (the "License").  You may not use this file except in compliance
12  * with the License.
13  *
14  * See the file CDDL.Schily.txt in this distribution for details.
15  * A copy of the CDDL is also available via the Internet at
16  * http://www.opensource.org/licenses/cddl1.txt
17  *
18  * When distributing Covered Code, include this CDDL HEADER in each
19  * file and include the License file CDDL.Schily.txt from this distribution.
20  */
21 
22 #ifndef	_SCHILY_TYPE_VAL_H
23 #define	_SCHILY_TYPE_VAL_H
24 
25 #ifndef	_SCHILY_MCONFIG_H
26 #include <schily/mconfig.h>
27 #endif
28 
29 /*
30  * Let us include system defined types too.
31  */
32 #ifndef	_SCHILY_TYPES_H
33 #include <schily/types.h>
34 #endif
35 /*
36  * Include sys/param.h for NBBY - needed in case that CHAR_BIT is missing
37  */
38 #ifndef	_SCHILY_PARAM_H
39 #include <schily/param.h>	/* Must be before limits.h */
40 #endif
41 
42 /*
43  * Include limits.h for CHAR_BIT - needed by TYPE_MINVAL(t) and  TYPE_MAXVAL(t)
44  */
45 #ifndef	_SCHILY_LIMITS_H
46 #include <schily/limits.h>
47 #endif
48 
49 #ifndef	CHAR_BIT
50 #ifdef	NBBY
51 #define	CHAR_BIT	NBBY
52 #endif
53 #endif
54 
55 /*
56  * Last resort: define CHAR_BIT by hand
57  */
58 #ifndef	CHAR_BIT
59 #define	CHAR_BIT	8
60 #endif
61 
62 /*
63  * These macros may not work on all platforms but as we depend
64  * on two's complement in many places, they do not reduce portability.
65  * The macros below work with 2s complement and ones complement machines.
66  * Verify with this table...
67  *
68  *	Bits	1's c.	2's complement.
69  * 	100	-3	-4
70  * 	101	-2	-3
71  * 	110	-1	-2
72  * 	111	-0	-1
73  * 	000	+0	 0
74  * 	001	+1	+1
75  * 	010	+2	+2
76  * 	011	+3	+3
77  *
78  * Computing -TYPE_MINVAL(type) will not work on 2's complement machines
79  * if 'type' is int or more. Use:
80  *		((unsigned type)(-1 * (TYPE_MINVAL(type)+1))) + 1;
81  * it works for both 1's complement and 2's complement machines.
82  */
83 #define	TYPE_ISSIGNED(t)	(((t)-1) < ((t)0))
84 #define	TYPE_ISUNSIGNED(t)	(!TYPE_ISSIGNED(t))
85 #if (-3 & 3) == 1		/* Two's complement */
86 #define	TYPE_MSBVAL(t)		(2 * -(((t)1) << (sizeof (t)*CHAR_BIT - 2)))
87 #else
88 #define	TYPE_MSBVAL(t)		((t)(~((t)0) << (sizeof (t)*CHAR_BIT - 1)))
89 #endif
90 #define	TYPE_MINVAL(t)		(TYPE_ISSIGNED(t)			\
91 				    ? TYPE_MSBVAL(t)			\
92 				    : ((t)0))
93 #define	TYPE_MAXVAL(t)		((t)(~((t)0) - TYPE_MINVAL(t)))
94 
95 #endif	/* _SCHILY_TYPE_VAL_H */
96