// Classic randomized skip list (Pugh 1990), p = 1/2, maximum height 32.
//
// Node layout (raw memory, 8-byte words):
//   [0] key   [1] value   [2 ..< 2+h] forward links for levels 0 ..< h
// Nodes are carved from per-height slabs (one pool per tower height), so a
// node's size is exactly 16 + 8*h bytes and tall nodes are packed densely
// together. Removed nodes go onto a per-height free list and are reused.
//
// A header node (32 links) starts every level; every level ends at a shared
// tail sentinel, so links are never nil. All mutable state lives in raw
// memory reached through `let` pointers (no exclusivity checks, no ARC).

typealias SLPtr = UnsafeMutableRawPointer

@inline(__always) private func slKey(_ n: SLPtr) -> Int64 {
    n.load(as: Int64.self)
}
@inline(__always) private func slVal(_ n: SLPtr) -> Int64 {
    n.load(fromByteOffset: 8, as: Int64.self)
}
@inline(__always) private func slSetVal(_ n: SLPtr, _ v: Int64) {
    n.storeBytes(of: v, toByteOffset: 8, as: Int64.self)
}
@inline(__always) private func slLink(_ n: SLPtr, _ l: Int) -> SLPtr {
    n.load(fromByteOffset: 16 &+ (l &<< 3), as: SLPtr.self)
}
@inline(__always) private func slSetLink(_ n: SLPtr, _ l: Int, _ v: SLPtr) {
    n.storeBytes(of: v, toByteOffset: 16 &+ (l &<< 3), as: SLPtr.self)
}

struct SLState {
    var count: Int = 0
    var level: Int = 0          // height of the tallest node (0 when empty)
    var rng: UInt64 = 0x2545F4914F6CDD1D
    var chunks: SLPtr? = nil    // singly linked list of slab chunks
}

final class SkipList {
    static let maxHeight = 32           // (1/p)^32 = 2^32
    private static let chunkMaxBytes = 1 << 20

    private let st: UnsafeMutablePointer<SLState>
    private let header: SLPtr
    private let tail: SLPtr
    private let preds: UnsafeMutablePointer<SLPtr>       // update vector
    private let freeHead: UnsafeMutablePointer<SLPtr?>   // per height
    private let bumpCur: UnsafeMutablePointer<UInt>      // per height
    private let bumpEnd: UnsafeMutablePointer<UInt>      // per height
    private let nextChunkNodes: UnsafeMutablePointer<Int> // per height

    init() {
        let mh = SkipList.maxHeight
        st = UnsafeMutablePointer<SLState>.allocate(capacity: 1)
        st.initialize(to: SLState())
        header = SLPtr.allocate(byteCount: 16 + 8 * mh, alignment: 64)
        tail = SLPtr.allocate(byteCount: 24, alignment: 64)
        tail.storeBytes(of: Int64.max, as: Int64.self)
        tail.storeBytes(of: 0, toByteOffset: 8, as: Int64.self)
        tail.storeBytes(of: tail, toByteOffset: 16, as: SLPtr.self)
        header.storeBytes(of: Int64.min, as: Int64.self)
        header.storeBytes(of: 0, toByteOffset: 8, as: Int64.self)
        for l in 0..<mh { slSetLink(header, l, tail) }
        preds = UnsafeMutablePointer<SLPtr>.allocate(capacity: mh)
        preds.initialize(repeating: header, count: mh)
        freeHead = UnsafeMutablePointer<SLPtr?>.allocate(capacity: mh + 1)
        freeHead.initialize(repeating: nil, count: mh + 1)
        bumpCur = UnsafeMutablePointer<UInt>.allocate(capacity: mh + 1)
        bumpCur.initialize(repeating: 0, count: mh + 1)
        bumpEnd = UnsafeMutablePointer<UInt>.allocate(capacity: mh + 1)
        bumpEnd.initialize(repeating: 0, count: mh + 1)
        nextChunkNodes = UnsafeMutablePointer<Int>.allocate(capacity: mh + 1)
        nextChunkNodes.initialize(repeating: 32, count: mh + 1)
    }

    deinit {
        var c = st.pointee.chunks
        while let p = c {
            c = p.load(as: SLPtr?.self)
            p.deallocate()
        }
        st.deinitialize(count: 1)
        st.deallocate()
        header.deallocate()
        tail.deallocate()
        preds.deallocate()
        freeHead.deallocate()
        bumpCur.deallocate()
        bumpEnd.deallocate()
        nextChunkNodes.deallocate()
    }

    // ------------------------------------------------------------ memory

    @inline(never)
    private func refill(_ h: Int) {
        let size = 16 + 8 * h
        let nodes = nextChunkNodes[h]
        let bytes = 64 + nodes * size
        let chunk = SLPtr.allocate(byteCount: bytes, alignment: 128)
        chunk.storeBytes(of: st.pointee.chunks, as: SLPtr?.self)
        st.pointee.chunks = chunk
        let start = UInt(bitPattern: chunk) &+ 64
        bumpCur[h] = start
        bumpEnd[h] = start &+ UInt(nodes * size)
        if (nodes * 2) * size <= SkipList.chunkMaxBytes {
            nextChunkNodes[h] = nodes * 2
        }
    }

