Canonicalize CIDR: Difference between revisions

→‎{{header|TXR}}: Take advantage of that inaddr-str already canonicalizes the numeric address.
(→‎{{header|TXR}}: New section.)
(→‎{{header|TXR}}: Take advantage of that inaddr-str already canonicalizes the numeric address.)
Line 1,747:
184.232.128.0/18</pre>
=={{header|TXR}}==
 
The following is a wasteful method which fails to take into account that <code>inaddr-str</code> is already stripping the bits:
 
<syntaxhighlight lang="txrlisp">(defun cidr-canon (str)
(match `@dots/@bits` str
Line 1,752 ⟶ 1,755:
(bits (int-str bits)))
`@(str-inaddr (logand inaddr (ash -1 (- 32 bits))))/@bits`)))</syntaxhighlight>
 
The following is a shorter method:
 
<syntaxhighlight lang="txrlisp">(defun cidr-canon (str)
(let ((a (inaddr-str str)))
`@(str-inaddr a.addr)/@{a.prefix}`))</syntaxhighlight>
 
A prefix notation can be condensed by removing unnecessary zeros. That is to say, <code>10.1.2.3/16</code> can be not just canonicalized to strip the irrelevant bits, but then shortened to <code>10.1/16</code>
 
The built-in function <code>inaddr-str-net</code> will produce this condensed prefix notation:
 
<syntaxhighlight lang="txrlisp">(defun cidr-canon (str)
(let ((a (inaddr-str str)))
(str-inaddr-net a.addr a.prefix)))</syntaxhighlight>
 
This can be written using the <code>flow</code> macro:
 
<syntaxhighlight lang="txrlisp">(defun cidr-canon (str)
(flow str
inaddr-str
(str-inaddr-net @1.addr @1.prefix)))</syntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
543

edits