Chromium 中JavaScript Blob API接口c++代码实现

Blob

备注: 此特性在 Web Worker 中可用。

Blob 对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取,也可以转换成 ReadableStream 来用于数据操作。

Blob 表示的不一定是 JavaScript 原生格式的数据。File 接口基于 Blob,继承了 blob 的功能并将其扩展以支持用户系统上的文件。

使用 blob

要从其他非 blob 对象和数据构造一个 Blob,请使用 Blob() 构造函数。要创建一个 blob 数据的子集 blob,请使用 slice() 方法。要获取用户文件系统上的文件对应的 Blob 对象,请参阅 File 文档。

接受 Blob 对象的 API 也被列在 File 文档中。

构造函数

Blob()

返回一个新创建的 Blob 对象,其内容由参数中给定的数组拼接组成。

实例属性

Blob.size 只读

Blob 对象中所包含数据的大小(字节)。

Blob.type 只读

一个字符串,表明该 Blob 对象所包含数据的 MIME 类型。如果类型未知,则该值为空字符串。

实例方法

Blob.arrayBuffer()

返回一个 promise,其会兑现一个包含 Blob 所有内容的二进制格式的 ArrayBuffer

Blob.bytes()

返回一个 promise,其会兑现一个包含 Blob 内容的 Uint8Array

Blob.slice()

返回一个新的 Blob 对象,其中包含调用它的 blob 的指定字节范围内的数据。

Blob.stream()

返回一个能读取 Blob 内容的 ReadableStream

Blob.text()

返回一个 promise,其会兑现一个包含 Blob 所有内容的 UTF-8 格式的字符串。

这些属性和方法在c++中的代码实现如下:

一、Blob定义third_party\blink\renderer\core\fileapi\blob.idl

/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// https://w3c.github.io/FileAPI/#blob-section

typedef (ArrayBuffer or ArrayBufferView or Blob or USVString) BlobPart;
[
    Exposed=(Window,Worker),
    Serializable
] interface Blob {
    [CallWith=ExecutionContext] constructor(optional sequence<BlobPart> blobParts, optional BlobPropertyBag options = {});
    readonly attribute unsigned long long size;
    readonly attribute DOMString type;

    // TODO(jsbell): start and end arguments should be [Clamp]
    [RaisesException] Blob slice(optional long long start, optional long long end, optional DOMString contentType);
    [CallWith=ScriptState] ReadableStream stream();
    [CallWith=ScriptState] Promise<USVString> text();
    [CallWith=ScriptState] Promise<ArrayBuffer> arrayBuffer();
};

二、blob接口实现

third_party\blink\renderer\core\fileapi\blob.h

third_party\blink\renderer\core\fileapi\blob.cc

/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FILEAPI_BLOB_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FILEAPI_BLOB_H_

#include "base/memory/scoped_refptr.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_typedefs.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/fileapi/url_registry.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap_source.h"
#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"

namespace blink {

class BlobPropertyBag;
class ExceptionState;
class ExecutionContext;

class CORE_EXPORT Blob : public ScriptWrappable,
                         public URLRegistrable,
                         public ImageBitmapSource {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static Blob* Create(ExecutionContext*) {
    return MakeGarbageCollected<Blob>(BlobDataHandle::Create());
  }

  static Blob* Create(ExecutionContext* execution_context,
                      const HeapVector<Member<V8BlobPart>>& blob_parts,
                      const BlobPropertyBag* options);

  static Blob* Create(const unsigned char* data,
                      size_t size,
                      const String& content_type);

  explicit Blob(scoped_refptr<BlobDataHandle>);
  ~Blob() override;

  virtual uint64_t size() const { return blob_data_handle_->size(); }
  Blob* slice(int64_t start,
              int64_t end,
              const String& content_type,
              ExceptionState&) const;

  // To allow ExceptionState to be passed in last, manually enumerate the
  // optional argument overloads.
  Blob* slice(ExceptionState& exception_state) const {
    return slice(0, std::numeric_limits<int64_t>::max(), String(),
                 exception_state);
  }
  Blob* slice(int64_t start, ExceptionState& exception_state) const {
    return slice(start, std::numeric_limits<int64_t>::max(), String(),
                 exception_state);
  }
  Blob* slice(int64_t start,
              int64_t end,
              ExceptionState& exception_state) const {
    return slice(start, end, String(), exception_state);
  }

  ReadableStream* stream(ScriptState* script_state) const;
  ScriptPromise text(ScriptState* script_state);
  ScriptPromise arrayBuffer(ScriptState* script_state);
  String type() const { return blob_data_handle_->GetType(); }
  String Uuid() const { return blob_data_handle_->Uuid(); }
  scoped_refptr<BlobDataHandle> GetBlobDataHandle() const {
    return blob_data_handle_;
  }
  // True for all File instances, including the user-built ones.
  virtual bool IsFile() const { return false; }
  // Only true for File instances that are backed by platform files.
  virtual bool HasBackingFile() const { return false; }

  // Used by the JavaScript Blob and File constructors.
  void AppendTo(BlobData&) const;

  // URLRegistrable to support PublicURLs.
  URLRegistry& Registry() const final;
  bool IsMojoBlob() final;
  void CloneMojoBlob(mojo::PendingReceiver<mojom::blink::Blob>) final;
  mojo::PendingRemote<mojom::blink::Blob> AsMojoBlob() const;

  // ImageBitmapSource implementation
  bool IsBlob() const override { return true; }

 protected:
  static void PopulateBlobData(BlobData* blob_data,
                               const HeapVector<Member<V8BlobPart>>& parts,
                               bool normalize_line_endings_to_native);
  static void ClampSliceOffsets(uint64_t size, int64_t& start, int64_t& end);

  // Called by the Blob and File constructors when processing the 'type'
  // option per the FileAPI standard. Returns "" if |type| contains any
  // character outside U+0020...U+007E, or |type| ASCII-lowercased otherwise.
  static String NormalizeType(const String& type);

 private:
  Blob() = delete;

  scoped_refptr<BlobDataHandle> blob_data_handle_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FILEAPI_BLOB_H_

测试用例读者自己补充验证吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值