/*
* Copyright (c) 2012-2013 Spotify AB
*
* 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.
*/
#ifndef SPARKEY_UTIL_H_INCLUDED
#define SPARKEY_UTIL_H_INCLUDED

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "sparkey.h"

/**
 * This macro sort of behaves like a new keyword.
 * Input must be an expression that returns sparkey_returncode.
 * The macro must be executed in a function that returns sparkey_returncode.
 * If the expression evaluates to something else than SPARKEY_SUCCESS,
 * then the containing function returns that value directly.
 */
#define RETHROW(f) do { sparkey_returncode returncode = (f); if (returncode != SPARKEY_SUCCESS) return returncode; } while (0);

/**
 * This macro requires that a sparkey_returncode returncode; is already defined in the function.
 * It evaluates the first argument which must return sparkey_returncode.
 * If that evaluates to something else than SPARKEY_SUCCESS,
 * it sets the returncode to that and jumps to the specified label.
 */
#define TRY(f, label) do { returncode = (f); if (returncode != SPARKEY_SUCCESS) goto label; } while (0);

/**
 * Convert error codes generated by open and fopen into sparkey return codes.
 * @param e an error code
 * @returns a sparkey_returncode corresponding to the error, or SPARKEY_INTERNAL_ERROR
 */
sparkey_returncode sparkey_open_returncode(int e);

/**
 * Convert error codes generated by creat into sparkey return codes.
 * @param e an error code
 * @returns a sparkey_returncode corresponding to the error, or SPARKEY_INTERNAL_ERROR
 */
sparkey_returncode sparkey_create_returncode(int e);

/**
 * Convert error codes generated by remove or unlink into sparkey return codes.
 * @param e an error code
 * @returns a sparkey_returncode corresponding to the error, or SPARKEY_INTERNAL_ERROR
 */
sparkey_returncode sparkey_remove_returncode(int e);

/**
 * Fetches a 32 bit unsigned value from a pseudorandom source.
 *
 * @param output a pointer to an uint32_t where the random value is written
 * @returns a sparkey_returncode SPARKEY_SUCCESS or, in case of error SPARKEY_INTERNAL_ERROR.
 */
static inline sparkey_returncode rand32(uint32_t *output) {
  int fd = open("/dev/urandom", O_RDONLY);
  if (fd < 0) {
    return SPARKEY_INTERNAL_ERROR;
  }
  int actual = read(fd, output, 4);
  close(fd);
  if (actual < 4) {
    return SPARKEY_INTERNAL_ERROR;
  }
  return SPARKEY_SUCCESS;
}


#endif

