/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 <b.h>

static void *b_io_open (unsigned char *file);
static int b_io_close (void *fd);
static int b_io_ftruncate (void *fd, b_uint64 size);

static void *b_io_mmap (void *fd, b_uint64 size, b_uint64 * ret_size);
static void b_io_munmap (void *fd, b_uint64 size);
static void b_io_msync (void *fd, b_uint64 size);

#ifdef WIN32
typedef struct b_io_win32_t b_io_win32_t;

struct b_io_win32_t
{
  HANDLE *file;
  HANDLE *data;
};
#endif

b_error_t
b_io_new (b_io_t ** ret, unsigned char *file, b_uint64 size)
{
  b_io_t *io;

  B_LOG3 ("b_io_new: %p %p %d", ret, file, (int) size);

  if (!ret || !file || size <= 0)
    return B_ERROR_DATA;

  if (!(io = calloc (1, sizeof (b_io_t))))
    return B_ERROR_MEMORY;

  if (!(io->fd = b_io_open (file)))
    {
      b_io_destroy (io);
      return B_ERROR_POSIX;
    }

  size = (B_HASH_SIZE + sizeof (b_uint64)) * size + sizeof (b_uint64);

  if (!(io->data = b_io_mmap (io->fd, size, &io->size)))
    {
      b_io_destroy (io);
      return B_ERROR_POSIX;
    }

  memcpy (&io->end_pointer, io->data, sizeof (b_uint64));

  if (!io->end_pointer)
    io->end_pointer = sizeof (b_uint64);

  *ret = io;
  return B_OK;
}

b_error_t
b_io_destroy (b_io_t * io)
{
  B_LOG1 ("b_io_destroy: %p", io);

  if (!io)
    return B_ERROR_DATA;

  b_io_sync (io);

  if (io->data && io->size)
    b_io_munmap (io->data, io->size);

  if (io->fd)
    b_io_close (io->fd);

  free (io);

  return B_OK;
}

b_error_t
b_io_sync (b_io_t * io)
{
  B_LOG1 ("b_io_sync: %p", io);

  if (!io)
    return B_ERROR_DATA;

  b_io_msync (io->data, io->size);
  return B_OK;
}

b_int64
b_io_read (b_io_t * io, void *what, b_uint64 size)
{
  B_LOG3 ("b_io_read: %p %p %d", io, what, (int) size);

  if ((io->end_pointer - io->pointer) < size)
    size = io->end_pointer - io->pointer;

  if (size)
    {
      memcpy (what, io->data + io->pointer, (size_t) size);
      io->pointer += size;
    }

  return size;
}

b_int64
b_io_write (b_io_t * io, void *what, b_uint64 size, b_uint64 buffer_max)
{
  B_LOG4 ("b_io_write: %p %p %d %d", io, what, (int) size, (int) buffer_max);

  while ((io->size - io->pointer) < size)
    {
      void *new;
      b_uint64 n, ret;

      b_io_sync (io);

      n = buffer_max * (B_HASH_SIZE + sizeof (b_uint64)) + sizeof (b_uint64);

      /* mremap doesn't work: */
      b_io_munmap (io->data, io->size);
      io->data = NULL;

      if (b_io_ftruncate (io->fd, io->size + n))
	return -1;

      if (!(new = b_io_mmap (io->fd, io->size + n, &ret)))
	return -1;

      memset (((unsigned char *) new) + io->size, 0, (size_t) n);

      io->size += n;
      io->data = new;
    }

  memcpy (io->data + io->pointer, what, (size_t) size);
  io->pointer += size;

  if (io->pointer > io->end_pointer)
    {
      io->end_pointer = io->pointer;
      memcpy (io->data, &io->end_pointer, sizeof (io->end_pointer));
    }

  return size;
}

b_int64
b_io_seek (b_io_t * io, b_uint64 size, int whence)
{
  B_LOG3 ("b_io_seek: %p %d %d", io, (int) size, whence);

  switch (whence)
    {
    case SEEK_SET:
      io->pointer = size <= io->end_pointer ? size : io->end_pointer;
      return io->pointer;

    case SEEK_END:
      io->pointer = io->end_pointer;
      return io->pointer;

    case SEEK_CUR:
    default:
      if ((io->end_pointer - io->pointer) < size)
	{
	  io->pointer = io->end_pointer;
	  return io->pointer;
	}

      io->pointer += size;
      return io->pointer;
    }
}

