diff --git a/js/blob.ts b/js/blob.ts index 7b4d23c4673939e42eb80da6f01efcfe61bb3d00..f2668b642a8df647dfe28fdb3d87150aa8a9f84c 100644 --- a/js/blob.ts +++ b/js/blob.ts @@ -2,13 +2,57 @@ import * as domTypes from "./dom_types"; import { containsOnlyASCII, hasOwnProperty } from "./util"; import { TextEncoder } from "./text_encoding"; +import { build } from "./build"; export const bytesSymbol = Symbol("bytes"); function convertLineEndingsToNative(s: string): string { - // TODO(qti3e) Implement convertLineEndingsToNative. - // https://w3c.github.io/FileAPI/#convert-line-endings-to-native - return s; + let nativeLineEnd = build.os == "win" ? "\r\n" : "\n"; + + let position = 0; + + let collectionResult = collectSequenceNotCRLF(s, position); + + let token = collectionResult.collected; + position = collectionResult.newPosition; + + let result = token; + + while (position < s.length) { + let c = s.charAt(position); + if (c == "\r") { + result += nativeLineEnd; + position++; + if (position < s.length && s.charAt(position) == "\n") { + position++; + } + } else if (c == "\n") { + position++; + result += nativeLineEnd; + } + + collectionResult = collectSequenceNotCRLF(s, position); + + token = collectionResult.collected; + position = collectionResult.newPosition; + + result += token; + } + + return result; +} + +function collectSequenceNotCRLF( + s: string, + position: number +): { collected: string; newPosition: number } { + const start = position; + for ( + let c = s.charAt(position); + position < s.length && !(c == "\r" || c == "\n"); + c = s.charAt(++position) + ); + return { collected: s.slice(start, position), newPosition: position }; } function toUint8Arrays( diff --git a/js/blob_test.ts b/js/blob_test.ts index b11a22f3c4bae9a0592a0a63fdcb3a7c71b73f35..7fc7db1e2ee38bd1572420e1728350e26154fee7 100644 --- a/js/blob_test.ts +++ b/js/blob_test.ts @@ -50,4 +50,13 @@ test(function blobShouldNotThrowError(): void { assertEquals(hasThrown, false); }); +test(function nativeEndLine(): void { + const options: object = { + ending: "native" + }; + let blob = new Blob(["Hello\nWorld"], options); + + assertEquals(blob.size, Deno.build.os === "win" ? 12 : 11); +}); + // TODO(qti3e) Test the stored data in a Blob after implementing FileReader API.