From b6a7d8d63a23aedbe9baa06a2a833217db94b01a Mon Sep 17 00:00:00 2001 From: Jose Carlos Venegas Munoz Date: Tue, 24 Mar 2020 23:27:47 +0000 Subject: [PATCH] utils: Add memory unit abstraction Add MemUnit to help to manage memory, this will handle memory units internally and provide proper methods to convert to different units. Signed-off-by: Jose Carlos Venegas Munoz --- virtcontainers/utils/utils.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/virtcontainers/utils/utils.go b/virtcontainers/utils/utils.go index 6be68f4286..85c554896a 100644 --- a/virtcontainers/utils/utils.go +++ b/virtcontainers/utils/utils.go @@ -240,3 +240,38 @@ func SupportsVsocks() bool { var StartCmd = func(c *exec.Cmd) error { return c.Start() } + +// AlignMem align memory provided to a block size +func (m MemUnit) AlignMem(blockSize MemUnit) MemUnit { + memSize := m + if m < blockSize { + memSize = blockSize + + } + + remainder := memSize % blockSize + + if remainder != 0 { + // Align memory to memoryBlockSizeMB + memSize += blockSize - remainder + + } + return memSize +} + +type MemUnit uint64 + +func (m MemUnit) ToMiB() uint64 { + return m.ToBytes() / (1 * MiB).ToBytes() +} + +func (m MemUnit) ToBytes() uint64 { + return uint64(m) +} + +const ( + Byte MemUnit = 1 + KiB = Byte << 10 + MiB = KiB << 10 + GiB = MiB << 10 +)