    @inline(__always)
    private func allocNode(_ h: Int) -> SLPtr {
        if let f = freeHead[h] {
            freeHead[h] = f.load(fromByteOffset: 16, as: SLPtr?.self)
            return f
        }
        let size = UInt(16 &+ (h &<< 3))
        var c = bumpCur[h]
        if c &+ size > bumpEnd[h] {
            refill(h)
            c = bumpCur[h]
        }
        bumpCur[h] = c &+ size
        return SLPtr(bitPattern: c).unsafelyUnwrapped
    }

    @inline(__always)
    private func freeNode(_ n: SLPtr, _ h: Int) {
        n.storeBytes(of: freeHead[h], toByteOffset: 16, as: SLPtr?.self)
        freeHead[h] = n
    }

    // splitmix64; height = 1 + number of trailing zero bits (p = 1/2), capped.
    @inline(__always)
    private func randomHeight() -> Int {
        let s = st.pointee.rng &+ 0x9E3779B97F4A7C15
        st.pointee.rng = s
        var z = s
        z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
        z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
        z ^= z >> 31
        let h = 1 &+ z.trailingZeroBitCount
        return h > SkipList.maxHeight ? SkipList.maxHeight : h
    }

    // ------------------------------------------------------------ operations

    var count: Int { st.pointee.count }

    func get(_ key: Int64) -> Int64? {
        var cur = header
        var last = tail      // known node with key >= search key (or tail)
        var l = st.pointee.level &- 1
        while l >= 0 {
            var next = slLink(cur, l)
            while next != last {
                let k = slKey(next)
                if k < key {
                    cur = next
                    next = slLink(cur, l)
                    continue
                }
                if k == key { return slVal(next) }
                last = next
                break
            }
            l &-= 1
        }
        return nil
    }

    func insert(_ key: Int64, _ value: Int64) -> Bool {
        let preds = self.preds
        var cur = header
        var last = tail
        let level = st.pointee.level
        var l = level &- 1
        while l >= 0 {
            var next = slLink(cur, l)
            while next != last {
                let k = slKey(next)
                if k < key {
                    cur = next
                    next = slLink(cur, l)
                    continue
                }
                if k == key {
                    slSetVal(next, value)
                    return false
                }
                last = next
                break
            }
            preds[l] = cur
            l &-= 1
        }

        let h = randomHeight()
        if h > level {
            var i = level
            while i < h { preds[i] = header; i &+= 1 }
            st.pointee.level = h
        }
        let node = allocNode(h)
        node.storeBytes(of: key, as: Int64.self)
        node.storeBytes(of: value, toByteOffset: 8, as: Int64.self)
        var i = 0
        while i < h {
            let p = preds[i]
            slSetLink(node, i, slLink(p, i))
            slSetLink(p, i, node)
            i &+= 1
        }
        st.pointee.count &+= 1
        return true
    }

    func remove(_ key: Int64) -> Bool {
        var cur = header
        var last = tail
        var l = st.pointee.level &- 1
        while l >= 0 {
            var next = slLink(cur, l)
            while next != last {
                let k = slKey(next)
                if k < key {
                    cur = next
                    next = slLink(cur, l)
                    continue
                }
                if k == key {
                    // First seen at its top level l: height is l + 1.
                    let target = next
                    slSetLink(cur, l, slLink(target, l))
                    var j = l &- 1
                    while j >= 0 {
                        var n2 = slLink(cur, j)
                        while n2 != target {
                            cur = n2
                            n2 = slLink(cur, j)
                        }
                        slSetLink(cur, j, slLink(target, j))
                        j &-= 1
                    }
                    freeNode(target, l &+ 1)
                    st.pointee.count &-= 1
                    var lv = st.pointee.level
                    let tl = tail
                    while lv > 0 && slLink(header, lv &- 1) == tl { lv &-= 1 }
                    st.pointee.level = lv
                    return true
                }
                last = next
                break
            }
            l &-= 1
        }
        return false
    }

    func range(_ lo: Int64, _ hi: Int64,
               _ outKeys: UnsafeMutablePointer<Int64>,
               _ outVals: UnsafeMutablePointer<Int64>,
               _ limit: Int) -> Int {
        if limit <= 0 || lo > hi { return 0 }
        var cur = header
        var last = tail
        var node: SLPtr? = nil
        var l = st.pointee.level &- 1
        outer: while l >= 0 {
            var next = slLink(cur, l)
            while next != last {
                let k = slKey(next)
                if k < lo {
                    cur = next
                    next = slLink(cur, l)
                    continue
                }
                if k == lo { node = next; break outer }
                last = next
                break
            }
            l &-= 1
        }
        var n = node ?? slLink(cur, 0)
        let tl = tail
        var i = 0
        while n != tl {
            let k = slKey(n)
            if k > hi { break }
            outKeys[i] = k
            outVals[i] = slVal(n)
            i &+= 1
            if i == limit { break }
            n = slLink(n, 0)
        }
        return i
    }

    func height() -> Int { st.pointee.level }

    func levelCount(_ level: Int) -> Int {
        if level < 0 || level >= SkipList.maxHeight { return 0 }
        var c = 0
        var n = slLink(header, level)
        let tl = tail
        while n != tl {
            c &+= 1
            n = slLink(n, level)
        }
        return c
    }
}
