ArrayBuffer 관련 정리

q6hillz·2022년 4월 14일
0

javascript

목록 보기
4/60

out of bounds behavior

What if we attempt to write an out-of-bounds value into a typed array? There will be no error. But extra bits are cut-off.

For instance, let’s try to put 256 into Uint8Array. In binary form, 256 is 100000000 (9 bits), but Uint8Array only provides 8 bits per value, that makes the available range from 0 to 255.

For bigger numbers, only the rightmost (less significant) 8 bits are stored, and the rest is cut off:

So we’ll get zero.

For 257, the binary form is 100000001 (9 bits), the rightmost 8 get stored, so we’ll have 1 in the array:

간단하게 생각하면 1byte(8bit) 체계안에서 표현할 수 있는 범위 0~255(unassigned) 와 같은 경우 256값을 입력하면 9bit 표현으로 넘어가고 쇼케이스 가능한 스코프는 8bit이기 때문에 256=> 0(10진수)를 출력하게 된다는 글.

Uint8ClampedArray

The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Constructor

위와 같은 일을 방지하기 위해서 최소, 최대 값이 정해진 ClampedArray의 등장. 만약 out of range 값이 입력되게 되면 자동으로 0,255로 치환된다.

TextEncoder

TextEncoder does the reverse thing – converts a string into bytes.

The syntax is:

let encoder = new TextEncoder();

The only encoding it supports is “utf-8”.

It has two methods:

  • encode(str) – returns Uint8Array from a string.
  • encodeInto(str, destination) – encodes str into destination that must be Uint8Array.
let encoder = new TextEncoder();

let uint8Array = encoder.encode("Hello");
alert(uint8Array); // 72,101,108,108,111

네트워크 상에서 문자를 주고받기 위해서는 bit값으로의 변환이 필요함. 그때 사용할 수 있는 class textencoder이다.

Blob

ArrayBuffer and views are a part of ECMA standard, a part of JavaScript.

In the browser, there are additional higher-level objects, described in File API, in particular Blob.

Blob consists of an optional string type (a MIME-type usually), plus blobParts – a sequence of other Blob objects, strings and BufferSource.

The constructor syntax is:

new Blob(blobParts, options);

MIME types (IANA media types)

A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) indicates the nature and format of a document, file, or assortment of bytes. MIME types are defined and standardized in IETF's RFC 6838.

Structure of a MIME type

A simplest MIME type consists of a type and a subtype. A MIME type comprises these strings concatenated with a slash (/). No whitespace is allowed in a MIME type:

type/subtype

The *type* represents the general category into which the data type falls, such as video or text.

The *subtype* identifies the exact kind of data of the specified type the MIME type represents. For example, for the MIME type text, the subtype might be plain (plain text), html (HTML source code), or calendar (for iCalendar/.ics) files.

Each type has its own set of possible subtypes. A MIME type always has both a type and a subtype, never just one or the other.

An optional parameter can be added to provide additional details:

type/subtype;parameter=value

For example, for any MIME type whose main type is text, you can add the optional charset parameter to specify the character set used for the characters in the data. If no charset is specified, the default is ASCII (US-ASCII) unless overridden by the user agent's settings. To specify a UTF-8 text file, the MIME type text/plain;charset=UTF-8 is used.

MIME types are case-insensitive but are traditionally written in lowercase. The parameter values can be case-sensitive.

//발송부
let link = document.createElement('a');
link.download = 'hello.txt';

let blob = new Blob(['Hello, world!'], {type: 'text/plain'});

link.href = URL.createObjectURL(blob);

link.click();

URL.revokeObjectURL(link.href);

//수신부
let reader = new FileReader();
reader.readAsDataURL(blob); // converts the blob to base64 and calls onload

URL.createObjectURL takes a Blob and creates a unique URL for it, in the form blob:<origin>/<uuid>.

That’s what the value of link.href looks like:

URL.createObjectURL takes a Blob and creates a unique URL for it, in the form blob:<origin>/<uuid>.

That’s what the value of link.href looks like:

blob:https://javascript.info/1e67e00e-860d-40a5-89ae-6ab0cbee6273

ArrayBuffer의 진화판 Blob에 대한 소개글이다. 어떻게 보면 arraybuffer로 다양한 데이터의 체계를 손쉽게 제어하기는 쉽지 않아 user friendly한 class를 만들게 되니 등장하게 된 것 같다.

MIME Type(indicates the nature and format of a document, file, or assortment of bytes)은 다양하다. 이미지 포멧, 캘린더 포멧, 동영상 포멧과 걸맞은 여러 인코딩 디코딩 방식이 존재할 것이다. 이들은 JS blob 설정을 해주고, 수신부에서는 FileReader를 장비하게 된다면 간편하게 네트워크에서 주고 받을 수 있는 시스템이 만들어 질 수 있어 보인다.

위에서는 또 주목해야 할 점은 URL.createObjectURL 메소드 인데, 유니크한 아이디(uuid)를 해당 blob에 연결시키는 해시 구조를 창출해낸다. 고로, 데이터 전송이 끝내고 만약 메모리가 부족하다면 수동으로 URL.revokeObjectURL(url)을 실행시켜 해지해 주어야 한다.

Filereader

FileReader is an object with the sole purpose of reading data from Blob (and hence File too) objects.

It delivers the data using events, as reading from disk may take time.

The constructor:

let reader = new FileReader(); // no arguments

As File inherits from Blob

The main methods:

  • readAsArrayBuffer(blob) – read the data in binary format ArrayBuffer.
  • readAsText(blob, [encoding]) – read the data as a text string with the given encoding (utf-8 by default).
  • readAsDataURL(blob) – read the binary data and encode it as base64 data url.
  • abort() – cancel the operation.

As the reading proceeds, there are events:

  • loadstart – loading started.
  • progress – occurs during reading.
  • load – no errors, reading complete.
  • abortabort() called.
  • error – error has occurred.
  • loadend – reading finished with either success or failure.

When the reading is finished, we can access the result as:

  • reader.result is the result (if successful)
  • reader.error is the error (if failed).

FileReader for blobs

As mentioned in the chapter Blob, FileReader can read not just files, but any blobs.

We can use it to convert a blob to another format:

  • readAsArrayBuffer(blob) – to ArrayBuffer,
  • readAsText(blob, [encoding]) – to string (an alternative to TextDecoder),
  • readAsDataURL(blob) – to base64 data url.

In many cases though, we don’t have to read the file contents. Just as we did with blobs, we can create a short url with URL.createObjectURL(file) and assign it to <a> or <img>. This way the file can be downloaded or shown up as an image, as a part of canvas etc.

js엔진에서 자연스럽게 해석되기 위해서는 정해진 encode 규칙이 존재할 것이다.

0개의 댓글