Skip to content

Commit cb9f3d6

Browse files
committed
libct/cg: improve ConvertMemorySwapToCgroupV2Value
Improve readability of ConvertMemorySwapToCgroupV2Value by switching from a bunch of if statements to a switch, and adding a comment describing each case. No functional change. Signed-off-by: Kir Kolyshkin <[email protected]>
1 parent d123e56 commit cb9f3d6

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

libcontainer/cgroups/utils.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -415,26 +415,26 @@ func ConvertCPUSharesToCgroupV2Value(cpuShares uint64) uint64 {
415415

416416
// ConvertMemorySwapToCgroupV2Value converts MemorySwap value from OCI spec
417417
// for use by cgroup v2 drivers. A conversion is needed since Resources.MemorySwap
418-
// is defined as memory+swap combined, while in cgroup v2 swap is a separate value.
418+
// is defined as memory+swap combined, while in cgroup v2 swap is a separate value,
419+
// so we need to subtract memory from it where it makes sense.
419420
func ConvertMemorySwapToCgroupV2Value(memorySwap, memory int64) (int64, error) {
420-
// for compatibility with cgroup1 controller, set swap to unlimited in
421-
// case the memory is set to unlimited, and swap is not explicitly set,
422-
// treating the request as "set both memory and swap to unlimited".
423-
if memory == -1 && memorySwap == 0 {
421+
switch {
422+
case memory == -1 && memorySwap == 0:
423+
// For compatibility with cgroup1 controller, set swap to unlimited in
424+
// case the memory is set to unlimited and the swap is not explicitly set,
425+
// treating the request as "set both memory and swap to unlimited".
424426
return -1, nil
425-
}
426-
if memorySwap == -1 || memorySwap == 0 {
427-
// -1 is "max", 0 is "unset", so treat as is
427+
case memorySwap == -1, memorySwap == 0:
428+
// Treat -1 ("max") and 0 ("unset") swap as is.
428429
return memorySwap, nil
429-
}
430-
// sanity checks
431-
if memory == 0 || memory == -1 {
430+
case memory == 0, memory == -1:
431+
// Unset or unlimited memory, can't calculate swap.
432432
return 0, errors.New("unable to set swap limit without memory limit")
433-
}
434-
if memory < 0 {
433+
case memory < 0:
434+
// Does not make sense to subtract a negative value.
435435
return 0, fmt.Errorf("invalid memory value: %d", memory)
436-
}
437-
if memorySwap < memory {
436+
case memorySwap < memory:
437+
// Sanity check.
438438
return 0, errors.New("memory+swap limit should be >= memory limit")
439439
}
440440

0 commit comments

Comments
 (0)