cue-lang / cue

The home of the CUE language! Validate and define text-based and dynamic configuration
https://cuelang.org
Apache License 2.0
4.94k stars 279 forks source link

ip arithmetic #3142

Open lgfausak opened 2 months ago

lgfausak commented 2 months ago

i create a lot of json to do configuration. typically my configurations contain ip addresses. i am new to cue, i've spent the day doing experiments and reading through all of the docs / tutorials / etc. If I wanted to use cue to create an ip address based upon a cidr + offset is that possible? something like "192.168.0.0/24" + 3 == 192.168.0.3

NoamTD commented 2 months ago

it's a bit convoluted, but would something like this work for you?

import "net"

#IncIP: {
    In!: net.IPv4
    Offset!: int

    _incremented: In[:3] + [In[len(In)-1]+Offset]

    Out: net.IPString(_incremented)
}

sourceIp: net.ToIP4("192.168.0.0")
withOffset: (#IncIP & {Offset: 1, In: sourceIp}).Out

output:

sourceIp: [192, 168, 0, 0]
withOffset: "192.168.0.1"
slewiskelly commented 2 months ago

it's a bit convoluted, but would something like this work for you?

This will fail if exceeding an octet (255).

I'm not certain that this is totally correct, but:

import (
    "math"
    "net"
    "strconv"
)

ip: (#IPAdd & {ip: "192.168.0.0", i: 256}).out

#IPAdd: {
    ip: string
    i:  uint

    out: "\(math.Floor(_out/16777216)).\(math.Floor(_out/65536) mod 256).\(math.Floor(_out/256) mod 256).\(_out mod 256)"

    _ip:  net.ToIP4(ip)
    _out: (_ip[0]*16777216 + _ip[1]*65536 + _ip[2]*256 + _ip[3]) + i
}

This is easier to implement in Go, but I'm not sure if something like this would be added to the standard library, though.