diff --git a/ascii.libsonnet b/ascii.libsonnet index f431376..05c2f38 100644 --- a/ascii.libsonnet +++ b/ascii.libsonnet @@ -96,4 +96,37 @@ local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet'; fraction(expectFraction), exponent(expectExponent), ]), + + '#stringToRFC1123': d.fn( + ||| + `stringToRFC113` converts a strings to match RFC1123, replacing non-alphanumeric characters with dashes. It'll throw an assertion if the string is too long. + + * RFC 1123. This means the string must: + * - contain at most 63 characters + * - contain only lowercase alphanumeric characters or '-' + * - start with an alphanumeric character + * - end with an alphanumeric character + |||, + [d.arg('str', d.T.string)] + ), + stringToRFC1123(str): + // lowercase alphabetic characters + local lowercase = std.asciiLower(str); + // replace non-alphanumeric characters with dashes + local alphanumeric = + std.join( + '', + std.map( + function(c) + if self.isLower(c) + || self.isNumber(c) + then c + else '-', + std.stringChars(lowercase) + ) + ); + // remove leading/trailing dashes + local return = std.stripChars(alphanumeric, '-'); + assert std.length(return) <= 63 : 'String too long'; + return, } diff --git a/docs/ascii.md b/docs/ascii.md index bee1eb3..95382d5 100644 --- a/docs/ascii.md +++ b/docs/ascii.md @@ -17,6 +17,7 @@ local ascii = import "github.com/jsonnet-libs/xtd/ascii.libsonnet" * [`fn isStringJSONNumeric(str)`](#fn-isstringjsonnumeric) * [`fn isStringNumeric(str)`](#fn-isstringnumeric) * [`fn isUpper(c)`](#fn-isupper) +* [`fn stringToRFC1123(str)`](#fn-stringtorfc1123) ## Fields @@ -58,4 +59,18 @@ isStringNumeric(str) isUpper(c) ``` -`isUpper` reports whether ASCII character `c` is a upper case letter \ No newline at end of file +`isUpper` reports whether ASCII character `c` is a upper case letter + +### fn stringToRFC1123 + +```ts +stringToRFC1123(str) +``` + +`stringToRFC113` converts a strings to match RFC1123, replacing non-alphanumeric characters with dashes. It'll throw an assertion if the string is too long. + +* RFC 1123. This means the string must: +* - contain at most 63 characters +* - contain only lowercase alphanumeric characters or '-' +* - start with an alphanumeric character +* - end with an alphanumeric character