Skip to content

Commit

Permalink
feat(ascii): conversion function for string to RFC1123 (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
Duologic authored Dec 13, 2024
1 parent 63d430b commit 1199b50
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
33 changes: 33 additions & 0 deletions ascii.libsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
17 changes: 16 additions & 1 deletion docs/ascii.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -58,4 +59,18 @@ isStringNumeric(str)
isUpper(c)
```

`isUpper` reports whether ASCII character `c` is a upper case letter
`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

0 comments on commit 1199b50

Please sign in to comment.