Canonicalize CIDR: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: changed a comment, updated example nodes.)
(→‎{{header|Wren}}: Changed to cope with the extra examples.)
Line 522: Line 522:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
{{libheader|Wren-str}}
<lang ecmascript>import "os" for Process
<lang ecmascript>import "/fmt" for Fmt, Conv
import "/fmt" for Fmt, Conv
import "/str" for Str
import "/str" for Str


// canonicalize a CIDR block: make sure none of the host bits are set
// canonicalize a CIDR block: make sure none of the host bits are set
var args = Process.arguments
var canonicalize = Fn.new { |cidr|
// dotted-decimal / bits in network part
var cidr = (args.count > 0) ? args[0] : Fiber.abort("Please pass the CIDR to be canonicalized.")
var split = cidr.split("/")
var dotted = split[0]
var size = Num.fromString(split[1])


// get IP as binary string
// dotted-decimal / bits in network part
var binary = dotted.split(".").map { |n| Fmt.swrite("$08b", Num.fromString(n)) }.join()
var split = cidr.split("/")
var dotted = split[0]
var size = Num.fromString(split[1])


// replace the host part with all zeros
// get IP as binary string
var binary = dotted.split(".").map { |n| Fmt.swrite("$08b", Num.fromString(n)) }.join()
binary = binary[0...size] + "0" * (32 - size)


// convert back to dotted-decimal
// replace the host part with all zeros
var chunks = Str.chunks(binary, 8)
binary = binary[0...size] + "0" * (32 - size)
var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")


// and return
// convert back to dotted-decimal
return canon + "/" + split[1]
var chunks = Str.chunks(binary, 8)
}
var canon = chunks.map { |c| Conv.atoi(c, 2) }.join(".")


var tests = [
// and output
"87.70.141.1/22",
System.print(canon + "/" + split[1])</lang>
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24" ,
"184.232.176.184/18"
]

for (test in tests) {
Fmt.print("$-18s -> $s", test, canonicalize.call(test))
}</lang>


{{out}}
{{out}}
<pre>
<pre>
$ wren canonicalize_cidr.wren 87.70.141.1/22
87.70.141.1/22 -> 87.70.140.0/22
36.18.154.103/12 -> 36.16.0.0/12
87.70.140.0/22
62.62.197.11/29 -> 62.62.197.8/29
67.137.119.181/4 -> 64.0.0.0/4
161.214.74.21/24 -> 161.214.74.0/24
184.232.176.184/18 -> 184.232.128.0/18
</pre>
</pre>