diff --git a/.prettierrc.json b/.prettierrc.json index 544138b..4f10486 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,3 +1,4 @@ { - "singleQuote": true + "singleQuote": true, + "maxLineLength": 80 } diff --git a/src/index.ts b/src/index.ts index 28c7da5..bc1e466 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,13 +9,14 @@ import * as unicode from './encoding/unicode'; import * as mbcs from './encoding/mbcs'; import * as sbcs from './encoding/sbcs'; import * as iso2022 from './encoding/iso2022'; +import { isByteArray } from './utils'; interface FullOptions { - sampleSize: number, - offset: number + sampleSize: number; + offset: number; } -export type Options = Partial +export type Options = Partial; const recognisers: Recogniser[] = [ new Utf8(), @@ -53,6 +54,10 @@ export const detect = (buffer: Uint8Array): string | null => { }; export const analyse = (buffer: Uint8Array): AnalyseResult => { + if (!isByteArray(buffer)) { + throw new Error('Input must be a byte array, e.g. Buffer or Uint8Array'); + } + // Tally up the byte occurrence statistics. const byteStats = []; for (let i = 0; i < 256; i++) byteStats[i] = 0; @@ -88,9 +93,12 @@ export const analyse = (buffer: Uint8Array): AnalyseResult => { }); return matches as Match[]; -} +}; -export const detectFile = (filepath: string, opts: Options = {}): Promise => +export const detectFile = ( + filepath: string, + opts: Options = {} +): Promise => new Promise((resolve, reject) => { let fd: any; const fs = loadFs(); @@ -120,7 +128,10 @@ export const detectFile = (filepath: string, opts: Options = {}): Promise { +export const detectFileSync = ( + filepath: string, + opts: Options = {} +): DetectResult => { const fs = loadFs(); if (opts && opts.sampleSize) { diff --git a/src/utils.test.ts b/src/utils.test.ts new file mode 100644 index 0000000..7efb05b --- /dev/null +++ b/src/utils.test.ts @@ -0,0 +1,18 @@ +import { isByteArray } from './utils'; + +describe('isByteArray', () => { + test('positives', () => { + expect(isByteArray(Buffer.from('hello'))).toBe(true); + expect(isByteArray(new Uint8Array(0))).toBe(true); + expect(isByteArray(new Uint8Array(1))).toBe(true); + expect(isByteArray([])).toBe(true); + expect(isByteArray([1])).toBe(true); + }); + + test('negatives', () => { + expect(isByteArray(null)).toBe(false); + expect(isByteArray('')).toBe(false); + expect(isByteArray('hello')).toBe(false); + expect(isByteArray(123)).toBe(false); + }); +}); diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000..34104cc --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,7 @@ +// May also check if every element is a number <= 255 but +// it a little bit slower +export const isByteArray = (input: any): input is Uint8Array => { + if (input == null || typeof input != 'object') return false; + + return isFinite(input.length) && input.length >= 0; +};