github.com/primecitizens/pcz/std@v0.2.1/core/sys/os_js.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright 2023 The Prime Citizens
     3  
     4  //go:build !noos && js
     5  
     6  package sys
     7  
     8  import (
     9  	"unsafe"
    10  
    11  	"github.com/primecitizens/pcz/std/core/sys/bindings"
    12  	"github.com/primecitizens/pcz/std/ffi/js"
    13  )
    14  
    15  var (
    16  	args []string
    17  	envs []string
    18  )
    19  
    20  func ntharg(i int) string {
    21  	return args[i]
    22  }
    23  
    24  func nthenv(i int) string {
    25  	return envs[i]
    26  }
    27  
    28  func init() {
    29  	var (
    30  		count     uint32
    31  		totalSize = uintptr(
    32  			bindings.Sizes(
    33  				js.Pointer(&count),
    34  			),
    35  		)
    36  
    37  		i uint32
    38  		n int32
    39  	)
    40  
    41  	if count == 0 || totalSize == 0 {
    42  		return
    43  	}
    44  
    45  	totalSize += unsafe.Sizeof(string("")) * uintptr(count)
    46  
    47  	buf := make([]byte, totalSize)
    48  	args = unsafe.Slice(
    49  		(*string)(unsafe.Pointer(unsafe.SliceData(buf))),
    50  		count,
    51  	)
    52  	buf = buf[unsafe.Sizeof(string(""))*uintptr(count):]
    53  
    54  	for i = 0; ; i++ {
    55  		n = bindings.Nth(
    56  			i,
    57  			js.SliceData(buf),
    58  			js.SizeU(len(buf)),
    59  		)
    60  		if n == -1 {
    61  			break
    62  		}
    63  
    64  		args[i] = unsafe.String(unsafe.SliceData(buf), n)
    65  		buf = buf[n:]
    66  	}
    67  
    68  	envs = args[i:]
    69  	args = args[:i]
    70  
    71  	for {
    72  		i++
    73  		n = bindings.Nth(
    74  			i,
    75  			js.SliceData(buf),
    76  			js.SizeU(len(buf)),
    77  		)
    78  		if n == -1 {
    79  			break
    80  		}
    81  
    82  		envs[i-uint32(len(args))-1] = unsafe.String(unsafe.SliceData(buf), n)
    83  		buf = buf[n:]
    84  	}
    85  }