示例工程 02-values-variables-types

02-values-variables-types/Sources/Ch02Kit/IntegerOverflow.swift

swift · 1.7 KB

import Foundation
 
/// 整数溢出:`+` 会 trap,`&+` 回绕,`addingReportingOverflow` 返回标志位。
public enum IntegerOverflow {
    /// 回绕加法,等价于 Go 的默认行为、C 的无符号行为(C 有符号是未定义)。
    public static func wrappingAdd(_ lhs: Int, _ rhs: Int) -> Int {
        lhs &+ rhs
    }
 
    /// 溢出时返回 nil,对应 C 里手动检查、Java 的 `Math.addExact` 抛异常。
    public static func checkedAdd(_ lhs: Int, _ rhs: Int) -> Int? {
        let result = lhs.addingReportingOverflow(rhs)
        return result.overflow ? nil : result.partialValue
    }
 
    /// 把整数收窄到 Int32;放不下时返回 nil,而不是 trap。
    public static func narrowToInt32(_ value: Int) -> Int32? {
        Int32(exactly: value)
    }
}
 
/// `Int` 的宽度随平台变化,`Int32` 固定 4 字节;内存布局可直接测量。
public enum IntegerWidth {
    public static let intBytes = MemoryLayout<Int>.size
    public static let int32Bytes = MemoryLayout<Int32>.size
    public static let doubleBytes = MemoryLayout<Double>.size
    public static let decimalBytes = MemoryLayout<Decimal>.size
}
 
/// 混合字段的结构体:`Bool` 与 `Int` 之间会插入填充,`size` 因此大于字段之和。
public struct MixedLayout: Sendable {
    public let flag: Bool
    public let count: Int
 
    public init(flag: Bool = true, count: Int = 0) {
        self.flag = flag
        self.count = count
    }
}
 
public enum LayoutSamples {
    public static let mixedSize = MemoryLayout<MixedLayout>.size
    public static let mixedStride = MemoryLayout<MixedLayout>.stride
    public static let mixedAlignment = MemoryLayout<MixedLayout>.alignment
}