/*
 * This file is part of libtqtvd_astronav
 *
 * Copyright (C) 2008-2017 TQTVD Software
 * Copyright (C) 2017 Mirakulo Software (mirakulo@mirakulo.com)
 *
 * 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
 */

#ifndef UTF8_UTIL_H
#define UTF8_UTIL_H

#define UCHAR_IS_RANGE(uc, inf, sup)      (uc >= inf && uc<= sup)
#define UCHAR_IS_LATIN1(uc)               UCHAR_IS_RANGE(uc, 0x0080, 0x00FF)
#define UCHAR_IS_BASIC_LATIN(uc)          UCHAR_IS_RANGE(uc, 0x0020, 0x007F)
#define UCHAR_IS_CONTROL(uc)              (uc <= 0x001F)

#define UCHAR_LATIN1_TO_UTF8(uc)          (uc & 0xBF)

#define UTF8_ESC1   0xC2
#define UTF8_ESC2   0xC3

#define UTF8_IS_LATIN1(b0, b1)              ((b0 == UTF8_ESC1 || b0 == UTF8_ESC2) && \
                                             UCHAR_IS_RANGE(b1, 0x80, 0xBF))
#define UTF8_LATIN1_TO_UCHAR(b0, b1)        ((b0 == UTF8_ESC1) ? b1 : b1 | 0x40)

#define UTF8_MBYTE_MASK(b0, mask1, mask2)   ((b0 & mask1) == mask2)
#define UTF8_HAS_N_MORE_BYTES(n, i, len)    (i + n < len)

#define UTF8_HAS_N_BYTES(b0, mask1, mask2, n, i, len) \
    (UTF8_MBYTE_MASK(b0, mask1, mask2) && UTF8_HAS_N_MORE_BYTES(n-1, i, len))

#define UTF8_HAS_6_BYTES(b0, i, len)        UTF8_HAS_N_BYTES(b0, 0xFE, 0xFC, 6, i, len) 
#define UTF8_HAS_5_BYTES(b0, i, len)        UTF8_HAS_N_BYTES(b0, 0xFC, 0xF8, 5, i, len) 
#define UTF8_HAS_4_BYTES(b0, i, len)        UTF8_HAS_N_BYTES(b0, 0xF8, 0xF0, 4, i, len) 
#define UTF8_HAS_3_BYTES(b0, i, len)        UTF8_HAS_N_BYTES(b0, 0xF0, 0xE0, 3, i, len) 
#define UTF8_HAS_2_BYTES(b0, i, len)        UTF8_HAS_N_BYTES(b0, 0xE0, 0xC0, 2, i, len) 
#define UTF8_HAS_1_BYTE(b0)                 (b0 <= 0x7F)

#define LATIN1_PART1_INF  0x0080
#define LATIN1_PART2_INF  0x00C0

#endif
