github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/ekastr/itoa.go (about)

     1  // Copyright © 2020. All rights reserved.
     2  // Author: Ilya Yuryevich.
     3  // Contacts: iyuryevich@pm.me, https://github.com/qioalice
     4  // License: https://opensource.org/licenses/MIT
     5  
     6  package ekastr
     7  
     8  //
     9  func PItoa32(i int32) (requiredBytes int) {
    10  	return PItoa64(int64(i))
    11  }
    12  
    13  //
    14  func PItoa64(i int64) (requiredBytes int) {
    15  
    16  	if i < 0 {
    17  		i = -i
    18  		requiredBytes += 1
    19  	}
    20  
    21  	switch {
    22  
    23  	case i < 10:
    24  		requiredBytes += 1
    25  
    26  	case i < 100:
    27  		requiredBytes += 2
    28  
    29  	case i < 1_000:
    30  		requiredBytes += 3
    31  
    32  	case i < 10_000:
    33  		requiredBytes += 4
    34  
    35  	case i < 100_000:
    36  		requiredBytes += 5
    37  
    38  	case i < 1_000_000:
    39  		requiredBytes += 6
    40  
    41  	case i < 10_000_000:
    42  		requiredBytes += 7
    43  
    44  	case i < 100_000_000:
    45  		requiredBytes += 8
    46  
    47  	case i < 1_000_000_000:
    48  		requiredBytes += 9
    49  
    50  	case i < 10_000_000_000:
    51  		requiredBytes += 10
    52  
    53  	case i < 100_000_000_000:
    54  		requiredBytes += 11
    55  
    56  	case i < 1_000_000_000_000:
    57  		requiredBytes += 12
    58  
    59  	case i < 10_000_000_000_000:
    60  		requiredBytes += 13
    61  
    62  	case i < 100_000_000_000_000:
    63  		requiredBytes += 14
    64  
    65  	case i < 1_000_000_000_000_000:
    66  		requiredBytes += 15
    67  
    68  	case i < 10_000_000_000_000_000:
    69  		requiredBytes += 16
    70  
    71  	case i < 100_000_000_000_000_000:
    72  		requiredBytes += 17
    73  
    74  	case i < 1_000_000_000_000_000_000:
    75  		requiredBytes += 18
    76  
    77  	default:
    78  		// i is int32 and max(int32) == 9_223_372_036_854_775_807
    79  		requiredBytes += 19
    80  	}
    81  
    82  	return requiredBytes
    83  }
    84  
    85  //
    86  func BItoa32(to []byte, i int32) (n int) {
    87  	return BItoa64(to, int64(i))
    88  }
    89  
    90  //
    91  func BItoa64(to []byte, i int64) (n int) {
    92  
    93  	idx := PItoa64(i)
    94  	if len(to) < idx {
    95  		return -1
    96  	}
    97  
    98  	if i < 0 {
    99  		i = -i
   100  		to[0] = '-'
   101  	}
   102  
   103  	n = idx
   104  	for idx--; i != 0; idx-- {
   105  		to[idx] = byte(i%10) + '0'
   106  		i /= 10
   107  	}
   108  
   109  	return n
   110  }