News for hackers. Stuff that matters.
Re:size_t-to-int vulnerability in Linux’s filesystem layer by frogblast on Tuesday July 20, 2021 @01:49PM (#27896875)
In swift:

    //  a is a UInt64
    let a = Int.random(in: 0..<Int.max)
    
    //  causes a fatal runtime error if out of range, halts execution
    let b = UInt32(a)
    
    //  returns a UInt32?, which will be nil if out of range
    let c =  UInt32(exactly: a)
    
    //  another approach for exact conversion:
    guard let d = UInt32(exactly: a) else {
        //  conversion failed
        //  handle error and return
        return
    }
    // 'd' is a UInt32 without any bits lost
    
    //  always succeeds, will return a UInt32, either clamped or truncated.   Truncation just cuts off the high bits.
    let e = UInt32(clamping: a)
    let f = UInt32(truncatingIfNeeded: a)

There are no comments on this comment yet.