d6cfb1f1创建于 4月27日历史提交
/*
 * Copyright (c) 2026 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "StreamSourceHarmony.h"
#include <algorithm>
#include <cstring>

namespace apng_drawable {
StreamSourceHarmony::StreamSourceHarmony(const uint8_t *data, size_t size)
    : mData(data), mSize(size), mOffset(0), mError(SUCCESS)
{
    if (!data || size == 0) {
        mError = ERR_STREAM_READ_FAIL;
    }
}

int32_t StreamSourceHarmony::CheckPngSignature()
{
    if (mError != SUCCESS) {
        return mError;
    }

    if (mSize < PNG_SIG_SIZE) {
        mError = ERR_UNEXPECTED_EOF;
        return mError;
    }

    if (png_sig_cmp(mData, 0, PNG_SIG_SIZE) != 0) {
        mError = ERR_INVALID_FILE_FORMAT;
        return mError;
    }

    return SUCCESS;
}

void StreamSourceHarmony::Init(png_structp pngPtr)
{
    png_set_read_fn(pngPtr, this, Reader);
}

void StreamSourceHarmony::Reader(png_structp png, png_bytep data, png_size_t length)
{
    auto *source = static_cast<StreamSourceHarmony *>(png_get_io_ptr(png));

    if (source->mOffset >= source->mSize) {
        source->mError = ERR_UNEXPECTED_EOF;
        png_error(png, "Unexpected EOF");
        return;
    }

    size_t available = source->mSize - source->mOffset;
    size_t toRead = (length < available) ? length : available;

    if (toRead > 0) {
        std::copy_n(const_cast<unsigned char*>(source->mData) + source->mOffset, toRead, data);
        source->mOffset += toRead;
    }

    if (toRead < length) {
        source->mError = ERR_UNEXPECTED_EOF;
        png_error(png, "Unexpected EOF");
    }
}

void StreamSourceHarmony::Reset()
{
    mOffset = 0;
    mError = SUCCESS;
}
}