github.com/primecitizens/pcz/std@v0.2.1/ffi/js/string.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright 2023 The Prime Citizens
     3  
     4  package js
     5  
     6  import (
     7  	"github.com/primecitizens/pcz/std/ffi/js/bindings"
     8  )
     9  
    10  // NewString creates a js string for the string, return the reference to
    11  // the created string.
    12  func NewString(s string) String {
    13  	return String{
    14  		ref: bindings.DecodeUTF8(
    15  			StringData(s),
    16  			SizeU(len(s)),
    17  		),
    18  	}
    19  }
    20  
    21  // A String is a reference to a javascript string.
    22  type String struct {
    23  	ref bindings.Ref
    24  }
    25  
    26  func (s String) FromRef(ref Ref) String {
    27  	return String{
    28  		ref: bindings.Ref(ref),
    29  	}
    30  }
    31  
    32  func (s String) Ref() Ref {
    33  	return Ref(s.ref)
    34  }
    35  
    36  func (s String) Once() String {
    37  	bindings.Once(s.ref)
    38  	return s
    39  }
    40  
    41  func (s String) Free() {
    42  	bindings.Free(s.ref)
    43  }
    44  
    45  func (s String) Equals(other string) bool {
    46  	return bindings.Ref(True) == bindings.EqualsUTF8(
    47  		s.ref,
    48  		StringData(other),
    49  		SizeU(len(other)),
    50  	)
    51  }
    52  
    53  func (s String) Prepend(ss ...string) String {
    54  	if len(ss) != 0 {
    55  		bindings.PrependUTF8(
    56  			s.ref,
    57  			SliceData(ss),
    58  			SizeU(len(ss)),
    59  		)
    60  	}
    61  	return s
    62  }
    63  
    64  func (s String) PrependString(take bool, ss ...String) String {
    65  	if len(ss) != 0 {
    66  		bindings.PrependString(
    67  			s.ref,
    68  			bindings.Ref(Bool(take)),
    69  			SliceData(ss),
    70  			SizeU(len(ss)),
    71  		)
    72  	}
    73  	return s
    74  }
    75  
    76  func (s String) Append(ss ...string) String {
    77  	if len(ss) != 0 {
    78  		bindings.AppendUTF8(
    79  			s.ref,
    80  			SliceData(ss),
    81  			SizeU(len(ss)),
    82  		)
    83  	}
    84  	return s
    85  }
    86  
    87  func (s String) AppendString(take bool, ss ...String) String {
    88  	if len(ss) != 0 {
    89  		bindings.AppendString(
    90  			s.ref,
    91  			bindings.Ref(Bool(take)),
    92  			SliceData(ss),
    93  			SizeU(len(ss)),
    94  		)
    95  	}
    96  	return s
    97  }
    98  
    99  // Read encodes the js string to buf (UTF-8 encoding) and
   100  // returns the count of bytes encoded.
   101  func (s String) Read(buf []byte) int {
   102  	n := bindings.EncodeUTF8(
   103  		s.ref,
   104  		SliceData(buf),
   105  		SizeU(len(buf)),
   106  	)
   107  	return int(n)
   108  }
   109  
   110  // Len returns the utf-8 length of the js string.
   111  func (s String) Len() int {
   112  	return int(bindings.SizeUTF8(s.ref))
   113  }