Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Display String #55

Merged
merged 5 commits into from
Jan 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ ChangeLog
------------------

* Support for a new 'Date' type, from draft [draft-ietf-httpbis-sfbis-02][7].
* Support for the "Display String" type.
* Now requires Node 18.


Expand Down
11 changes: 9 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,17 @@ The following are examples of `item` headers:
Parsed as string

```
# Parsed as string
# Parsed an ASCII string
Header: "foo"

# A simple string, called a 'Token' in the spec
Header: foo

# A Unicode string, called a 'Display String' in the spec. They use
# percent encoding, but encode a different set of characters than
# URLs.
Header %"Frysl%C3%A2n"

# Parsed as number
Header: 5
Header: -10
Expand All @@ -84,7 +89,6 @@ Header: "Hello world"; a="5"
Header: @1686634251
```


To parse these header values, use the `parseItem`:

```typescript
Expand Down Expand Up @@ -217,6 +221,9 @@ serializeItem([5.5, new Map()]);
// Returns "hello world"
serializeItem(["hello world", new Map()]);

// Returns %"Frysl%C3%A2n"
serializeItem(["Fryslân", new Map()]);

// Returns ?1
serializeItem([true, new Map()]);

Expand Down
16 changes: 16 additions & 0 deletions src/displaystring.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export class DisplayString {

private value: string;
constructor(value: string) {

this.value = value;

}

toString(): string {

return this.value;

}

}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './parser';
export * from './types';
export * from './util';
export { Token } from './token';
export { DisplayString } from './displaystring';
57 changes: 57 additions & 0 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { Token } from './token';

import { isAscii } from './util';
import { DisplayString } from './displaystring';

export function parseDictionary(input: string): Dictionary {

Expand Down Expand Up @@ -185,6 +186,9 @@ export default class Parser {
if (char === '@') {
return this.parseDate();
}
if (char === '%') {
return this.parseDisplayString();
}
throw new ParseError(this.pos, 'Unexpected input');

}
Expand Down Expand Up @@ -299,6 +303,49 @@ export default class Parser {

}

private parseDisplayString(): DisplayString {

const chars = this.getChars(2);
if (chars !== '%"') {
throw new ParseError(this.pos, 'Unexpected character. Display strings should start with %=');
}

const result:number[] = [];

while (!this.eof()) {

const char = this.getChar();
if (char.charCodeAt(0) <= 0x1F || (char.charCodeAt(0) >= 0x7F && char.charCodeAt(0) <= 0xFF)) {
throw new ParseError(this.pos, 'Invalid char found in DisplayString. Did you forget to escape?');
}

if (char==='%') {
const hexChars = this.getChars(2);
if (/^[0-9a-f]{2}$/.test(hexChars)) {
result.push(parseInt(hexChars, 16));
} else {
throw new ParseError(this.pos, `Unexpected sequence after % in DispalyString: "${hexChars}". Note that hexidecimals must be lowercase`);
}
continue;
}
if (char==='"') {
const textDecoder = new TextDecoder('utf-8', {
fatal: true
});
try {
return new DisplayString(
textDecoder.decode(new Uint8Array(result))
);
} catch (err) {
throw new ParseError(this.pos, 'Fatal error decoding UTF-8 sequence in Display String');
}
}
result.push(char.charCodeAt(0));
}
throw new ParseError(this.pos, 'Unexpected end of input');

}

private parseToken(): Token {

// The specification wants this check, but it's an unreachable code block.
Expand Down Expand Up @@ -429,6 +476,16 @@ export default class Parser {

return this.input[this.pos++];

}
private getChars(count: number): string {

const result = this.input.substr(
this.pos,
count
);
this.pos += count;
return result;

}
private eof():boolean {

Expand Down
22 changes: 22 additions & 0 deletions src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { Token } from './token';

import { isAscii, isInnerList, isValidKeyStr } from './util';
import { DisplayString } from './displaystring';

export class SerializeError extends Error {}

Expand Down Expand Up @@ -80,6 +81,9 @@ export function serializeBareItem(input: BareItem): string {
if (input instanceof ByteSequence) {
return serializeByteSequence(input);
}
if (input instanceof DisplayString) {
return serializeDisplayString(input);
}
if (input instanceof Date) {
return serializeDate(input);
}
Expand Down Expand Up @@ -114,6 +118,24 @@ export function serializeString(input: string): string {
return `"${input.replace(/("|\\)/g, (v) => '\\' + v)}"`;
}

export function serializeDisplayString(input: DisplayString): string {
let out = '%"';
const textEncoder = new TextEncoder();
for (const char of textEncoder.encode(input.toString())) {
if (
char === 0x25 // %
|| char === 0x22 // "
|| char <= 0x1f
|| char >= 0x7f
) {
out += '%' + char.toString(16);
} else {
out += String.fromCharCode(char);
}
}
return out + '"';
}

export function serializeBoolean(input: boolean): string {
return input ? '?1' : '?0';
}
Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Token } from './token';
import { DisplayString } from './displaystring';

/**
* Lists are arrays of zero or more members, each of which can be an Item
Expand Down Expand Up @@ -47,6 +48,6 @@ export class ByteSequence {

}

export type BareItem = number | string | Token | ByteSequence | Date | boolean;
export type BareItem = number | string | Token | ByteSequence | Date | boolean | DisplayString;

export type Item = [BareItem, Parameters];
11 changes: 10 additions & 1 deletion test/httpwg-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const {

ParseError,
} = require('../dist');
const { Token, ByteSequence } = require('../dist');
const { Token, ByteSequence, DisplayString } = require('../dist');
const base32Encode = require('base32-encode');
const base32Decode = require('base32-decode');
const fs = require('fs');
Expand All @@ -24,6 +24,7 @@ describe('HTTP-WG tests', () => {
'string',
'token',
'date',
'display-string',

'item',

Expand Down Expand Up @@ -284,6 +285,12 @@ function packTestValue(input) {
value: input.toString()
}
}
if(input instanceof DisplayString) {
return {
__type: 'displaystring',
value: input.toString()
}
}
if (input instanceof ByteSequence) {
return {
__type: 'binary',
Expand Down Expand Up @@ -340,6 +347,8 @@ function unpackTestValue(input) {
return new ByteSequence(Buffer.from(base32Decode(input.value, 'RFC4648')).toString('base64'));
case 'date' :
return new Date(input.value * 1000);
case 'displaystring' :
return new DisplayString(input.value);
default:
throw new Error('Unknown input __type: ' + input.__type);
}
Expand Down
Loading