概述

off是tiny Allocator的偏移指针,根据将要分配的内存大小,需调整off。如果size是8的倍数,则调用round(off,8)函数将off向上舍入到8的倍数。否则,如果size4的倍数,则调用round(off,4)函数将off向上舍入到4的倍数。最后,如果size2的倍数,则调用round(off,2)函数将off舍入到2的倍数。

    off := c.tinyoffset
	// Align tiny pointer for required (conservative) alignment.
	if size&7 == 0 {
		off = round(off, 8)
	} else if size&3 == 0 {
		off = round(off, 4)
	} else if size&1 == 0 {
		off = round(off, 2)
	} 

验证如下,需要调整的都会打印出来

===>原始: off:1, size:2  | 调整后: off:2, size:2 <===2倍数
// https://go.dev/play/p/1fl_cnJNwD-

package main

import (
	"fmt"
)

func main() {
	for i := 0; i < 16; i++ {
		for j := 1; j < 16; j++ {
			tmpOff, tmpSize := Size(i, j)
			if i != tmpOff {
				fmt.Printf("===>原始: off:%d, size:%d ", i, j)
				fmt.Printf(" | 调整后: off:%d, size:%d <===", tmpOff, tmpSize)
				var n = -1
				if j%8 == 0 {
					n = 8
				} else if j%4 == 0 {
					n = 4
				} else if j%2 == 0 {
					n = 2
				}
				if n != -1 {
					fmt.Printf("%d倍数\n", n)
				} else {
					fmt.Printf(" \n")
				}
			}
		}
	}
}

func Size(off int, size int) (int, int) {
	if size&7 == 0 {
		off = int(round(off, 8))
	} else if size&3 == 0 {
		off = int(round(off, 4))
	} else if size&1 == 0 {
		off = int(round(off, 2))
	}
	return off, size
}

func round(n, a int) int {
	return (n + a - 1) &^ (a - 1)
}