#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif

// Red-black tree stored in index-addressed pools.
//
// Hot node record (16 bytes, in `hot`):  key: Int64 @0, child[0]: UInt32 @8,
// child[1]: UInt32 @12. Index 0 is the nil link. Values live in a parallel
// array `vals`, colours in a parallel bitmap `colors` (bit set = red), so a
// search touches only 16 bytes per node and colour checks of uncles/nephews
// hit a small (n/8 bytes) cache-resident bitmap. No parent links: insert and
// remove record the search path on an explicit stack (packed node<<1 | dir).

@inline(__always) private func rbKey(_ h: UnsafeMutableRawPointer, _ n: Int) -> Int64 {
    h.load(fromByteOffset: n &<< 4, as: Int64.self)
}
@inline(__always) private func rbSetKey(_ h: UnsafeMutableRawPointer, _ n: Int, _ k: Int64) {
    h.storeBytes(of: k, toByteOffset: n &<< 4, as: Int64.self)
}
@inline(__always) private func rbCh(_ h: UnsafeMutableRawPointer, _ n: Int, _ d: Int) -> Int {
    Int(h.load(fromByteOffset: (n &<< 4) &+ 8 &+ (d &<< 2), as: UInt32.self))
}
@inline(__always) private func rbSetCh(_ h: UnsafeMutableRawPointer, _ n: Int, _ d: Int, _ v: Int) {
    h.storeBytes(of: UInt32(truncatingIfNeeded: v), toByteOffset: (n &<< 4) &+ 8 &+ (d &<< 2), as: UInt32.self)
}
@inline(__always) private func rbIsRed(_ c: UnsafeMutablePointer<UInt64>, _ n: Int) -> Bool {
    (c[n &>> 6] &>> UInt64(truncatingIfNeeded: n & 63)) & 1 != 0
}
@inline(__always) private func rbSetRed(_ c: UnsafeMutablePointer<UInt64>, _ n: Int) {
    c[n &>> 6] |= (1 as UInt64) &<< UInt64(truncatingIfNeeded: n & 63)
}
@inline(__always) private func rbSetBlack(_ c: UnsafeMutablePointer<UInt64>, _ n: Int) {
    c[n &>> 6] &= ~((1 as UInt64) &<< UInt64(truncatingIfNeeded: n & 63))
}

final class RBTree {
    private var hot: UnsafeMutableRawPointer
    private var vals: UnsafeMutablePointer<Int64>
    private var colors: UnsafeMutablePointer<UInt64>
    private let stack: UnsafeMutablePointer<Int>
    private var cap: Int
    private var used: Int
    private var freeHead: Int
    private var root: Int
    private var cnt: Int

    init() {
        let c = 64
        cap = c
        hot = malloc(c * 16)!
        memset(hot, 0, 16)
        vals = malloc(c * 8)!.bindMemory(to: Int64.self, capacity: c)
        colors = calloc(c / 64, 8)!.bindMemory(to: UInt64.self, capacity: c / 64)
        stack = UnsafeMutablePointer<Int>.allocate(capacity: 256)
        used = 1
        freeHead = 0
        root = 0
        cnt = 0
    }

    deinit {
        free(hot)
        free(UnsafeMutableRawPointer(vals))
        free(UnsafeMutableRawPointer(colors))
        stack.deallocate()
    }

    var count: Int { cnt }

    @inline(never)
    private func grow() {
        let oc = cap
        let nc = oc * 2
        hot = realloc(hot, nc * 16)!
        vals = realloc(UnsafeMutableRawPointer(vals), nc * 8)!.bindMemory(to: Int64.self, capacity: nc)
        let cr = realloc(UnsafeMutableRawPointer(colors), (nc / 64) * 8)!
        memset(cr + (oc / 64) * 8, 0, ((nc - oc) / 64) * 8)
        colors = cr.bindMemory(to: UInt64.self, capacity: nc / 64)
        cap = nc
    }

    @inline(__always)
    private func newNode(_ key: Int64, _ value: Int64) -> Int {
        var z = freeHead
        if z != 0 {
            freeHead = rbCh(hot, z, 0)
        } else {
            if used == cap { grow() }
            z = used
            used = z &+ 1
        }
        let h = hot
        rbSetKey(h, z, key)
        h.storeBytes(of: 0 as UInt64, toByteOffset: (z &<< 4) &+ 8, as: UInt64.self)
        vals[z] = value
        rbSetRed(colors, z)
        return z
    }

    func get(_ key: Int64) -> Int64? {
        let h = hot
        var n = root
        while n != 0 {
            let k = rbKey(h, n)
            if k == key { return vals[n] }
            n = rbCh(h, n, key > k ? 1 : 0)
        }
        return nil
    }

