/****************************************************************************
**
** Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
** Copyright (C) 2013-2023 Arm Limited (or its affiliates).
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**********************************************************************/
#include "qpipewriter_p.h"
#include <io.h>

qint64 qt_native_write(Q_PIPE pipe, const char* data, qint64 len)
{
    DWORD bytesWritten = 0;
    ::WriteFile(pipe, data, static_cast<DWORD>(len), &bytesWritten, 0);

    return bytesWritten;
}

Q_PIPE qt_open_write_pipe(const char* pathname)
{
    return ::CreateNamedPipeA(pathname, 
                              PIPE_ACCESS_OUTBOUND, 
                              PIPE_NOWAIT, 
                              PIPE_UNLIMITED_INSTANCES,
                              1024, 
                              1024, 
                              3000, 
                              NULL);
}

void qt_ignore_sigpipe()
{
}

void QPipeWriterPrivate::closePipe()
{
    if (pipe != INVALID_Q_PIPE)
    {
        ::CloseHandle(pipe);
        pipe = INVALID_Q_PIPE;
    }
}

void QPipeWriterPrivate::createNotifier()
{
}

qint64 QPipeWriterPrivate::bytesAvailable() const
{
    DWORD bytesAvail = 0;
	::PeekNamedPipe(pipe, 0, 0, 0, &bytesAvail, 0);

#if defined (QPIPEWRITER_DEBUG)
    qDebug("QPipeWriterPrivate::bytesAvailable() == %ld", bytesAvail);
#endif
    return bytesAvail;
}
