github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/align/align.go (about)

     1  // Copyright 2015-2022 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package align provides helpers for doing uint alignment.
     6  //
     7  // alignment is done via bit operation at the moment, so alignment
     8  // size need be a power of 2.
     9  package align
    10  
    11  import "os"
    12  
    13  var pageSize = uint(os.Getpagesize())
    14  
    15  // Up aligns v up to next multiple of alignSize.
    16  //
    17  // alignSize need be a power of 2.
    18  func Up(v uint, alignSize uint) uint {
    19  	mask := alignSize - 1
    20  	return (v + mask) &^ mask
    21  }
    22  
    23  // Down aligns v down to a previous multiple of alignSize.
    24  //
    25  // alignSize need be a power of 2.
    26  func Down(v uint, alignSize uint) uint {
    27  	return Up(v-(alignSize-1), alignSize)
    28  }
    29  
    30  // UpPage aligns v up by system page size.
    31  func UpPage(v uint) uint {
    32  	return Up(v, pageSize)
    33  }
    34  
    35  // DownPage aligns v down by system page size.
    36  func DownPage(v uint) uint {
    37  	return Down(v, pageSize)
    38  }