github.com/gotranspile/cxgo@v0.3.7/libs/limits.go (about)

     1  package libs
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"strings"
     7  
     8  	"github.com/gotranspile/cxgo/types"
     9  )
    10  
    11  const (
    12  	limitsH = "limits.h"
    13  )
    14  
    15  func init() {
    16  	RegisterLibrary(limitsH, func(c *Env) *Library {
    17  		var buf strings.Builder
    18  		buf.WriteString("#define CHAR_BIT 8\n")
    19  
    20  		idents := make(map[string]*types.Ident)
    21  		intMinMax(&buf, idents, "SCHAR", "Int", math.MinInt8, math.MaxInt8, 8)
    22  		uintMax(&buf, idents, "UCHAR", "Uint", math.MaxUint8, 8)
    23  		intMinMax(&buf, idents, "CHAR", "Int", math.MinInt8, math.MaxInt8, 8)
    24  
    25  		intMinMax(&buf, idents, "SHRT", "Int", math.MinInt16, math.MaxInt16, 16)
    26  		uintMax(&buf, idents, "USHRT", "Uint", math.MaxUint16, 16)
    27  
    28  		switch c.IntSize() {
    29  		case 4:
    30  			intMinMax(&buf, idents, "INT", "Int", math.MinInt32, math.MaxInt32, 32)
    31  			uintMax(&buf, idents, "UINT", "Uint", math.MaxUint32, 32)
    32  			intMinMax(&buf, idents, "LONG", "Int", math.MinInt32, math.MaxInt32, 32)
    33  			uintMax(&buf, idents, "ULONG", "Uint", math.MaxUint32, 32)
    34  		case 8:
    35  			intMinMax(&buf, idents, "INT", "Int", math.MinInt64, math.MaxInt64, 64)
    36  			uintMax(&buf, idents, "UINT", "Uint", math.MaxUint64, 64)
    37  			intMinMax(&buf, idents, "LONG", "Int", math.MinInt64, math.MaxInt64, 64)
    38  			uintMax(&buf, idents, "ULONG", "Uint", math.MaxUint64, 64)
    39  		}
    40  
    41  		intMinMax(&buf, idents, "LLONG", "Int", math.MinInt64, math.MaxInt64, 64)
    42  		uintMax(&buf, idents, "ULLONG", "Uint", math.MaxUint64, 64)
    43  
    44  		return &Library{
    45  			Idents: idents,
    46  			Header: buf.String(),
    47  		}
    48  	})
    49  }
    50  
    51  func uintMax(buf *strings.Builder, m map[string]*types.Ident, cPref, goPref string, max uint64, size int) {
    52  	cName := cPref + "_MAX"
    53  	if m != nil && goPref != "" {
    54  		m[cName] = types.NewIdentGo(cName, fmt.Sprintf("math.Max%s%d", goPref, size), types.UntypedIntT(size/8))
    55  	}
    56  	_, _ = fmt.Fprintf(buf, "#define %s %du\n", cName, max)
    57  }
    58  
    59  func intMinMax(buf *strings.Builder, m map[string]*types.Ident, cPref, goPref string, min, max int64, size int) {
    60  	cName := cPref + "_MIN"
    61  	if m != nil && goPref != "" {
    62  		m[cName] = types.NewIdentGo(cName, fmt.Sprintf("math.Min%s%d", goPref, size), types.UntypedIntT(size/8))
    63  	}
    64  	_, _ = fmt.Fprintf(buf, "#define %s %d\n", cName, min)
    65  	uintMax(buf, m, cPref, goPref, uint64(max), size)
    66  }