1/*
2 * Copyright (c) 2024-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <cinttypes>
17#include <mutex>
18#include <stdexcept>
19#include <string>
20
21#include "signature_tools_log.h"
22#include "random_access_file_output.h"
23
24namespace OHOS {
25namespace SignatureTools {
26RandomAccessFileOutput::RandomAccessFileOutput(RandomAccessFile* file)
27    : RandomAccessFileOutput(file, 0)
28{
29}
30
31RandomAccessFileOutput::RandomAccessFileOutput(RandomAccessFile* file, int64_t startPosition)
32    : file(file)
33{
34    if (startPosition < 0) {
35        SIGNATURE_TOOLS_LOGE("invalide start position: %" PRId64, startPosition);
36        return;
37    }
38    position = startPosition;
39}
40
41bool RandomAccessFileOutput::Write(ByteBuffer& buffer)
42{
43    int length = buffer.GetCapacity();
44    if (length == 0) {
45        return false;
46    }
47    {
48        std::mutex tmpMutex;
49        std::scoped_lock lock(tmpMutex);
50        if (file->WriteToFile(buffer, position, length) < 0) {
51            PrintErrorNumberMsg("IO_ERROR", IO_ERROR, "write from ByteBuffer to RandomAccessFile failed");
52            return false;
53        }
54        position += length;
55    }
56    return true;
57}
58} // namespace SignatureTools
59} // namespace OHOS
60