radix.odin 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. /*
  2. Copyright 2021 Jeroen van Rijn <[email protected]>.
  3. Made available under Odin's BSD-3 license.
  4. An arbitrary precision mathematics implementation in Odin.
  5. For the theoretical underpinnings, see Knuth's The Art of Computer Programming, Volume 2, section 4.3.
  6. The code started out as an idiomatic source port of libTomMath, which is in the public domain, with thanks.
  7. This file contains radix conversions, `string_to_int` (atoi) and `int_to_string` (itoa).
  8. TODO:
  9. - Use Barrett reduction for non-powers-of-two.
  10. - Also look at extracting and splatting several digits at once.
  11. */
  12. package math_big
  13. import "core:intrinsics"
  14. import "core:mem"
  15. import "core:os"
  16. /*
  17. This version of `itoa` allocates on behalf of the caller. The caller must free the string.
  18. The radix defaults to 10.
  19. */
  20. int_itoa_string :: proc(a: ^Int, radix := i8(10), zero_terminate := false, allocator := context.allocator) -> (res: string, err: Error) {
  21. assert_if_nil(a)
  22. context.allocator = allocator
  23. a := a; radix := radix
  24. clear_if_uninitialized(a) or_return
  25. /*
  26. TODO: If we want to write a prefix for some of the radixes, we can oversize the buffer.
  27. Then after the digits are written and the string is reversed
  28. */
  29. /*
  30. Calculate the size of the buffer we need, and
  31. Exit if calculating the size returned an error.
  32. */
  33. size := radix_size(a, radix, zero_terminate) or_return
  34. /*
  35. Allocate the buffer we need.
  36. */
  37. buffer := make([]u8, size)
  38. /*
  39. Write the digits out into the buffer.
  40. */
  41. written: int
  42. written, err = int_itoa_raw(a, radix, buffer, size, zero_terminate)
  43. return string(buffer[:written]), err
  44. }
  45. /*
  46. This version of `itoa` allocates on behalf of the caller. The caller must free the string.
  47. The radix defaults to 10.
  48. */
  49. int_itoa_cstring :: proc(a: ^Int, radix := i8(10), allocator := context.allocator) -> (res: cstring, err: Error) {
  50. assert_if_nil(a)
  51. context.allocator = allocator
  52. a := a; radix := radix
  53. clear_if_uninitialized(a) or_return
  54. s: string
  55. s, err = int_itoa_string(a, radix, true)
  56. return cstring(raw_data(s)), err
  57. }
  58. /*
  59. A low-level `itoa` using a caller-provided buffer. `itoa_string` and `itoa_cstring` use this.
  60. You can use also use it if you want to pre-allocate a buffer and optionally reuse it.
  61. Use `radix_size` or `radix_size_estimate` to determine a buffer size big enough.
  62. You can pass the output of `radix_size` to `size` if you've previously called it to size
  63. the output buffer. If you haven't, this routine will call it. This way it knows if the buffer
  64. is the appropriate size, and we can write directly in place without a reverse step at the end.
  65. === === === IMPORTANT === === ===
  66. If you determined the buffer size using `radix_size_estimate`, or have a buffer
  67. that you reuse that you know is large enough, don't pass this size unless you know what you are doing,
  68. because we will always write backwards starting at last byte of the buffer.
  69. Keep in mind that if you set `size` yourself and it's smaller than the buffer,
  70. it'll result in buffer overflows, as we use it to avoid reversing at the end
  71. and having to perform a buffer overflow check each character.
  72. */
  73. int_itoa_raw :: proc(a: ^Int, radix: i8, buffer: []u8, size := int(-1), zero_terminate := false) -> (written: int, err: Error) {
  74. assert_if_nil(a)
  75. a := a; radix := radix; size := size
  76. clear_if_uninitialized(a) or_return
  77. /*
  78. Radix defaults to 10.
  79. */
  80. radix = radix if radix > 0 else 10
  81. if radix < 2 || radix > 64 {
  82. return 0, .Invalid_Argument
  83. }
  84. /*
  85. We weren't given a size. Let's compute it.
  86. */
  87. if size == -1 {
  88. size = radix_size(a, radix, zero_terminate) or_return
  89. }
  90. /*
  91. Early exit if the buffer we were given is too small.
  92. */
  93. available := len(buffer)
  94. if available < size {
  95. return 0, .Buffer_Overflow
  96. }
  97. /*
  98. Fast path for when `Int` == 0 or the entire `Int` fits in a single radix digit.
  99. */
  100. z, _ := is_zero(a)
  101. if z || (a.used == 1 && a.digit[0] < DIGIT(radix)) {
  102. if zero_terminate {
  103. available -= 1
  104. buffer[available] = 0
  105. }
  106. available -= 1
  107. buffer[available] = RADIX_TABLE[a.digit[0]]
  108. if n, _ := is_neg(a); n {
  109. available -= 1
  110. buffer[available] = '-'
  111. }
  112. /*
  113. If we overestimated the size, we need to move the buffer left.
  114. */
  115. written = len(buffer) - available
  116. if written < size {
  117. diff := size - written
  118. mem.copy(&buffer[0], &buffer[diff], written)
  119. }
  120. return written, nil
  121. }
  122. /*
  123. Fast path for when `Int` fits within a `_WORD`.
  124. */
  125. if a.used == 1 || a.used == 2 {
  126. if zero_terminate {
  127. available -= 1
  128. buffer[available] = 0
  129. }
  130. val := _WORD(a.digit[1]) << _DIGIT_BITS + _WORD(a.digit[0])
  131. for val > 0 {
  132. q := val / _WORD(radix)
  133. available -= 1
  134. buffer[available] = RADIX_TABLE[val - (q * _WORD(radix))]
  135. val = q
  136. }
  137. if n, _ := is_neg(a); n {
  138. available -= 1
  139. buffer[available] = '-'
  140. }
  141. /*
  142. If we overestimated the size, we need to move the buffer left.
  143. */
  144. written = len(buffer) - available
  145. if written < size {
  146. diff := size - written
  147. mem.copy(&buffer[0], &buffer[diff], written)
  148. }
  149. return written, nil
  150. }
  151. /*
  152. Fast path for radixes that are a power of two.
  153. */
  154. if is_power_of_two(int(radix)) {
  155. if zero_terminate {
  156. available -= 1
  157. buffer[available] = 0
  158. }
  159. shift, count: int
  160. // mask := _WORD(radix - 1);
  161. shift, err = log(DIGIT(radix), 2)
  162. count, err = count_bits(a)
  163. digit: _WORD
  164. for offset := 0; offset < count; offset += shift {
  165. bits_to_get := int(min(count - offset, shift))
  166. digit, err = int_bitfield_extract(a, offset, bits_to_get)
  167. if err != nil {
  168. return len(buffer) - available, .Invalid_Argument
  169. }
  170. available -= 1
  171. buffer[available] = RADIX_TABLE[digit]
  172. }
  173. if n, _ := is_neg(a); n {
  174. available -= 1
  175. buffer[available] = '-'
  176. }
  177. /*
  178. If we overestimated the size, we need to move the buffer left.
  179. */
  180. written = len(buffer) - available
  181. if written < size {
  182. diff := size - written
  183. mem.copy(&buffer[0], &buffer[diff], written)
  184. }
  185. return written, nil
  186. }
  187. return _itoa_raw_full(a, radix, buffer, zero_terminate)
  188. }
  189. itoa :: proc{int_itoa_string, int_itoa_raw}
  190. int_to_string :: int_itoa_string
  191. int_to_cstring :: int_itoa_cstring
  192. /*
  193. Read a string [ASCII] in a given radix.
  194. */
  195. int_atoi :: proc(res: ^Int, input: string, radix := i8(10), allocator := context.allocator) -> (err: Error) {
  196. assert_if_nil(res)
  197. input := input
  198. context.allocator = allocator
  199. /*
  200. Make sure the radix is ok.
  201. */
  202. if radix < 2 || radix > 64 { return .Invalid_Argument }
  203. /*
  204. Set the integer to the default of zero.
  205. */
  206. internal_zero(res) or_return
  207. /*
  208. We'll interpret an empty string as zero.
  209. */
  210. if len(input) == 0 {
  211. return nil
  212. }
  213. /*
  214. If the leading digit is a minus set the sign to negative.
  215. Given the above early out, the length should be at least 1.
  216. */
  217. sign := Sign.Zero_or_Positive
  218. if input[0] == '-' {
  219. input = input[1:]
  220. sign = .Negative
  221. }
  222. /*
  223. Process each digit of the string.
  224. */
  225. ch: rune
  226. for len(input) > 0 {
  227. /* if the radix <= 36 the conversion is case insensitive
  228. * this allows numbers like 1AB and 1ab to represent the same value
  229. * [e.g. in hex]
  230. */
  231. ch = rune(input[0])
  232. if radix <= 36 && ch >= 'a' && ch <= 'z' {
  233. ch -= 32 // 'a' - 'A'
  234. }
  235. pos := ch - '+'
  236. if RADIX_TABLE_REVERSE_SIZE <= pos {
  237. break
  238. }
  239. y := RADIX_TABLE_REVERSE[pos]
  240. /* if the char was found in the map
  241. * and is less than the given radix add it
  242. * to the number, otherwise exit the loop.
  243. */
  244. if y >= u8(radix) {
  245. break
  246. }
  247. internal_mul(res, res, DIGIT(radix)) or_return
  248. internal_add(res, res, DIGIT(y)) or_return
  249. input = input[1:]
  250. }
  251. /*
  252. If an illegal character was found, fail.
  253. */
  254. if len(input) > 0 && ch != 0 && ch != '\r' && ch != '\n' {
  255. return .Invalid_Argument
  256. }
  257. /*
  258. Set the sign only if res != 0.
  259. */
  260. if res.used > 0 {
  261. res.sign = sign
  262. }
  263. return nil
  264. }
  265. atoi :: proc { int_atoi, }
  266. /*
  267. We size for `string` by default.
  268. */
  269. radix_size :: proc(a: ^Int, radix: i8, zero_terminate := false, allocator := context.allocator) -> (size: int, err: Error) {
  270. a := a
  271. assert_if_nil(a)
  272. if radix < 2 || radix > 64 { return -1, .Invalid_Argument }
  273. clear_if_uninitialized(a) or_return
  274. if internal_is_zero(a) {
  275. if zero_terminate {
  276. return 2, nil
  277. }
  278. return 1, nil
  279. }
  280. if internal_is_power_of_two(a) {
  281. /*
  282. Calculate `log` on a temporary "copy" with its sign set to positive.
  283. */
  284. t := &Int{
  285. used = a.used,
  286. sign = .Zero_or_Positive,
  287. digit = a.digit,
  288. }
  289. size = internal_log(t, DIGIT(radix)) or_return
  290. } else {
  291. la, k := &Int{}, &Int{}
  292. defer internal_destroy(la, k)
  293. /* la = floor(log_2(a)) + 1 */
  294. bit_count := internal_count_bits(a)
  295. internal_set(la, bit_count) or_return
  296. /* k = floor(2^29/log_2(radix)) + 1 */
  297. lb := _log_bases
  298. internal_set(k, lb[radix]) or_return
  299. /* n = floor((la * k) / 2^29) + 1 */
  300. internal_mul(k, la, k) or_return
  301. internal_shr(k, k, _RADIX_SIZE_SCALE) or_return
  302. /* The "+1" here is the "+1" in "floor((la * k) / 2^29) + 1" */
  303. /* n = n + 1 + EOS + sign */
  304. size_, _ := internal_get(k, u128)
  305. size = int(size_)
  306. }
  307. /*
  308. log truncates to zero, so we need to add one more, and one for `-` if negative.
  309. */
  310. size += 2 if a.sign == .Negative else 1
  311. size += 1 if zero_terminate else 0
  312. return size, nil
  313. }
  314. /*
  315. We might add functions to read and write byte-encoded Ints from/to files, using `int_to_bytes_*` functions.
  316. LibTomMath allows exporting/importing to/from a file in ASCII, but it doesn't support a much more compact representation in binary, even though it has several pack functions int_to_bytes_* (which I expanded upon and wrote Python interoperable versions of as well), and (un)pack, which is GMP compatible.
  317. Someone could implement their own read/write binary int procedures, of course.
  318. Could be worthwhile to add a canonical binary file representation with an optional small header that says it's an Odin big.Int, big.Rat or Big.Float, byte count for each component that follows, flag for big/little endian and a flag that says a checksum exists at the end of the file.
  319. For big.Rat and big.Float the header couldn't be optional, because we'd have no way to distinguish where the components end.
  320. */
  321. /*
  322. Read an Int from an ASCII file.
  323. */
  324. internal_int_read_from_ascii_file :: proc(a: ^Int, filename: string, radix := i8(10), allocator := context.allocator) -> (err: Error) {
  325. context.allocator = allocator
  326. /*
  327. We can either read the entire file at once, or read a bunch at a time and keep multiplying by the radix.
  328. For now, we'll read the entire file. Eventually we'll replace this with a copy that duplicates the logic
  329. of `atoi` so we don't need to read the entire file.
  330. */
  331. res, ok := os.read_entire_file(filename, allocator)
  332. defer delete(res, allocator)
  333. if !ok {
  334. return .Cannot_Read_File
  335. }
  336. as := string(res)
  337. return atoi(a, as, radix)
  338. }
  339. /*
  340. Write an Int to an ASCII file.
  341. */
  342. internal_int_write_to_ascii_file :: proc(a: ^Int, filename: string, radix := i8(10), allocator := context.allocator) -> (err: Error) {
  343. context.allocator = allocator
  344. /*
  345. For now we'll convert the Int using itoa and writing the result in one go.
  346. If we want to preserve memory we could duplicate the itoa logic and write backwards.
  347. */
  348. as := itoa(a, radix) or_return
  349. defer delete(as)
  350. l := len(as)
  351. assert(l > 0)
  352. data := transmute([]u8)mem.Raw_Slice{
  353. data = raw_data(as),
  354. len = l,
  355. }
  356. ok := os.write_entire_file(filename, data, truncate=true)
  357. return nil if ok else .Cannot_Write_File
  358. }
  359. /*
  360. Calculate the size needed for `internal_int_pack`.
  361. See https://gmplib.org/manual/Integer-Import-and-Export.html
  362. */
  363. internal_int_pack_count :: proc(a: ^Int, $T: typeid, nails := 0) -> (size_needed: int) {
  364. assert(nails >= 0 && nails < (size_of(T) * 8))
  365. bits := internal_count_bits(a)
  366. size := size_of(T)
  367. size_needed = bits / ((size * 8) - nails)
  368. size_needed += 1 if (bits % ((size * 8) - nails)) != 0 else 0
  369. return size_needed
  370. }
  371. /*
  372. Based on gmp's mpz_export.
  373. See https://gmplib.org/manual/Integer-Import-and-Export.html
  374. `buf` is a pre-allocated slice of type `T` "words", which must be an unsigned integer of some description.
  375. Use `internal_int_pack_count(a, T, nails)` to calculate the necessary size.
  376. The library internally uses `DIGIT` as the type, which is u64 or u32 depending on the platform.
  377. You are of course welcome to export to []u8, []u32be, and so forth.
  378. After this you can use `mem.slice_data_cast` to interpret the buffer as bytes if you so choose.
  379. `nails` are the number of top bits the output "word" reserves.
  380. To mimic the internals of this library, this would be 4.
  381. To use the minimum amount of output bytes, set `nails` to 0 and pass a `[]u8`.
  382. IMPORTANT: `pack` serializes the magnitude of an Int, that is, the output is unsigned.
  383. Assumes `a` not to be `nil` and to have been initialized.
  384. */
  385. internal_int_pack :: proc(a: ^Int, buf: []$T, nails := 0, order := Order.LSB_First) -> (written: int, err: Error)
  386. where intrinsics.type_is_integer(T) && intrinsics.type_is_unsigned(T) && size_of(T) <= 16 {
  387. assert(nails >= 0 && nails < (size_of(T) * 8))
  388. type_size := size_of(T)
  389. type_bits := (type_size * 8) - nails
  390. word_count := internal_int_pack_count(a, T, nails)
  391. bit_count := internal_count_bits(a)
  392. if len(buf) < word_count {
  393. return 0, .Buffer_Overflow
  394. }
  395. bit_offset := 0
  396. word_offset := 0
  397. #no_bounds_check for i := 0; i < word_count; i += 1 {
  398. bit_offset = i * type_bits
  399. if order == .MSB_First {
  400. word_offset = word_count - i - 1
  401. } else {
  402. word_offset = i
  403. }
  404. bits_to_get := min(type_bits, bit_count - bit_offset)
  405. W := internal_int_bitfield_extract(a, bit_offset, bits_to_get) or_return
  406. buf[word_offset] = T(W)
  407. }
  408. return word_count, nil
  409. }
  410. internal_int_unpack :: proc(a: ^Int, buf: []$T, nails := 0, order := Order.LSB_First, allocator := context.allocator) -> (err: Error)
  411. where intrinsics.type_is_integer(T) && intrinsics.type_is_unsigned(T) && size_of(T) <= 16 {
  412. assert(nails >= 0 && nails < (size_of(T) * 8))
  413. context.allocator = allocator
  414. type_size := size_of(T)
  415. type_bits := (type_size * 8) - nails
  416. type_mask := T(1 << uint(type_bits)) - 1
  417. if len(buf) == 0 {
  418. return .Invalid_Argument
  419. }
  420. bit_count := type_bits * len(buf)
  421. digit_count := (bit_count / _DIGIT_BITS) + min(1, bit_count % _DIGIT_BITS)
  422. /*
  423. Pre-size output Int.
  424. */
  425. internal_grow(a, digit_count) or_return
  426. t := &Int{}
  427. defer internal_destroy(t)
  428. if order == .LSB_First {
  429. for W, i in buf {
  430. internal_set(t, W & type_mask) or_return
  431. internal_shl(t, t, type_bits * i) or_return
  432. internal_add(a, a, t) or_return
  433. }
  434. } else {
  435. for W in buf {
  436. internal_set(t, W & type_mask) or_return
  437. internal_shl(a, a, type_bits) or_return
  438. internal_add(a, a, t) or_return
  439. }
  440. }
  441. return internal_clamp(a)
  442. }
  443. /*
  444. Overestimate the size needed for the bigint to string conversion by a very small amount.
  445. The error is about 10^-8; it will overestimate the result by at most 11 elements for
  446. a number of the size 2^(2^31)-1 which is currently the largest possible in this library.
  447. Some short tests gave no results larger than 5 (plus 2 for sign and EOS).
  448. */
  449. /*
  450. Table of {0, INT(log_2([1..64])*2^p)+1 } where p is the scale
  451. factor defined in MP_RADIX_SIZE_SCALE and INT() extracts the integer part (truncating).
  452. Good for 32 bit "int". Set MP_RADIX_SIZE_SCALE = 61 and recompute values
  453. for 64 bit "int".
  454. */
  455. _RADIX_SIZE_SCALE :: 29
  456. _log_bases :: [65]u32{
  457. 0, 0, 0x20000001, 0x14309399, 0x10000001,
  458. 0xdc81a35, 0xc611924, 0xb660c9e, 0xaaaaaab, 0xa1849cd,
  459. 0x9a209a9, 0x94004e1, 0x8ed19c2, 0x8a5ca7d, 0x867a000,
  460. 0x830cee3, 0x8000001, 0x7d42d60, 0x7ac8b32, 0x7887847,
  461. 0x7677349, 0x749131f, 0x72d0163, 0x712f657, 0x6fab5db,
  462. 0x6e40d1b, 0x6ced0d0, 0x6badbde, 0x6a80e3b, 0x6964c19,
  463. 0x6857d31, 0x6758c38, 0x6666667, 0x657fb21, 0x64a3b9f,
  464. 0x63d1ab4, 0x6308c92, 0x624869e, 0x618ff47, 0x60dedea,
  465. 0x6034ab0, 0x5f90e7b, 0x5ef32cb, 0x5e5b1b2, 0x5dc85c3,
  466. 0x5d3aa02, 0x5cb19d9, 0x5c2d10f, 0x5bacbbf, 0x5b3064f,
  467. 0x5ab7d68, 0x5a42df0, 0x59d1506, 0x5962ffe, 0x58f7c57,
  468. 0x588f7bc, 0x582a000, 0x57c7319, 0x5766f1d, 0x5709243,
  469. 0x56adad9, 0x565474d, 0x55fd61f, 0x55a85e8, 0x5555556,
  470. }
  471. /*
  472. Characters used in radix conversions.
  473. */
  474. RADIX_TABLE := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
  475. RADIX_TABLE_REVERSE := [RADIX_TABLE_REVERSE_SIZE]u8{
  476. 0x3e, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x01, 0x02, 0x03, 0x04, /* +,-./01234 */
  477. 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, /* 56789:;<=> */
  478. 0xff, 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, /* ?@ABCDEFGH */
  479. 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, /* IJKLMNOPQR */
  480. 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0xff, 0xff, /* STUVWXYZ[\ */
  481. 0xff, 0xff, 0xff, 0xff, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, /* ]^_`abcdef */
  482. 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, /* ghijklmnop */
  483. 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, /* qrstuvwxyz */
  484. }
  485. RADIX_TABLE_REVERSE_SIZE :: 80
  486. /*
  487. Stores a bignum as a ASCII string in a given radix (2..64)
  488. The buffer must be appropriately sized. This routine doesn't check.
  489. */
  490. _itoa_raw_full :: proc(a: ^Int, radix: i8, buffer: []u8, zero_terminate := false, allocator := context.allocator) -> (written: int, err: Error) {
  491. assert_if_nil(a)
  492. context.allocator = allocator
  493. temp, denominator := &Int{}, &Int{}
  494. internal_copy(temp, a) or_return
  495. internal_set(denominator, radix) or_return
  496. available := len(buffer)
  497. if zero_terminate {
  498. available -= 1
  499. buffer[available] = 0
  500. }
  501. if a.sign == .Negative {
  502. temp.sign = .Zero_or_Positive
  503. }
  504. remainder: DIGIT
  505. for {
  506. if remainder, err = #force_inline internal_divmod(temp, temp, DIGIT(radix)); err != nil {
  507. internal_destroy(temp, denominator)
  508. return len(buffer) - available, err
  509. }
  510. available -= 1
  511. buffer[available] = RADIX_TABLE[remainder]
  512. if temp.used == 0 {
  513. break
  514. }
  515. }
  516. if a.sign == .Negative {
  517. available -= 1
  518. buffer[available] = '-'
  519. }
  520. internal_destroy(temp, denominator)
  521. /*
  522. If we overestimated the size, we need to move the buffer left.
  523. */
  524. written = len(buffer) - available
  525. if written < len(buffer) {
  526. diff := len(buffer) - written
  527. mem.copy(&buffer[0], &buffer[diff], written)
  528. }
  529. return written, nil
  530. }