    func insert(_ key: Int64, _ value: Int64) -> Bool {
        var n = root
        if n == 0 {
            let z = newNode(key, value)
            rbSetBlack(colors, z)
            root = z
            cnt = 1
            return true
        }
        var h = hot
        let st = stack
        var sp = 0
        var d = 0
        while true {
            let k = rbKey(h, n)
            if k == key {
                vals[n] = value
                return false
            }
            d = key > k ? 1 : 0
            st[sp] = (n &<< 1) | d
            sp &+= 1
            let c = rbCh(h, n, d)
            if c == 0 { break }
            n = c
        }
        let z = newNode(key, value)
        h = hot
        let col = colors
        rbSetCh(h, n, d, z)
        cnt &+= 1

        var x = z
        while sp >= 2 {
            let pe = st[sp &- 1]
            let p = pe &>> 1
            if !rbIsRed(col, p) { break }
            let ge = st[sp &- 2]
            let g = ge &>> 1
            let pd = ge & 1
            let u = rbCh(h, g, pd ^ 1)
            if rbIsRed(col, u) {
                rbSetBlack(col, p)
                rbSetBlack(col, u)
                rbSetRed(col, g)
                x = g
                sp &-= 2
                continue
            }
            var top = p
            let xd = pe & 1
            if xd != pd {
                rbSetCh(h, p, xd, rbCh(h, x, pd))
                rbSetCh(h, x, pd, p)
                top = x
            }
            rbSetCh(h, g, pd, rbCh(h, top, pd ^ 1))
            rbSetCh(h, top, pd ^ 1, g)
            if sp >= 3 {
                let gge = st[sp &- 3]
                rbSetCh(h, gge &>> 1, gge & 1, top)
            } else {
                root = top
            }
            rbSetBlack(col, top)
            rbSetRed(col, g)
            break
        }
        rbSetBlack(col, root)
        return true
    }

    func remove(_ key: Int64) -> Bool {
        let h = hot
        let st = stack
        let col = colors
        var n = root
        var sp = 0
        while n != 0 {
            let k = rbKey(h, n)
            if k == key { break }
            let d = key > k ? 1 : 0
            st[sp] = (n &<< 1) | d
            sp &+= 1
            n = rbCh(h, n, d)
        }
        if n == 0 { return false }

        var t = n
        let l = rbCh(h, n, 0)
        let r = rbCh(h, n, 1)
        let c: Int
        if l != 0 && r != 0 {
            st[sp] = (n &<< 1) | 1
            sp &+= 1
            var s = r
            while true {
                let sl = rbCh(h, s, 0)
                if sl == 0 { break }
                st[sp] = s &<< 1
                sp &+= 1
                s = sl
            }
            rbSetKey(h, n, rbKey(h, s))
            vals[n] = vals[s]
            t = s
            c = rbCh(h, s, 1)
        } else {
            c = l | r
        }
        if sp == 0 {
            root = c
        } else {
            let e = st[sp &- 1]
            rbSetCh(h, e &>> 1, e & 1, c)
        }
        let tBlack = !rbIsRed(col, t)
        rbSetCh(h, t, 0, freeHead)
        freeHead = t
        cnt &-= 1
        if !tBlack { return true }
        if c != 0 {
            rbSetBlack(col, c)
            return true
        }

        // Fix a double-black at the (nil) child slot recorded at st[sp-1].
        while sp > 0 {
            let e = st[sp &- 1]
            let p = e &>> 1
            let d = e & 1
            var s = rbCh(h, p, d ^ 1)
            if rbIsRed(col, s) {
                rbSetCh(h, p, d ^ 1, rbCh(h, s, d))
                rbSetCh(h, s, d, p)
                rbSetBlack(col, s)
                rbSetRed(col, p)
                if sp >= 2 {
                    let ge = st[sp &- 2]
                    rbSetCh(h, ge &>> 1, ge & 1, s)
                } else {
                    root = s
                }
                st[sp &- 1] = (s &<< 1) | d
                st[sp] = e
                sp &+= 1
                s = rbCh(h, p, d ^ 1)
            }
            var far = rbCh(h, s, d ^ 1)
            if !rbIsRed(col, far) {
                let near = rbCh(h, s, d)
                if !rbIsRed(col, near) {
                    rbSetRed(col, s)
                    if rbIsRed(col, p) {
                        rbSetBlack(col, p)
                        return true
                    }
                    sp &-= 1
                    continue
                }
                // Near nephew red, far black: rotate at s so it becomes far.
                rbSetCh(h, s, d, rbCh(h, near, d ^ 1))
                rbSetCh(h, near, d ^ 1, s)
                far = s
                s = near
            }
            if rbIsRed(col, p) { rbSetRed(col, s) } else { rbSetBlack(col, s) }
            rbSetBlack(col, p)
            rbSetBlack(col, far)
            rbSetCh(h, p, d ^ 1, rbCh(h, s, d))
            rbSetCh(h, s, d, p)
            if sp >= 2 {
                let ge = st[sp &- 2]
                rbSetCh(h, ge &>> 1, ge & 1, s)
            } else {
                root = s
            }
            return true
        }
        return true
    }

    func range(_ lo: Int64, _ hi: Int64,
               _ outKeys: UnsafeMutablePointer<Int64>,
               _ outVals: UnsafeMutablePointer<Int64>,
               _ limit: Int) -> Int {
        if lo > hi || limit <= 0 { return 0 }
        let h = hot
        let v = vals
        let st = stack
        var sp = 0
        var n = root
        while n != 0 {
            if rbKey(h, n) < lo {
                n = rbCh(h, n, 1)
            } else {
                st[sp] = n
                sp &+= 1
                n = rbCh(h, n, 0)
            }
        }
        var out = 0
        while sp > 0 {
            sp &-= 1
            let x = st[sp]
            let k = rbKey(h, x)
            if k > hi { break }
            outKeys[out] = k
            outVals[out] = v[x]
            out &+= 1
            if out == limit { break }
            var c = rbCh(h, x, 1)
            while c != 0 {
                st[sp] = c
                sp &+= 1
                c = rbCh(h, c, 0)
            }
        }
        return out
    }

    func height() -> Int {
        return heightOf(root)
    }

    private func heightOf(_ n: Int) -> Int {
        if n == 0 { return 0 }
        return 1 + max(heightOf(rbCh(hot, n, 0)), heightOf(rbCh(hot, n, 1)))
    }
}
