github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/lnutil/stdlib.go (about) 1 package lnutil 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 7 "github.com/mit-dci/lit/logging" 8 ) 9 10 // I shouldn't even have to write these... 11 12 // int32 to 4 bytes. Always works. 13 func I32tB(i int32) []byte { 14 var buf bytes.Buffer 15 binary.Write(&buf, binary.BigEndian, i) 16 return buf.Bytes() 17 } 18 19 // uint32 to 4 bytes. Always works. 20 func U32tB(i uint32) []byte { 21 var buf bytes.Buffer 22 binary.Write(&buf, binary.BigEndian, i) 23 return buf.Bytes() 24 } 25 26 // 4 byte slice to uint32. Returns ffffffff if something doesn't work. 27 func BtU32(b []byte) uint32 { 28 if len(b) != 4 { 29 logging.Errorf("Got %x to BtU32 (%d bytes)\n", b, len(b)) 30 return 0xffffffff 31 } 32 var i uint32 33 buf := bytes.NewBuffer(b) 34 binary.Read(buf, binary.BigEndian, &i) 35 return i 36 } 37 38 // 4 byte slice to int32. Returns 7fffffff if something doesn't work. 39 func BtI32(b []byte) int32 { 40 if len(b) != 4 { 41 logging.Errorf("Got %x to BtI32 (%d bytes)\n", b, len(b)) 42 return 0x7fffffff 43 } 44 var i int32 45 buf := bytes.NewBuffer(b) 46 binary.Read(buf, binary.BigEndian, &i) 47 return i 48 } 49 50 // uint64 to 8 bytes. Always works. 51 func U64tB(i uint64) []byte { 52 var buf bytes.Buffer 53 binary.Write(&buf, binary.BigEndian, i) 54 return buf.Bytes() 55 } 56 57 // int64 to 8 bytes. Always works. 58 func I64tB(i int64) []byte { 59 var buf bytes.Buffer 60 binary.Write(&buf, binary.BigEndian, i) 61 return buf.Bytes() 62 } 63 64 // 8 bytes to int64 (bitcoin amounts). returns 7fff... if it doesn't work. 65 func BtI64(b []byte) int64 { 66 if len(b) != 8 { 67 logging.Errorf("Got %x to BtI64 (%d bytes)\n", b, len(b)) 68 return 0x7fffffffffffffff 69 } 70 var i int64 71 buf := bytes.NewBuffer(b) 72 binary.Read(buf, binary.BigEndian, &i) 73 return i 74 } 75 76 // 8 bytes to uint64. returns ffff. if it doesn't work. 77 func BtU64(b []byte) uint64 { 78 if len(b) != 8 { 79 logging.Errorf("Got %x to BtU64 (%d bytes)\n", b, len(b)) 80 return 0xffffffffffffffff 81 } 82 var i uint64 83 buf := bytes.NewBuffer(b) 84 binary.Read(buf, binary.BigEndian, &i) 85 return i 86 } 87 88 // NopeString returns true if the string means "nope" 89 func NopeString(s string) bool { 90 nopes := []string{ 91 "nope", "no", "n", "false", "0", "nil", "null", "disable", "off", "", 92 } 93 for _, ts := range nopes { 94 if ts == s { 95 return true 96 } 97 } 98 return false 99 } 100 101 // YupString returns true if the string means "yup" 102 func YupString(s string) bool { 103 yups := []string{ 104 "yup", "yes", "y", "true", "1", "ok", "enable", "on", 105 } 106 for _, ts := range yups { 107 if ts == s { 108 return true 109 } 110 } 111 return false 112 }