github.com/trim21/go-phpserialize@v0.0.22-0.20240301204449-2fca0319b3f0/internal/encoder/int_as_string.go (about) 1 package encoder 2 3 import ( 4 "fmt" 5 "reflect" 6 "strconv" 7 "unsafe" 8 9 "github.com/trim21/go-phpserialize/internal/runtime" 10 ) 11 12 func compileIntAsString(typ *runtime.Type) (encoder, error) { 13 switch typ.Kind() { 14 case reflect.Int8: 15 return encodeInt8AsString, nil 16 case reflect.Int16: 17 return encodeInt16AsString, nil 18 case reflect.Int32: 19 return encodeInt32AsString, nil 20 case reflect.Int64: 21 return encodeInt64AsString, nil 22 case reflect.Int: 23 return encodeIntAsString, nil 24 } 25 26 panic(fmt.Sprintf("unexpected kind %s", typ.Kind())) 27 } 28 29 func encodeInt8AsString(ctx *Ctx, b []byte, p uintptr) ([]byte, error) { 30 value := **(**int8)(unsafe.Pointer(&p)) 31 return appendIntAsString(b, int64(value)) 32 33 } 34 35 func encodeInt16AsString(ctx *Ctx, b []byte, p uintptr) ([]byte, error) { 36 value := **(**int16)(unsafe.Pointer(&p)) 37 return appendIntAsString(b, int64(value)) 38 39 } 40 41 func encodeInt32AsString(ctx *Ctx, b []byte, p uintptr) ([]byte, error) { 42 value := **(**int32)(unsafe.Pointer(&p)) 43 return appendIntAsString(b, int64(value)) 44 45 } 46 47 func encodeInt64AsString(ctx *Ctx, b []byte, p uintptr) ([]byte, error) { 48 value := **(**int64)(unsafe.Pointer(&p)) 49 return appendIntAsString(b, int64(value)) 50 51 } 52 53 func encodeIntAsString(ctx *Ctx, b []byte, p uintptr) ([]byte, error) { 54 value := **(**int)(unsafe.Pointer(&p)) 55 return appendIntAsString(b, int64(value)) 56 } 57 58 func appendIntAsString(b []byte, v int64) ([]byte, error) { 59 b = appendStringHead(b, iterativeDigitsCount(v)) 60 b = append(b, '"') 61 b = strconv.AppendInt(b, v, 10) 62 return append(b, '"', ';'), nil 63 } 64 65 func iterativeDigitsCount(number int64) int64 { 66 var count int64 67 if number <= 0 { 68 count++ 69 } 70 71 for number != 0 { 72 number /= 10 73 count += 1 74 } 75 76 return count 77 }