github.com/racerxdl/gonx@v0.0.0-20210103083128-c5afc43bcbd2/nx/memory/allocpages.go (about)

     1  package memory
     2  
     3  import "unsafe"
     4  
     5  const pageSize = 0x1000
     6  
     7  // AllocPages will alocate a page-aligned region of memory that is at least min bytes long and no more than max bytes long
     8  // Returns null if can't allocate a page aligned byte slice
     9  // By default Nintendo Switch page size is 4KB
    10  func AllocPages(min, max int) (page []byte) {
    11  	pageSizeMinus1 := uintptr(pageSize - 1)
    12  	slice := make([]byte, max+int(pageSizeMinus1))
    13  	ptr := uintptr(unsafe.Pointer(&slice[0]))
    14  	slice = slice[pageSizeMinus1-(ptr+pageSizeMinus1)%pageSize:]
    15  	if len(slice) > max {
    16  		slice = slice[:max]
    17  	}
    18  
    19  	if len(slice) < min {
    20  		return nil
    21  	}
    22  
    23  	return slice
    24  }