static void *
b_io_open (unsigned char *file)
{
#ifndef WIN32
  int fd;

  B_LOG1 ("b_io_open: %p", file);

  if ((fd = open ((char *) file, O_RDWR | O_CREAT, 0644)) == -1)
    return NULL;

  return (void *) fd;
#else
  b_io_win32_t *data;

  B_LOG1 ("b_io_open: %p", file);

  if (!(data = calloc (1, sizeof (b_io_win32_t))))
    return NULL;

  if ((data->file =
       CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0,
		   0)) == INVALID_HANDLE_VALUE)
    return NULL;

  return (void *) data;
#endif
}

static int
b_io_close (void *dummy)
{
#ifndef WIN32
  B_LOG1 ("b_io_close: %p", dummy);

  return close ((int) dummy);
#else
  b_io_win32_t *data = (b_io_win32_t *) dummy;

  B_LOG1 ("b_io_close: %p", dummy);

  CloseHandle ((HANDLE) data->data);
  CloseHandle ((HANDLE) data->file);

  free (data);
  return 0;
#endif
}

static int
b_io_ftruncate (void *dummy, b_uint64 size)
{
#ifndef WIN32
  B_LOG2 ("b_io_ftruncate: %p %d", dummy, (int) size);

  return ftruncate ((int) dummy, size);
#else
  b_io_win32_t *win = (b_io_win32_t *) dummy;

  B_LOG2 ("b_io_ftruncate: %p %d", dummy, (int) size);

  SetFilePointer (win->file, (LONG) size, 0, FILE_BEGIN);
  return 0;
#endif
}

static void *
b_io_mmap (void *dummy, b_uint64 size, b_uint64 * ret_size)
{
  unsigned char *data;

#ifndef WIN32
  struct stat st;
  int fd;

  B_LOG3 ("b_io_mmap: %p %d %p", dummy, (int) size, ret_size);

  fd = (int) dummy;

  if (fstat (fd, &st))
    return NULL;

  if ((b_uint64) st.st_size < size)
    {
      if (ftruncate (fd, size))
	return NULL;
    }

  size = (b_uint64) st.st_size < size ? size : (b_uint64) st.st_size;

  if ((data =
       mmap (0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
	     0)) == MAP_FAILED)
    return NULL;

  if ((b_uint64) st.st_size < size)
    memset (data + st.st_size, 0, size - st.st_size);

  *ret_size = size;
  return (void *) data;
#else
  b_io_win32_t *win = (b_io_win32_t *) dummy;
  b_uint64 s;

  B_LOG3 ("b_io_mmap: %p %d %p", dummy, (int) size, ret_size);

  s = GetFileSize (win->file, NULL);
  size = s < size ? size : s;

  if (!
      (win->data =
       CreateFileMapping (win->file, NULL, PAGE_READWRITE, 0, (DWORD) size,
			  NULL)) || win->data == INVALID_HANDLE_VALUE)
    return NULL;

  if (!
      (data = MapViewOfFile (win->data, FILE_MAP_WRITE, 0, 0, (SIZE_T) size)))
    return NULL;

  if (s < size)
    memset (data + s, 0, (size_t) (size - s));

  *ret_size = size;
  return data;
#endif
}

static void
b_io_munmap (void *data, b_uint64 size)
{
  B_LOG2 ("b_io_munmap: %p %d", data, (int) size);

#ifndef WIN32
  munmap (data, size);
#else
  UnmapViewOfFile (data);
#endif
}

static void
b_io_msync (void *data, b_uint64 size)
{
  B_LOG2 ("b_io_msync: %p %d", data, (int) size);

#ifndef WIN32
  msync (data, size, MS_ASYNC);
#else
  FlushViewOfFile (data, (SIZE_T) size);
#endif
}

/* EOF */
