1 //------------------------------------------------------------------------------
2 // GB_Index_multiply:  multiply two integers 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 where c is GrB_Index (uint64_t), and a and b are int64_t.
11 // Check for overflow.  Requires a >= 0 and b >= 0.
12 
13 #include "GB.h"
14 
GB_Index_multiply(GrB_Index * restrict c,const int64_t a,const int64_t b)15 bool GB_Index_multiply      // true if ok, false if overflow
16 (
17     GrB_Index *restrict c,  // c = a*b, or zero if overflow occurs
18     const int64_t a,
19     const int64_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 < 0 || a > GxB_INDEX_MAX || b < 0 || b > GxB_INDEX_MAX)
32     {
33         // a or b are out of range
34         return (false) ;
35     }
36 
37     if (GB_CEIL_LOG2 (a) + GB_CEIL_LOG2 (b) > 60)
38     {
39         // a * b may overflow
40         return (false) ;
41     }
42 
43     // a * b will not overflow
44     (*c) = a * b ;
45     return (true) ;
46 }
47 
48