1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <include/DataUriSource.h>
18
19#include <net/base/data_url.h>
20#include <googleurl/src/gurl.h>
21
22
23namespace android {
24
25DataUriSource::DataUriSource(const char *uri) :
26    mDataUri(uri),
27    mInited(NO_INIT) {
28
29    // Copy1: const char *uri -> String8 mDataUri.
30    std::string mimeTypeStr, unusedCharsetStr, dataStr;
31    // Copy2: String8 mDataUri -> std::string
32    const bool ret = net::DataURL::Parse(
33            GURL(std::string(mDataUri.string())),
34            &mimeTypeStr, &unusedCharsetStr, &dataStr);
35    // Copy3: std::string dataStr -> AString mData
36    mData.setTo(dataStr.data(), dataStr.length());
37    mInited = ret ? OK : UNKNOWN_ERROR;
38
39    // The chromium data url implementation defaults to using "text/plain"
40    // if no mime type is specified. We prefer to leave this unspecified
41    // instead, since the mime type is sniffed in most cases.
42    if (mimeTypeStr != "text/plain") {
43        mMimeType = mimeTypeStr.c_str();
44    }
45}
46
47ssize_t DataUriSource::readAt(off64_t offset, void *out, size_t size) {
48    if (mInited != OK) {
49        return mInited;
50    }
51
52    const off64_t length = mData.size();
53    if (offset >= length) {
54        return UNKNOWN_ERROR;
55    }
56
57    const char *dataBuf = mData.c_str();
58    const size_t bytesToCopy =
59            offset + size >= length ? (length - offset) : size;
60
61    if (bytesToCopy > 0) {
62        memcpy(out, dataBuf + offset, bytesToCopy);
63    }
64
65    return bytesToCopy;
66}
67
68}  // namespace android
69