Skip to content

Commit

Permalink
Implement function convertLineEndingsToNative in blob.ts (denoland#2695)
Browse files Browse the repository at this point in the history
  • Loading branch information
7k8m authored and ry committed Aug 1, 2019
1 parent 3971dcf commit deec1b9
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
50 changes: 47 additions & 3 deletions js/blob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
9 changes: 9 additions & 0 deletions js/blob_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.

0 comments on commit deec1b9

Please sign in to comment.