1 //------------------------------------------------------------------------------
2 // GB_size_t_multiply: multiply two size_t and guard against overflow
3 //------------------------------------------------------------------------------
4
5 // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
6 // SPDX-License-Identifier: Apache-2.0
7
8 //------------------------------------------------------------------------------
9
10 // c = a*b but check for overflow
11
12 #include "GB.h"
13
14 GB_PUBLIC // accessed by the MATLAB tests in GraphBLAS/Test only
GB_size_t_multiply(size_t * c,const size_t a,const size_t b)15 bool GB_size_t_multiply // true if ok, false if overflow
16 (
17 size_t *c, // c = a*b, or zero if overflow occurs
18 const size_t a,
19 const size_t b
20 )
21 {
22
23 ASSERT (c != NULL) ;
24
25 (*c) = 0 ;
26 if (a == 0 || b == 0)
27 {
28 return (true) ;
29 }
30
31 if (a > SIZE_MAX / 2 || b > SIZE_MAX / 2)
32 {
33 // a or b are out of range
34 return (false) ;
35 }
36
37 // a + b is now safe to compute
38 if ((a + b) > (SIZE_MAX / GB_IMIN (a,b)))
39 {
40 // a * b may overflow
41 return (false) ;
42 }
43
44 // a * b will not overflow
45 (*c) = a * b ;
46 return (true) ;
47 }
48
49