File: stream_file.cpp

package info (click to toggle)
emscripten 2.0.12~dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 108,440 kB
  • sloc: ansic: 510,324; cpp: 384,763; javascript: 84,341; python: 51,362; sh: 50,019; pascal: 4,159; makefile: 3,409; asm: 2,150; lisp: 1,869; ruby: 488; cs: 142
file content (52 lines) | stat: -rw-r--r-- 2,064 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright 2016 The Emscripten Authors.  All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License.  Both these licenses can be
// found in the LICENSE file.

#include <string.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <emscripten/fetch.h>

// Compute rudimentary checksum of data
uint32_t checksum = 0;

int result = 0;

int main()
{
  emscripten_fetch_attr_t attr;
  emscripten_fetch_attr_init(&attr);
  strcpy(attr.requestMethod, "GET");
  attr.onsuccess = [](emscripten_fetch_t *fetch) {
    printf("Finished downloading %llu bytes\n", fetch->totalBytes);
    printf("Data checksum: %08X\n", checksum);
    assert(fetch->data == 0); // The data was streamed via onprogress, no bytes available here.
    assert(fetch->numBytes == 0);
    assert(fetch->totalBytes == 134217728);
    assert(checksum == 0xA7F8E858U);
    emscripten_fetch_close(fetch);

#ifdef REPORT_RESULT
    // Fetch API appears to sometimes call the handlers more than once, see https://github.com/emscripten-core/emscripten/pull/8191
    MAYBE_REPORT_RESULT(1);
#endif
  };
  attr.onprogress = [](emscripten_fetch_t *fetch) {
    printf("Downloading.. %.2f%s complete. Received chunk [%llu, %llu[\n", 
      (fetch->totalBytes > 0) ? ((fetch->dataOffset + fetch->numBytes) * 100.0 / fetch->totalBytes) : (double)(fetch->dataOffset + fetch->numBytes),
      (fetch->totalBytes > 0) ? "%" : " bytes",
      fetch->dataOffset,
      fetch->dataOffset + fetch->numBytes);
    assert(fetch->data != 0);
    assert(fetch->numBytes > 0);
    assert(fetch->dataOffset + fetch->numBytes <= fetch->totalBytes);
    assert(fetch->totalBytes <= 134217728);

    for(int i = 0; i < fetch->numBytes; ++i)
      checksum = ((checksum << 8) | (checksum >> 24)) * fetch->data[i] + fetch->data[i];
  };
  attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY | EMSCRIPTEN_FETCH_APPEND | EMSCRIPTEN_FETCH_STREAM_DATA;
  emscripten_fetch_t *fetch = emscripten_fetch(&attr, "largefile.txt");
}