Skip to content

Commit

Permalink
fix(source-memory): allow creating source with string url
Browse files Browse the repository at this point in the history
  • Loading branch information
blacha committed Jul 20, 2023
1 parent c2ccb55 commit 640a4a4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
10 changes: 10 additions & 0 deletions packages/source-memory/src/__test__/memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,14 @@ describe('SourceMemory', () => {
const bytesNegative = await source.fetch(-2);
assert.equal(Buffer.from(bytesNegative).toString(), '23');
});

it('should allow string names', () => {
const array = new Uint8Array(chars.split('').map((c) => c.charCodeAt(0)));

const source = new SourceMemory('memory://test.txt', array);
assert.equal(source.url.href, 'memory://test.txt');

const sourceRel = new SourceMemory('test.txt', array);
assert.equal(sourceRel.url.href, 'memory://test.txt');
});
});
13 changes: 10 additions & 3 deletions packages/source-memory/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { Source, SourceError, SourceMetadata } from '@chunkd/source';
import { Source, SourceError, SourceMetadata, tryParseUrl } from '@chunkd/source';

function parseMemoryUrl(s: string | URL): URL {
if (typeof s !== 'string') return s;
const url = tryParseUrl(s);
if (url) return url;
return new URL('memory://' + s);
}

export class SourceMemory implements Source {
url: URL;
Expand All @@ -12,9 +19,9 @@ export class SourceMemory implements Source {
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}

constructor(url: URL, bytes: Buffer | Uint8Array | ArrayBuffer) {
constructor(url: URL | string, bytes: Buffer | Uint8Array | ArrayBuffer) {
const buf = SourceMemory.toArrayBuffer(bytes ?? new Uint8Array());
this.url = url;
this.url = parseMemoryUrl(url);
this.data = buf;
this.metadata = { size: buf.byteLength };
}
Expand Down

0 comments on commit 640a4a4

Please sign in to comment.