Skip to content

Commit 1199b50

Browse files
authored
feat(ascii): conversion function for string to RFC1123 (#33)
1 parent 63d430b commit 1199b50

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

ascii.libsonnet

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,37 @@ local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet';
9696
fraction(expectFraction),
9797
exponent(expectExponent),
9898
]),
99+
100+
'#stringToRFC1123': d.fn(
101+
|||
102+
`stringToRFC113` converts a strings to match RFC1123, replacing non-alphanumeric characters with dashes. It'll throw an assertion if the string is too long.
103+
104+
* RFC 1123. This means the string must:
105+
* - contain at most 63 characters
106+
* - contain only lowercase alphanumeric characters or '-'
107+
* - start with an alphanumeric character
108+
* - end with an alphanumeric character
109+
|||,
110+
[d.arg('str', d.T.string)]
111+
),
112+
stringToRFC1123(str):
113+
// lowercase alphabetic characters
114+
local lowercase = std.asciiLower(str);
115+
// replace non-alphanumeric characters with dashes
116+
local alphanumeric =
117+
std.join(
118+
'',
119+
std.map(
120+
function(c)
121+
if self.isLower(c)
122+
|| self.isNumber(c)
123+
then c
124+
else '-',
125+
std.stringChars(lowercase)
126+
)
127+
);
128+
// remove leading/trailing dashes
129+
local return = std.stripChars(alphanumeric, '-');
130+
assert std.length(return) <= 63 : 'String too long';
131+
return,
99132
}

docs/ascii.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ local ascii = import "github.com/jsonnet-libs/xtd/ascii.libsonnet"
1717
* [`fn isStringJSONNumeric(str)`](#fn-isstringjsonnumeric)
1818
* [`fn isStringNumeric(str)`](#fn-isstringnumeric)
1919
* [`fn isUpper(c)`](#fn-isupper)
20+
* [`fn stringToRFC1123(str)`](#fn-stringtorfc1123)
2021

2122
## Fields
2223

@@ -58,4 +59,18 @@ isStringNumeric(str)
5859
isUpper(c)
5960
```
6061

61-
`isUpper` reports whether ASCII character `c` is a upper case letter
62+
`isUpper` reports whether ASCII character `c` is a upper case letter
63+
64+
### fn stringToRFC1123
65+
66+
```ts
67+
stringToRFC1123(str)
68+
```
69+
70+
`stringToRFC113` converts a strings to match RFC1123, replacing non-alphanumeric characters with dashes. It'll throw an assertion if the string is too long.
71+
72+
* RFC 1123. This means the string must:
73+
* - contain at most 63 characters
74+
* - contain only lowercase alphanumeric characters or '-'
75+
* - start with an alphanumeric character
76+
* - end with an alphanumeric character

0 commit comments

Comments
 (0)