text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2014-2016, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/

#ifndef UDISPLAYCONTEXT_H
#define UDISPLAYCONTEXT_H

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

/**
 * \file
 * \brief C API: Display context types (enum values)
 */

/**
 * Display context types, for getting values of a particular setting.
 * Note, the specific numeric values are internal and may change.
 * @stable ICU 51
 */
enum UDisplayContextType {
    /**
     * Type to retrieve the dialect handling setting, e.g.
     * UDISPCTX_STANDARD_NAMES or UDISPCTX_DIALECT_NAMES.
     * @stable ICU 51
     */
    UDISPCTX_TYPE_DIALECT_HANDLING = 0,
    /**
     * Type to retrieve the capitalization context setting, e.g.
     * UDISPCTX_CAPITALIZATION_NONE, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,
     * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, etc.
     * @stable ICU 51
     */
    UDISPCTX_TYPE_CAPITALIZATION = 1,
    /**
     * Type to retrieve the display length setting, e.g.
     * UDISPCTX_LENGTH_FULL, UDISPCTX_LENGTH_SHORT.
     * @stable ICU 54
     */
    UDISPCTX_TYPE_DISPLAY_LENGTH = 2,
    /**
     * Type to retrieve the substitute handling setting, e.g.
     * UDISPCTX_SUBSTITUTE, UDISPCTX_NO_SUBSTITUTE.
     * @stable ICU 58
     */
    UDISPCTX_TYPE_SUBSTITUTE_HANDLING = 3
};
/**
*  @stable ICU 51
*/
typedef enum UDisplayContextType UDisplayContextType;

/**
 * Display context settings.
 * Note, the specific numeric values are internal and may change.
 * @stable ICU 51
 */
enum UDisplayContext {
    /**
     * ================================
     * DIALECT_HANDLING can be set to one of UDISPCTX_STANDARD_NAMES or
     * UDISPCTX_DIALECT_NAMES. Use UDisplayContextType UDISPCTX_TYPE_DIALECT_HANDLING
     * to get the value.
     */
    /**
     * A possible setting for DIALECT_HANDLING:
     * use standard names when generating a locale name,
     * e.g. en_GB displays as 'English (United Kingdom)'.
     * @stable ICU 51
     */
    UDISPCTX_STANDARD_NAMES = (UDISPCTX_TYPE_DIALECT_HANDLING<<8) + 0,
    /**
     * A possible setting for DIALECT_HANDLING:
     * use dialect names, when generating a locale name,
     * e.g. en_GB displays as 'British English'.
     * @stable ICU 51
     */
    UDISPCTX_DIALECT_NAMES = (UDISPCTX_TYPE_DIALECT_HANDLING<<8) + 1,
    /**
     * ================================
     * CAPITALIZATION can be set to one of UDISPCTX_CAPITALIZATION_NONE,
     * UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,
     * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE,
     * UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU, or
     * UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
     * Use UDisplayContextType UDISPCTX_TYPE_CAPITALIZATION to get the value.
     */
    /**
     * The capitalization context to be used is unknown (this is the default value).
     * @stable ICU 51
     */
    UDISPCTX_CAPITALIZATION_NONE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 0,
    /**
     * The capitalization context if a date, date symbol or display name is to be
     * formatted with capitalization appropriate for the middle of a sentence.
     * @stable ICU 51
     */
    UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 1,
    /**
     * The capitalization context if a date, date symbol or display name is to be
     * formatted with capitalization appropriate for the beginning of a sentence.
     * @stable ICU 51
     */
    UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 2,
    /**
     * The capitalization context if a date, date symbol or display name is to be
     * formatted with capitalization appropriate for a user-interface list or menu item.
     * @stable ICU 51
     */
    UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 3,
    /**
     * The capitalization context if a date, date symbol or display name is to be
     * formatted with capitalization appropriate for stand-alone usage such as an
     * isolated name on a calendar page.
     * @stable ICU 51
     */
    UDISPCTX_CAPITALIZATION_FOR_STANDALONE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 4,
    /**
     * ================================
     * DISPLAY_LENGTH can be set to one of UDISPCTX_LENGTH_FULL or
     * UDISPCTX_LENGTH_SHORT. Use UDisplayContextType UDISPCTX_TYPE_DISPLAY_LENGTH
     * to get the value.
     */
    /**
     * A possible setting for DISPLAY_LENGTH:
     * use full names when generating a locale name,
     * e.g. "United States" for US.
     * @stable ICU 54
     */
    UDISPCTX_LENGTH_FULL = (UDISPCTX_TYPE_DISPLAY_LENGTH<<8) + 0,
    /**
     * A possible setting for DISPLAY_LENGTH:
     * use short names when generating a locale name,
     * e.g. "U.S." for US.
     * @stable ICU 54
     */
    UDISPCTX_LENGTH_SHORT = (UDISPCTX_TYPE_DISPLAY_LENGTH<<8) + 1,
    /**
     * ================================
     * SUBSTITUTE_HANDLING can be set to one of UDISPCTX_SUBSTITUTE or
     * UDISPCTX_NO_SUBSTITUTE. Use UDisplayContextType UDISPCTX_TYPE_SUBSTITUTE_HANDLING
     * to get the value.
     */
    /**
     * A possible setting for SUBSTITUTE_HANDLING:
     * Returns a fallback value (e.g., the input code) when no data is available.
     * This is the default value.
     * @stable ICU 58
     */
    UDISPCTX_SUBSTITUTE = (UDISPCTX_TYPE_SUBSTITUTE_HANDLING<<8) + 0,
    /**
     * A possible setting for SUBSTITUTE_HANDLING:
     * Returns a null value when no data is available.
     * @stable ICU 58
     */
    UDISPCTX_NO_SUBSTITUTE = (UDISPCTX_TYPE_SUBSTITUTE_HANDLING<<8) + 1

};
/**
*  @stable ICU 51
*/
typedef enum UDisplayContext UDisplayContext;

#endif /* #if !UCONFIG_NO_FORMATTING */

#endif

repo_language: C

mime_type: text/x-c


text:
/*
******************************************************************************
*
* © 2016 and later: Unicode, Inc. and others.
* License & terms of use: http://www.unicode.org/copyright.html
*
******************************************************************************
*   file name:  ubiditransform.h
*   encoding:   UTF-8
*   tab size:   8 (not used)
*   indentation:4
*
*   created on: 2016jul24
*   created by: Lina Kemmel
*
*/

#ifndef UBIDITRANSFORM_H
#define UBIDITRANSFORM_H

#include "unicode/utypes.h"
#include "unicode/ubidi.h"
#include "unicode/uchar.h"
#include "unicode/localpointer.h"

/**
 * \file
 * \brief Bidi Transformations
 */

/**
 * `UBiDiOrder` indicates the order of text.
 *
 * This bidi transformation engine supports all possible combinations (4 in
 * total) of input and output text order:
 *
 *   - <logical input, visual output>: unless the output direction is RTL, this
 *     corresponds to a normal operation of the Bidi algorithm as described in the
 *     Unicode Technical Report and implemented by `UBiDi` when the
 *     reordering mode is set to `UBIDI_REORDER_DEFAULT`. Visual RTL
 *     mode is not supported by `UBiDi` and is accomplished through
 *     reversing a visual LTR string,
 *
 *   - <visual input, logical output>: unless the input direction is RTL, this
 *     corresponds to an "inverse bidi algorithm" in `UBiDi` with the
 *     reordering mode set to `UBIDI_REORDER_INVERSE_LIKE_DIRECT`.
 *     Visual RTL mode is not not supported by `UBiDi` and is
 *     accomplished through reversing a visual LTR string,
 *
 *   - <logical input, logical output>: if the input and output base directions
 *     mismatch, this corresponds to the `UBiDi` implementation with the
 *     reordering mode set to `UBIDI_REORDER_RUNS_ONLY`; and if the
 *     input and output base directions are identical, the transformation engine
 *     will only handle character mirroring and Arabic shaping operations without
 *     reordering,
 *
 *   - <visual input, visual output>: this reordering mode is not supported by
 *     the `UBiDi` engine; it implies character mirroring, Arabic
 *     shaping, and - if the input/output base directions mismatch -  string
 *     reverse operations.
 * @see ubidi_setInverse
 * @see ubidi_setReorderingMode
 * @see UBIDI_REORDER_DEFAULT
 * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT
 * @see UBIDI_REORDER_RUNS_ONLY
 * @stable ICU 58
 */
typedef enum {
    /** 0: Constant indicating a logical order.
      * This is the default for input text.
      * @stable ICU 58
      */
    UBIDI_LOGICAL = 0,
    /** 1: Constant indicating a visual order.
      * This is a default for output text.
      * @stable ICU 58
      */
    UBIDI_VISUAL
} UBiDiOrder;

/**
 * UBiDiMirroring indicates whether or not characters with the
 * "mirrored" property in RTL runs should be replaced with their mirror-image
 * counterparts.
 * @see UBIDI_DO_MIRRORING
 * @see ubidi_setReorderingOptions
 * @see ubidi_writeReordered
 * @see ubidi_writeReverse
 * @stable ICU 58
 */
typedef enum {
    /** 0: Constant indicating that character mirroring should not be
      * performed.
      * This is the default.
      * @stable ICU 58
      */
    UBIDI_MIRRORING_OFF = 0,
    /** 1: Constant indicating that character mirroring should be performed.
      * This corresponds to calling ubidi_writeReordered or
      * ubidi_writeReverse with the
      * UBIDI_DO_MIRRORING option bit set.
      * @stable ICU 58
      */
    UBIDI_MIRRORING_ON
} UBiDiMirroring;

/**
 * Forward declaration of the UBiDiTransform structure that stores
 * information used by the layout transformation engine.
 * @stable ICU 58
 */
typedef struct UBiDiTransform UBiDiTransform;

/**
 * Performs transformation of text from the bidi layout defined by the input
 * ordering scheme to the bidi layout defined by the output ordering scheme,
 * and applies character mirroring and Arabic shaping operations.

 * In terms of UBiDi, such a transformation implies:
 *

 *
calling ubidi_setReorderingMode as needed (when the
 * reordering mode is other than normal),

 *
calling ubidi_setInverse as needed (when text should be
 * transformed from a visual to a logical form),

 *
resolving embedding levels of each character in the input text by
 * calling ubidi_setPara,

 *
reordering the characters based on the computed embedding levels, also
 * performing character mirroring as needed, and streaming the result to the
 * output, by calling ubidi_writeReordered,

 *
performing Arabic digit and letter shaping on the output text by calling
 * u_shapeArabic.

 *

 * An "ordering scheme" encompasses the base direction and the order of text,
 * and these characteristics must be defined by the caller for both input and
 * output explicitly .

 * There are 36 possible combinations of <input, output> ordering schemes,
 * which are partially supported by UBiDi already. Examples of the
 * currently supported combinations:
 *

 *
<Logical LTR, Visual LTR>: this is equivalent to calling
 * ubidi_setPara with paraLevel == UBIDI_LTR,

 *
<Logical RTL, Visual LTR>: this is equivalent to calling
 * ubidi_setPara with paraLevel == UBIDI_RTL,

 *
<Logical Default ("Auto") LTR, Visual LTR>: this is equivalent to
 * calling ubidi_setPara with
 * paraLevel == UBIDI_DEFAULT_LTR,

 *
<Logical Default ("Auto") RTL, Visual LTR>: this is equivalent to
 * calling ubidi_setPara with
 * paraLevel == UBIDI_DEFAULT_RTL,

 *
<Visual LTR, Logical LTR>: this is equivalent to
 * calling ubidi_setInverse(UBiDi*, TRUE) and then
 * ubidi_setPara with paraLevel == UBIDI_LTR,

 *
<Visual LTR, Logical RTL>: this is equivalent to
 * calling ubidi_setInverse(UBiDi*, TRUE) and then
 * ubidi_setPara with paraLevel == UBIDI_RTL.

 *

 * All combinations that involve the Visual RTL scheme are unsupported by
 * UBiDi, for instance:
 *

 *
<Logical LTR, Visual RTL>,

 *
<Visual RTL, Logical RTL>.

 *

 *
Example of usage of the transformation engine:

 *

 * \code
 * UChar text1[] = {'a', 'b', 'c', 0x0625, '1', 0};
 * UChar text2[] = {'a', 'b', 'c', 0x0625, '1', 0};
 * UErrorCode errorCode = U_ZERO_ERROR;
 * // Run a transformation.
 * ubiditransform_transform(pBidiTransform,
 *          text1, -1, text2, -1,
 *          UBIDI_LTR, UBIDI_VISUAL,
 *          UBIDI_RTL, UBIDI_LOGICAL,
 *          UBIDI_MIRRORING_OFF,
 *          U_SHAPE_DIGITS_AN2EN | U_SHAPE_DIGIT_TYPE_AN_EXTENDED,
 *          &errorCode);
 * // Do something with text2.
 *  text2[4] = '2';
 * // Run a reverse transformation.
 * ubiditransform_transform(pBidiTransform,
 *          text2, -1, text1, -1,
 *          UBIDI_RTL, UBIDI_LOGICAL,
 *          UBIDI_LTR, UBIDI_VISUAL,
 *          UBIDI_MIRRORING_OFF,
 *          U_SHAPE_DIGITS_EN2AN | U_SHAPE_DIGIT_TYPE_AN_EXTENDED,
 *          &errorCode);
 *\endcode
 *

 *

 *
 * @param pBiDiTransform A pointer to a UBiDiTransform object
 *        allocated with ubiditransform_open() or
 *        NULL.

 *        This object serves for one-time setup to amortize initialization
 *        overheads. Use of this object is not thread-safe. All other threads
 *        should allocate a new UBiDiTransform object by calling
 *        ubiditransform_open() before using it. Alternatively,
 *        a caller can set this parameter to NULL, in which case
 *        the object will be allocated by the engine on the fly.

 * @param src A pointer to the text that the Bidi layout transformations will
 *        be performed on.
 *
Note: the text must be (at least)
 *        srcLength long.

 * @param srcLength The length of the text, in number of UChars. If
 *        length == -1 then the text must be zero-terminated.
 * @param dest A pointer to where the processed text is to be copied.
 * @param destSize The size of the dest buffer, in number of
 *        UChars. If the U_SHAPE_LETTERS_UNSHAPE option is set,
 *        then the destination length could be as large as
 *        srcLength * 2. Otherwise, the destination length will
 *        not exceed srcLength. If the caller reserves the last
 *        position for zero-termination, it should be excluded from
 *        destSize.
 *
destSize == -1 is allowed and makes sense when
 *        dest was holds some meaningful value, e.g. that of
 *        src. In this case dest must be
 *        zero-terminated.

 * @param inParaLevel A base embedding level of the input as defined in
 *        ubidi_setPara documentation for the
 *        paraLevel parameter.
 * @param inOrder An order of the input, which can be one of the
 *        UBiDiOrder values.
 * @param outParaLevel A base embedding level of the output as defined in
 *        ubidi_setPara documentation for the
 *        paraLevel parameter.
 * @param outOrder An order of the output, which can be one of the
 *        UBiDiOrder values.
 * @param doMirroring Indicates whether or not to perform character mirroring,
 *        and can accept one of the UBiDiMirroring values.
 * @param shapingOptions Arabic digit and letter shaping options defined in the
 *        ushape.h documentation.
 *
Note: Direction indicator options are computed by
 *        the transformation engine based on the effective ordering schemes, so
 *        user-defined direction indicators will be ignored.

 * @param pErrorCode A pointer to an error code value.
 *
 * @return The destination length, i.e. the number of UChars written to
 *         dest. If the transformation fails, the return value
 *         will be 0 (and the error code will be written to
 *         pErrorCode).
 *
 * @see UBiDiLevel
 * @see UBiDiOrder
 * @see UBiDiMirroring
 * @see ubidi_setPara
 * @see u_shapeArabic
 * @stable ICU 58
 */
U_STABLE uint32_t U_EXPORT2
ubiditransform_transform(UBiDiTransform *pBiDiTransform,
            const UChar *src, int32_t srcLength,
            UChar *dest, int32_t destSize,
            UBiDiLevel inParaLevel, UBiDiOrder inOrder,
            UBiDiLevel outParaLevel, UBiDiOrder outOrder,
            UBiDiMirroring doMirroring, uint32_t shapingOptions,
            UErrorCode *pErrorCode);

/**
 * Allocates a UBiDiTransform object. This object can be reused,
 * e.g. with different ordering schemes, mirroring or shaping options.

 * Note:The object can only be reused in the same thread.
 * All other threads should allocate a new UBiDiTransform object
 * before using it.

 * Example of usage:

 *

 * \code
 * UErrorCode errorCode = U_ZERO_ERROR;
 * // Open a new UBiDiTransform.
 * UBiDiTransform* transform = ubiditransform_open(&errorCode);
 * // Run a transformation.
 * ubiditransform_transform(transform,
 *          text1, -1, text2, -1,
 *          UBIDI_RTL, UBIDI_LOGICAL,
 *          UBIDI_LTR, UBIDI_VISUAL,
 *          UBIDI_MIRRORING_ON,
 *          U_SHAPE_DIGITS_EN2AN,
 *          &errorCode);
 * // Do something with the output text and invoke another transformation using
 * //   that text as input.
 * ubiditransform_transform(transform,
 *          text2, -1, text3, -1,
 *          UBIDI_LTR, UBIDI_VISUAL,
 *          UBIDI_RTL, UBIDI_VISUAL,
 *          UBIDI_MIRRORING_ON,
 *          0, &errorCode);
 *\endcode
 *

 *

 * The UBiDiTransform object must be deallocated by calling
 * ubiditransform_close().
 *
 * @return An empty UBiDiTransform object.
 * @stable ICU 58
 */
U_STABLE UBiDiTransform* U_EXPORT2
ubiditransform_open(UErrorCode *pErrorCode);

/**
 * Deallocates the given UBiDiTransform object.
 * @stable ICU 58
 */
U_STABLE void U_EXPORT2
ubiditransform_close(UBiDiTransform *pBidiTransform);

#if U_SHOW_CPLUSPLUS_API

U_NAMESPACE_BEGIN

/**
 * \class LocalUBiDiTransformPointer
 * "Smart pointer" class, closes a UBiDiTransform via ubiditransform_close().
 * For most methods see the LocalPointerBase base class.
 *
 * @see LocalPointerBase
 * @see LocalPointer
 * @stable ICU 58
 */
U_DEFINE_LOCAL_OPEN_POINTER(LocalUBiDiTransformPointer, UBiDiTransform, ubiditransform_close);

U_NAMESPACE_END

#endif

#endif


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
*
*   Copyright (C) 1997-2012, International Business Machines
*   Corporation and others.  All Rights Reserved.
*
******************************************************************************
*
*  FILE NAME : ptypes.h
*
*   Date        Name        Description
*   05/13/98    nos         Creation (content moved here from ptypes.h).
*   03/02/99    stephen     Added AS400 support.
*   03/30/99    stephen     Added Linux support.
*   04/13/99    stephen     Reworked for autoconf.
*   09/18/08    srl         Moved basic types back to ptypes.h from platform.h
******************************************************************************
*/

/**
 * \file
 * \brief C API: Definitions of integer types of various widths
 */

#ifndef _PTYPES_H
#define _PTYPES_H

/**
 * \def __STDC_LIMIT_MACROS
 * According to the Linux stdint.h, the ISO C99 standard specifies that in C++ implementations
 * macros like INT32_MIN and UINTPTR_MAX should only be defined if explicitly requested.
 * We need to define __STDC_LIMIT_MACROS before including stdint.h in C++ code
 * that uses such limit macros.
 * @internal
 */
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif

/* NULL, size_t, wchar_t */
#include <stddef.h>

/*
 * If all compilers provided all of the C99 headers and types,
 * we would just unconditionally #include <stdint.h> here
 * and not need any of the stuff after including platform.h.
 */

/* Find out if we have stdint.h etc. */
#include "unicode/platform.h"

/*===========================================================================*/
/* Generic data types                                                        */
/*===========================================================================*/

/* If your platform does not have the <stdint.h> header, you may
   need to edit the typedefs in the #else section below.
   Use #if...#else...#endif with predefined compiler macros if possible. */
#if U_HAVE_STDINT_H

/*
 * We mostly need <stdint.h> (which defines the standard integer types) but not <inttypes.h>.
 * <inttypes.h> includes <stdint.h> and adds the printf/scanf helpers PRId32, SCNx16 etc.
 * which we almost never use, plus stuff like imaxabs() which we never use.
 */
#include <stdint.h>

#if U_PLATFORM == U_PF_OS390
/* The features header is needed to get (u)int64_t sometimes. */
#include <features.h>
/* z/OS has <stdint.h>, but some versions are missing uint8_t (APAR PK62248). */
#if !defined(__uint8_t)
#define __uint8_t 1
typedef unsigned char uint8_t;
#endif
#endif /* U_PLATFORM == U_PF_OS390 */

#elif U_HAVE_INTTYPES_H

#   include <inttypes.h>

#else /* neither U_HAVE_STDINT_H nor U_HAVE_INTTYPES_H */

/// \cond
#if ! U_HAVE_INT8_T
typedef signed char int8_t;
#endif

#if ! U_HAVE_UINT8_T
typedef unsigned char uint8_t;
#endif

#if ! U_HAVE_INT16_T
typedef signed short int16_t;
#endif

#if ! U_HAVE_UINT16_T
typedef unsigned short uint16_t;
#endif

#if ! U_HAVE_INT32_T
typedef signed int int32_t;
#endif

#if ! U_HAVE_UINT32_T
typedef unsigned int uint32_t;
#endif

#if ! U_HAVE_INT64_T
#ifdef _MSC_VER
    typedef signed __int64 int64_t;
#else
    typedef signed long long int64_t;
#endif
#endif

#if ! U_HAVE_UINT64_T
#ifdef _MSC_VER
    typedef unsigned __int64 uint64_t;
#else
    typedef unsigned long long uint64_t;
#endif
#endif
/// \endcond

#endif /* U_HAVE_STDINT_H / U_HAVE_INTTYPES_H */

#endif /* _PTYPES_H */


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
*   Copyright (C) 2004-2012, International Business Machines
*   Corporation and others.  All Rights Reserved.
*
*******************************************************************************
*   file name:  utext.h
*   encoding:   UTF-8
*   tab size:   8 (not used)
*   indentation:4
*
*   created on: 2004oct06
*   created by: Markus W. Scherer
*/

#ifndef __UTEXT_H__
#define __UTEXT_H__

/**
 * \file
 * \brief C API: Abstract Unicode Text API
 *
 * The Text Access API provides a means to allow text that is stored in alternative
 * formats to work with ICU services.  ICU normally operates on text that is
 * stored in UTF-16 format, in (UChar *) arrays for the C APIs or as type
 * UnicodeString for C++ APIs.
 *
 * ICU Text Access allows other formats, such as UTF-8 or non-contiguous
 * UTF-16 strings, to be placed in a UText wrapper and then passed to ICU services.
 *
 * There are three general classes of usage for UText:
 *
 *     Application Level Use.  This is the simplest usage - applications would
 *     use one of the utext_open() functions on their input text, and pass
 *     the resulting UText to the desired ICU service.
 *
 *     Second is usage in ICU Services, such as break iteration, that will need to
 *     operate on input presented to them as a UText.  These implementations
 *     will need to use the iteration and related UText functions to gain
 *     access to the actual text.
 *
 *     The third class of UText users are "text providers."  These are the
 *     UText implementations for the various text storage formats.  An application
 *     or system with a unique text storage format can implement a set of
 *     UText provider functions for that format, which will then allow
 *     ICU services to operate on that format.
 *
 *
 * Iterating over text
 *
 * Here is sample code for a forward iteration over the contents of a UText
 *
 * \code
 *    UChar32  c;
 *    UText    *ut = whatever();
 *
 *    for (c=utext_next32From(ut, 0); c>=0; c=utext_next32(ut)) {
 *       // do whatever with the codepoint c here.
 *    }
 * \endcode
 *
 * And here is similar code to iterate in the reverse direction, from the end
 * of the text towards the beginning.
 *
 * \code
 *    UChar32  c;
 *    UText    *ut = whatever();
 *    int      textLength = utext_nativeLength(ut);
 *    for (c=utext_previous32From(ut, textLength); c>=0; c=utext_previous32(ut)) {
 *       // do whatever with the codepoint c here.
 *    }
 * \endcode
 *
 * Characters and Indexing
 *
 * Indexing into text by UText functions is nearly always in terms of the native
 * indexing of the underlying text storage.  The storage format could be UTF-8
 * or UTF-32, for example.  When coding to the UText access API, no assumptions
 * can be made regarding the size of characters, or how far an index
 * may move when iterating between characters.
 *
 * All indices supplied to UText functions are pinned to the length of the
 * text.  An out-of-bounds index is not considered to be an error, but is
 * adjusted to be in the range  0 <= index <= length of input text.
 *
 *
 * When an index position is returned from a UText function, it will be
 * a native index to the underlying text.  In the case of multi-unit characters,
 * it will  always refer to the first position of the character,
 * never to the interior.  This is essentially the same thing as saying that
 * a returned index will always point to a boundary between characters.
 *
 * When a native index is supplied to a UText function, all indices that
 * refer to any part of a multi-unit character representation are considered
 * to be equivalent.  In the case of multi-unit characters, an incoming index
 * will be logically normalized to refer to the start of the character.
 *
 * It is possible to test whether a native index is on a code point boundary
 * by doing a utext_setNativeIndex() followed by a utext_getNativeIndex().
 * If the index is returned unchanged, it was on a code point boundary.  If
 * an adjusted index is returned, the original index referred to the
 * interior of a character.
 *
 * Conventions for calling UText functions
 *
 * Most UText access functions have as their first parameter a (UText *) pointer,
 * which specifies the UText to be used.  Unless otherwise noted, the
 * pointer must refer to a valid, open UText.  Attempting to
 * use a closed UText or passing a NULL pointer is a programming error and
 * will produce undefined results or NULL pointer exceptions.
 *
 * The UText_Open family of functions can either open an existing (closed)
 * UText, or heap allocate a new UText.  Here is sample code for creating
 * a stack-allocated UText.
 *
 * \code
 *    char     *s = whatever();  // A utf-8 string
 *    U_ErrorCode status = U_ZERO_ERROR;
 *    UText    ut = UTEXT_INITIALIZER;
 *    utext_openUTF8(ut, s, -1, &status);
 *    if (U_FAILURE(status)) {
 *        // error handling
 *    } else {
 *        // work with the UText
 *    }
 * \endcode
 *
 * Any existing UText passed to an open function _must_ have been initialized,
 * either by the UTEXT_INITIALIZER, or by having been originally heap-allocated
 * by an open function.  Passing NULL will cause the open function to
 * heap-allocate and fully initialize a new UText.
 *
 */

#include "unicode/utypes.h"
#include "unicode/uchar.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#include "unicode/rep.h"
#include "unicode/unistr.h"
#include "unicode/chariter.h"
#endif

U_CDECL_BEGIN

struct UText;
typedef struct UText UText; /**< C typedef for struct UText. @stable ICU 3.6 */

/***************************************************************************************
 *
 *   C Functions for creating UText wrappers around various kinds of text strings.
 *
 ****************************************************************************************/

/**
  * Close function for UText instances.
  * Cleans up, releases any resources being held by an open UText.
  *

  *   If the UText was originally allocated by one of the utext_open functions,
  *   the storage associated with the utext will also be freed.
  *   If the UText storage originated with the application, as it would with
  *   a local or static instance, the storage will not be deleted.
  *
  *   An open UText can be reset to refer to new string by using one of the utext_open()
  *   functions without first closing the UText.
  *
  * @param ut  The UText to be closed.
  * @return    NULL if the UText struct was deleted by the close.  If the UText struct
  *            was originally provided by the caller to the open function, it is
  *            returned by this function, and may be safely used again in
  *            a subsequent utext_open.
  *
  * @stable ICU 3.4
  */
U_STABLE UText * U_EXPORT2
utext_close(UText *ut);

/**
 * Open a read-only UText implementation for UTF-8 strings.
 *
 * \htmlonly
 * Any invalid UTF-8 in the input will be handled in this way:
 * a sequence of bytes that has the form of a truncated, but otherwise valid,
 * UTF-8 sequence will be replaced by a single unicode replacement character, \uFFFD.
 * Any other illegal bytes will each be replaced by a \uFFFD.
 * \endhtmlonly
 *
 * @param ut     Pointer to a UText struct.  If NULL, a new UText will be created.
 *               If non-NULL, must refer to an initialized UText struct, which will then
 *               be reset to reference the specified UTF-8 string.
 * @param s      A UTF-8 string.  Must not be NULL.
 * @param length The length of the UTF-8 string in bytes, or -1 if the string is
 *               zero terminated.
 * @param status Errors are returned here.
 * @return       A pointer to the UText.  If a pre-allocated UText was provided, it
 *               will always be used and returned.
 * @stable ICU 3.4
 */
U_STABLE UText * U_EXPORT2
utext_openUTF8(UText *ut, const char *s, int64_t length, UErrorCode *status);

/**
 * Open a read-only UText for UChar * string.
 *
 * @param ut     Pointer to a UText struct.  If NULL, a new UText will be created.
 *               If non-NULL, must refer to an initialized UText struct, which will then
 *               be reset to reference the specified UChar string.
 * @param s      A UChar (UTF-16) string
 * @param length The number of UChars in the input string, or -1 if the string is
 *               zero terminated.
 * @param status Errors are returned here.
 * @return       A pointer to the UText.  If a pre-allocated UText was provided, it
 *               will always be used and returned.
 * @stable ICU 3.4
 */
U_STABLE UText * U_EXPORT2
utext_openUChars(UText *ut, const UChar *s, int64_t length, UErrorCode *status);

#if U_SHOW_CPLUSPLUS_API
/**
 * Open a writable UText for a non-const UnicodeString.
 *
 * @param ut      Pointer to a UText struct.  If NULL, a new UText will be created.
 *                 If non-NULL, must refer to an initialized UText struct, which will then
 *                 be reset to reference the specified input string.
 * @param s       A UnicodeString.
 * @param status Errors are returned here.
 * @return        Pointer to the UText.  If a UText was supplied as input, this
 *                 will always be used and returned.
 * @stable ICU 3.4
 */
U_STABLE UText * U_EXPORT2
utext_openUnicodeString(UText *ut, icu::UnicodeString *s, UErrorCode *status);

/**
 * Open a UText for a const UnicodeString.   The resulting UText will not be writable.
 *
 * @param ut    Pointer to a UText struct.  If NULL, a new UText will be created.
 *               If non-NULL, must refer to an initialized UText struct, which will then
 *               be reset to reference the specified input string.
 * @param s      A const UnicodeString to be wrapped.
 * @param status Errors are returned here.
 * @return       Pointer to the UText.  If a UText was supplied as input, this
 *               will always be used and returned.
 * @stable ICU 3.4
 */
U_STABLE UText * U_EXPORT2
utext_openConstUnicodeString(UText *ut, const icu::UnicodeString *s, UErrorCode *status);

/**
 * Open a writable UText implementation for an ICU Replaceable object.
 * @param ut    Pointer to a UText struct.  If NULL, a new UText will be created.
 *               If non-NULL, must refer to an already existing UText, which will then
 *               be reset to reference the specified replaceable text.
 * @param rep    A Replaceable text object.
 * @param status Errors are returned here.
 * @return       Pointer to the UText.  If a UText was supplied as input, this
 *               will always be used and returned.
 * @see Replaceable
 * @stable ICU 3.4
 */
U_STABLE UText * U_EXPORT2
utext_openReplaceable(UText *ut, icu::Replaceable *rep, UErrorCode *status);

/**
 * Open a  UText implementation over an ICU CharacterIterator.
 * @param ut    Pointer to a UText struct.  If NULL, a new UText will be created.
 *               If non-NULL, must refer to an already existing UText, which will then
 *               be reset to reference the specified replaceable text.
 * @param ci     A Character Iterator.
 * @param status Errors are returned here.
 * @return       Pointer to the UText.  If a UText was supplied as input, this
 *               will always be used and returned.
 * @see Replaceable
 * @stable ICU 3.4
 */
U_STABLE UText * U_EXPORT2
utext_openCharacterIterator(UText *ut, icu::CharacterIterator *ci, UErrorCode *status);

#endif

/**
  *  Clone a UText.  This is much like opening a UText where the source text is itself
  *  another UText.
  *
  *  A deep clone will copy both the UText data structures and the underlying text.
  *  The original and cloned UText will operate completely independently; modifications
  *  made to the text in one will not affect the other.  Text providers are not
  *  required to support deep clones.  The user of clone() must check the status return
  *  and be prepared to handle failures.
  *
  *  The standard UText implementations for UTF8, UChar *, UnicodeString and
  *  Replaceable all support deep cloning.
  *
  *  The UText returned from a deep clone will be writable, assuming that the text
  *  provider is able to support writing, even if the source UText had been made
  *  non-writable by means of UText_freeze().
  *
  *  A shallow clone replicates only the UText data structures; it does not make
  *  a copy of the underlying text.  Shallow clones can be used as an efficient way to
  *  have multiple iterators active in a single text string that is not being
  *  modified.
  *
  *  A shallow clone operation will not fail, barring truly exceptional conditions such
  *  as memory allocation failures.
  *
  *  Shallow UText clones should be avoided if the UText functions that modify the
  *  text are expected to be used, either on the original or the cloned UText.
  *  Any such modifications  can cause unpredictable behavior.  Read Only
  *  shallow clones provide some protection against errors of this type by
  *  disabling text modification via the cloned UText.
  *
  *  A shallow clone made with the readOnly parameter == FALSE will preserve the
  *  utext_isWritable() state of the source object.  Note, however, that
  *  write operations must be avoided while more than one UText exists that refer
  *  to the same underlying text.
  *
  *  A UText and its clone may be safely concurrently accessed by separate threads.
  *  This is true for read access only with shallow clones, and for both read and
  *  write access with deep clones.
  *  It is the responsibility of the Text Provider to ensure that this thread safety
  *  constraint is met.
  *
  *  @param dest   A UText struct to be filled in with the result of the clone operation,
  *                or NULL if the clone function should heap-allocate a new UText struct.
  *                If non-NULL, must refer to an already existing UText, which will then
  *                be reset to become the clone.
  *  @param src    The UText to be cloned.
  *  @param deep   TRUE to request a deep clone, FALSE for a shallow clone.
  *  @param readOnly TRUE to request that the cloned UText have read only access to the
  *                underlying text.

  *  @param status Errors are returned here.  For deep clones, U_UNSUPPORTED_ERROR
  *                will be returned if the text provider is unable to clone the
  *                original text.
  *  @return       The newly created clone, or NULL if the clone operation failed.
  *  @stable ICU 3.4
  */
U_STABLE UText * U_EXPORT2
utext_clone(UText *dest, const UText *src, UBool deep, UBool readOnly, UErrorCode *status);

/**
  *  Compare two UText objects for equality.
  *  UTexts are equal if they are iterating over the same text, and
  *    have the same iteration position within the text.
  *    If either or both of the parameters are NULL, the comparison is FALSE.
  *
  *  @param a   The first of the two UTexts to compare.
  *  @param b   The other UText to be compared.
  *  @return    TRUE if the two UTexts are equal.
  *  @stable ICU 3.6
  */
U_STABLE UBool U_EXPORT2
utext_equals(const UText *a, const UText *b);

/*****************************************************************************
 *
 *   Functions to work with the text represented by a UText wrapper
 *
 *****************************************************************************/

/**
  * Get the length of the text.  Depending on the characteristics
  * of the underlying text representation, this may be expensive.
  * @see  utext_isLengthExpensive()
  *
  *
  * @param ut  the text to be accessed.
  * @return the length of the text, expressed in native units.
  *
  * @stable ICU 3.4
  */
U_STABLE int64_t U_EXPORT2
utext_nativeLength(UText *ut);

/**
 *  Return TRUE if calculating the length of the text could be expensive.
 *  Finding the length of NUL terminated strings is considered to be expensive.
 *
 *  Note that the value of this function may change
 *  as the result of other operations on a UText.
 *  Once the length of a string has been discovered, it will no longer
 *  be expensive to report it.
 *
 * @param ut the text to be accessed.
 * @return TRUE if determining the length of the text could be time consuming.
 * @stable ICU 3.4
 */
U_STABLE UBool U_EXPORT2
utext_isLengthExpensive(const UText *ut);

/**
 * Returns the code point at the requested index,
 * or U_SENTINEL (-1) if it is out of bounds.
 *
 * If the specified index points to the interior of a multi-unit
 * character - one of the trail bytes of a UTF-8 sequence, for example -
 * the complete code point will be returned.
 *
 * The iteration position will be set to the start of the returned code point.
 *
 * This function is roughly equivalent to the sequence
 *    utext_setNativeIndex(index);
 *    utext_current32();
 * (There is a subtle difference if the index is out of bounds by being less than zero -
 * utext_setNativeIndex(negative value) sets the index to zero, after which utext_current()
 * will return the char at zero.  utext_char32At(negative index), on the other hand, will
 * return the U_SENTINEL value of -1.)
 *
 * @param ut the text to be accessed
 * @param nativeIndex the native index of the character to be accessed.  If the index points
 *        to other than the first unit of a multi-unit character, it will be adjusted
 *        to the start of the character.
 * @return the code point at the specified index.
 * @stable ICU 3.4
 */
U_STABLE UChar32 U_EXPORT2
utext_char32At(UText *ut, int64_t nativeIndex);

/**
 *
 * Get the code point at the current iteration position,
 * or U_SENTINEL (-1) if the iteration has reached the end of
 * the input text.
 *
 * @param ut the text to be accessed.
 * @return the Unicode code point at the current iterator position.
 * @stable ICU 3.4
 */
U_STABLE UChar32 U_EXPORT2
utext_current32(UText *ut);

/**
 * Get the code point at the current iteration position of the UText, and
 * advance the position to the first index following the character.
 *
 * If the position is at the end of the text (the index following
 * the last character, which is also the length of the text),
 * return U_SENTINEL (-1) and do not advance the index.
 *
 * This is a post-increment operation.
 *
 * An inline macro version of this function, UTEXT_NEXT32(),
 * is available for performance critical use.
 *
 * @param ut the text to be accessed.
 * @return the Unicode code point at the iteration position.
 * @see UTEXT_NEXT32
 * @stable ICU 3.4
 */
U_STABLE UChar32 U_EXPORT2
utext_next32(UText *ut);

/**
 *  Move the iterator position to the character (code point) whose
 *  index precedes the current position, and return that character.
 *  This is a pre-decrement operation.
 *
 *  If the initial position is at the start of the text (index of 0)
 *  return U_SENTINEL (-1), and leave the position unchanged.
 *
 *  An inline macro version of this function, UTEXT_PREVIOUS32(),
 *  is available for performance critical use.
 *
 *  @param ut the text to be accessed.
 *  @return the previous UChar32 code point, or U_SENTINEL (-1)
 *          if the iteration has reached the start of the text.
 *  @see UTEXT_PREVIOUS32
 *  @stable ICU 3.4
 */
U_STABLE UChar32 U_EXPORT2
utext_previous32(UText *ut);

/**
  * Set the iteration index and return the code point at that index.
  * Leave the iteration index at the start of the following code point.
  *
  * This function is the most efficient and convenient way to
  * begin a forward iteration.  The results are identical to the those
  * from the sequence
  * \code
  *    utext_setIndex();
  *    utext_next32();
  * \endcode
  *
  *  @param ut the text to be accessed.
  *  @param nativeIndex Iteration index, in the native units of the text provider.
  *  @return Code point which starts at or before index,
  *         or U_SENTINEL (-1) if it is out of bounds.
  * @stable ICU 3.4
  */
U_STABLE UChar32 U_EXPORT2
utext_next32From(UText *ut, int64_t nativeIndex);

/**
  * Set the iteration index, and return the code point preceding the
  * one specified by the initial index.  Leave the iteration position
  * at the start of the returned code point.
  *
  * This function is the most efficient and convenient way to
  * begin a backwards iteration.
  *
  * @param ut the text to be accessed.
  * @param nativeIndex Iteration index in the native units of the text provider.
  * @return Code point preceding the one at the initial index,
  *         or U_SENTINEL (-1) if it is out of bounds.
  *
  * @stable ICU 3.4
  */
U_STABLE UChar32 U_EXPORT2
utext_previous32From(UText *ut, int64_t nativeIndex);

/**
  * Get the current iterator position, which can range from 0 to
  * the length of the text.
  * The position is a native index into the input text, in whatever format it
  * may have (possibly UTF-8 for example), and may not always be the same as
  * the corresponding UChar (UTF-16) index.
  * The returned position will always be aligned to a code point boundary.
  *
  * @param ut the text to be accessed.
  * @return the current index position, in the native units of the text provider.
  * @stable ICU 3.4
  */
U_STABLE int64_t U_EXPORT2
utext_getNativeIndex(const UText *ut);

/**
 * Set the current iteration position to the nearest code point
 * boundary at or preceding the specified index.
 * The index is in the native units of the original input text.
 * If the index is out of range, it will be pinned to be within
 * the range of the input text.
 *

 * It will usually be more efficient to begin an iteration
 * using the functions utext_next32From() or utext_previous32From()
 * rather than setIndex().
 *

 * Moving the index position to an adjacent character is best done
 * with utext_next32(), utext_previous32() or utext_moveIndex32().
 * Attempting to do direct arithmetic on the index position is
 * complicated by the fact that the size (in native units) of a
 * character depends on the underlying representation of the character
 * (UTF-8, UTF-16, UTF-32, arbitrary codepage), and is not
 * easily knowable.
 *
 * @param ut the text to be accessed.
 * @param nativeIndex the native unit index of the new iteration position.
 * @stable ICU 3.4
 */
U_STABLE void U_EXPORT2
utext_setNativeIndex(UText *ut, int64_t nativeIndex);

/**
 * Move the iterator position by delta code points.  The number of code points
 * is a signed number; a negative delta will move the iterator backwards,
 * towards the start of the text.
 *

 * The index is moved by delta code points
 * forward or backward, but no further backward than to 0 and
 * no further forward than to utext_nativeLength().
 * The resulting index value will be in between 0 and length, inclusive.
 *
 * @param ut the text to be accessed.
 * @param delta the signed number of code points to move the iteration position.
 * @return TRUE if the position could be moved the requested number of positions while
 *              staying within the range [0 - text length].
 * @stable ICU 3.4
 */
U_STABLE UBool U_EXPORT2
utext_moveIndex32(UText *ut, int32_t delta);

/**
 * Get the native index of the character preceding the current position.
 * If the iteration position is already at the start of the text, zero
 * is returned.
 * The value returned is the same as that obtained from the following sequence,
 * but without the side effect of changing the iteration position.
 *
 * \code
 *    UText  *ut = whatever;
 *      ...
 *    utext_previous(ut)
 *    utext_getNativeIndex(ut);
 * \endcode
 *
 * This function is most useful during forwards iteration, where it will get the
 *   native index of the character most recently returned from utext_next().
 *
 * @param ut the text to be accessed
 * @return the native index of the character preceding the current index position,
 *         or zero if the current position is at the start of the text.
 * @stable ICU 3.6
 */
U_STABLE int64_t U_EXPORT2
utext_getPreviousNativeIndex(UText *ut);

/**
 *
 * Extract text from a UText into a UChar buffer.  The range of text to be extracted
 * is specified in the native indices of the UText provider.  These may not necessarily
 * be UTF-16 indices.
 *

 * The size (number of 16 bit UChars) of the data to be extracted is returned.  The
 * full number of UChars is returned, even when the extracted text is truncated
 * because the specified buffer size is too small.
 *

 * The extracted string will (if you are a user) / must (if you are a text provider)
 * be NUL-terminated if there is sufficient space in the destination buffer.  This
 * terminating NUL is not included in the returned length.
 *

 * The iteration index is left at the position following the last extracted character.
 *
 * @param  ut    the UText from which to extract data.
 * @param  nativeStart the native index of the first character to extract.\
 *               If the specified index is out of range,
 *               it will be pinned to be within 0 <= index <= textLength
 * @param  nativeLimit the native string index of the position following the last
 *               character to extract.  If the specified index is out of range,
 *               it will be pinned to be within 0 <= index <= textLength.
 *               nativeLimit must be >= nativeStart.
 * @param  dest  the UChar (UTF-16) buffer into which the extracted text is placed
 * @param  destCapacity  The size, in UChars, of the destination buffer.  May be zero
 *               for precomputing the required size.
 * @param  status receives any error status.
 *         U_BUFFER_OVERFLOW_ERROR: the extracted text was truncated because the
 *         buffer was too small.  Returns number of UChars for preflighting.
 * @return Number of UChars in the data to be extracted.  Does not include a trailing NUL.
 *
 * @stable ICU 3.4
 */
U_STABLE int32_t U_EXPORT2
utext_extract(UText *ut,
             int64_t nativeStart, int64_t nativeLimit,
             UChar *dest, int32_t destCapacity,
             UErrorCode *status);

/************************************************************************************
 *
 *  #define inline versions of selected performance-critical text access functions
 *          Caution:  do not use auto increment++ or decrement-- expressions
 *                    as parameters to these macros.
 *
 *          For most use, where there is no extreme performance constraint, the
 *          normal, non-inline functions are a better choice.  The resulting code
 *          will be smaller, and, if the need ever arises, easier to debug.
 *
 *          These are implemented as #defines rather than real functions
 *          because there is no fully portable way to do inline functions in plain C.
 *
 ************************************************************************************/

#ifndef U_HIDE_INTERNAL_API
/**
 * inline version of utext_current32(), for performance-critical situations.
 *
 * Get the code point at the current iteration position of the UText.
 * Returns U_SENTINEL (-1) if the position is at the end of the
 * text.
 *
 * @internal ICU 4.4 technology preview
 */
#define UTEXT_CURRENT32(ut)  \
    ((ut)->chunkOffset < (ut)->chunkLength && ((ut)->chunkContents)[(ut)->chunkOffset]<0xd800 ? \
    ((ut)->chunkContents)[((ut)->chunkOffset)] : utext_current32(ut))
#endif  /* U_HIDE_INTERNAL_API */

/**
 * inline version of utext_next32(), for performance-critical situations.
 *
 * Get the code point at the current iteration position of the UText, and
 * advance the position to the first index following the character.
 * This is a post-increment operation.
 * Returns U_SENTINEL (-1) if the position is at the end of the
 * text.
 *
 * @stable ICU 3.4
 */
#define UTEXT_NEXT32(ut)  \
    ((ut)->chunkOffset < (ut)->chunkLength && ((ut)->chunkContents)[(ut)->chunkOffset]<0xd800 ? \
    ((ut)->chunkContents)[((ut)->chunkOffset)++] : utext_next32(ut))

/**
 * inline version of utext_previous32(), for performance-critical situations.
 *
 *  Move the iterator position to the character (code point) whose
 *  index precedes the current position, and return that character.
 *  This is a pre-decrement operation.
 *  Returns U_SENTINEL (-1) if the position is at the start of the  text.
 *
 * @stable ICU 3.4
 */
#define UTEXT_PREVIOUS32(ut)  \
    ((ut)->chunkOffset > 0 && \
     (ut)->chunkContents[(ut)->chunkOffset-1] < 0xd800 ? \
          (ut)->chunkContents[--((ut)->chunkOffset)]  :  utext_previous32(ut))

/**
  *  inline version of utext_getNativeIndex(), for performance-critical situations.
  *
  * Get the current iterator position, which can range from 0 to
  * the length of the text.
  * The position is a native index into the input text, in whatever format it
  * may have (possibly UTF-8 for example), and may not always be the same as
  * the corresponding UChar (UTF-16) index.
  * The returned position will always be aligned to a code point boundary.
  *
  * @stable ICU 3.6
  */
#define UTEXT_GETNATIVEINDEX(ut)                       \
    ((ut)->chunkOffset <= (ut)->nativeIndexingLimit?   \
        (ut)->chunkNativeStart+(ut)->chunkOffset :     \
        (ut)->pFuncs->mapOffsetToNative(ut))

/**
  *  inline version of utext_setNativeIndex(), for performance-critical situations.
  *
  * Set the current iteration position to the nearest code point
  * boundary at or preceding the specified index.
  * The index is in the native units of the original input text.
  * If the index is out of range, it will be pinned to be within
  * the range of the input text.
  *
  * @stable ICU 3.8
  */
#define UTEXT_SETNATIVEINDEX(ut, ix) UPRV_BLOCK_MACRO_BEGIN { \
    int64_t __offset = (ix) - (ut)->chunkNativeStart; \
    if (__offset>=0 && __offset<(int64_t)(ut)->nativeIndexingLimit && (ut)->chunkContents[__offset]<0xdc00) { \
        (ut)->chunkOffset=(int32_t)__offset; \
    } else { \
        utext_setNativeIndex((ut), (ix)); \
    } \
} UPRV_BLOCK_MACRO_END

/************************************************************************************
 *
 *   Functions related to writing or modifying the text.
 *   These will work only with modifiable UTexts.  Attempting to
 *   modify a read-only UText will return an error status.
 *
 ************************************************************************************/

/**
 *  Return TRUE if the text can be written (modified) with utext_replace() or
 *  utext_copy().  For the text to be writable, the text provider must
 *  be of a type that supports writing and the UText must not be frozen.
 *
 *  Attempting to modify text when utext_isWriteable() is FALSE will fail -
 *  the text will not be modified, and an error will be returned from the function
 *  that attempted the modification.
 *
 * @param  ut   the UText to be tested.
 * @return TRUE if the text is modifiable.
 *
 * @see    utext_freeze()
 * @see    utext_replace()
 * @see    utext_copy()
 * @stable ICU 3.4
 *
 */
U_STABLE UBool U_EXPORT2
utext_isWritable(const UText *ut);

/**
  * Test whether there is meta data associated with the text.
  * @see Replaceable::hasMetaData()
  *
  * @param ut The UText to be tested
  * @return TRUE if the underlying text includes meta data.
  * @stable ICU 3.4
  */
U_STABLE UBool U_EXPORT2
utext_hasMetaData(const UText *ut);

/**
 * Replace a range of the original text with a replacement text.
 *
 * Leaves the current iteration position at the position following the
 *  newly inserted replacement text.
 *
 * This function is only available on UText types that support writing,
 * that is, ones where utext_isWritable() returns TRUE.
 *
 * When using this function, there should be only a single UText opened onto the
 * underlying native text string.  Behavior after a replace operation
 * on a UText is undefined for any other additional UTexts that refer to the
 * modified string.
 *
 * @param ut               the UText representing the text to be operated on.
 * @param nativeStart      the native index of the start of the region to be replaced
 * @param nativeLimit      the native index of the character following the region to be replaced.
 * @param replacementText  pointer to the replacement text
 * @param replacementLength length of the replacement text, or -1 if the text is NUL terminated.
 * @param status           receives any error status.  Possible errors include
 *                         U_NO_WRITE_PERMISSION
 *
 * @return The signed number of (native) storage units by which
 *         the length of the text expanded or contracted.
 *
 * @stable ICU 3.4
 */
U_STABLE int32_t U_EXPORT2
utext_replace(UText *ut,
             int64_t nativeStart, int64_t nativeLimit,
             const UChar *replacementText, int32_t replacementLength,
             UErrorCode *status);

/**
 *
 * Copy or move a substring from one position to another within the text,
 * while retaining any metadata associated with the text.
 * This function is used to duplicate or reorder substrings.
 * The destination index must not overlap the source range.
 *
 * The text to be copied or moved is inserted at destIndex;
 * it does not replace or overwrite any existing text.
 *
 * The iteration position is left following the newly inserted text
 * at the destination position.
 *
 * This function is only available on UText types that support writing,
 * that is, ones where utext_isWritable() returns TRUE.
 *
 * When using this function, there should be only a single UText opened onto the
 * underlying native text string.  Behavior after a copy operation
 * on a UText is undefined in any other additional UTexts that refer to the
 * modified string.
 *
 * @param ut           The UText representing the text to be operated on.
 * @param nativeStart  The native index of the start of the region to be copied or moved
 * @param nativeLimit  The native index of the character position following the region
 *                     to be copied.
 * @param destIndex    The native destination index to which the source substring is
 *                     copied or moved.
 * @param move         If TRUE, then the substring is moved, not copied/duplicated.
 * @param status       receives any error status.  Possible errors include U_NO_WRITE_PERMISSION
 *
 * @stable ICU 3.4
 */
U_STABLE void U_EXPORT2
utext_copy(UText *ut,
          int64_t nativeStart, int64_t nativeLimit,
          int64_t destIndex,
          UBool move,
          UErrorCode *status);

/**
  *

  *  Freeze a UText.  This prevents any modification to the underlying text itself
  *  by means of functions operating on this UText.
  *

  *

  *  Once frozen, a UText can not be unfrozen.  The intent is to ensure
  *  that a the text underlying a frozen UText wrapper cannot be modified via that UText.
  *

  *

  *  Caution:  freezing a UText will disable changes made via the specific
  *   frozen UText wrapper only; it will not have any effect on the ability to
  *   directly modify the text by bypassing the UText.  Any such backdoor modifications
  *   are always an error while UText access is occurring because the underlying
  *   text can get out of sync with UText's buffering.
  *

  *
  *  @param ut  The UText to be frozen.
  *  @see   utext_isWritable()
  *  @stable ICU 3.6
  */
U_STABLE void U_EXPORT2
utext_freeze(UText *ut);

/**
 * UText provider properties (bit field indexes).
 *
 * @see UText
 * @stable ICU 3.4
 */
enum {
    /**
     * It is potentially time consuming for the provider to determine the length of the text.
     * @stable ICU 3.4
     */
    UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE = 1,
    /**
     * Text chunks remain valid and usable until the text object is modified or
     * deleted, not just until the next time the access() function is called
     * (which is the default).
     * @stable ICU 3.4
     */
    UTEXT_PROVIDER_STABLE_CHUNKS = 2,
    /**
     * The provider supports modifying the text via the replace() and copy()
     * functions.
     * @see Replaceable
     * @stable ICU 3.4
     */
    UTEXT_PROVIDER_WRITABLE = 3,
    /**
     * There is meta data associated with the text.
     * @see Replaceable::hasMetaData()
     * @stable ICU 3.4
     */
    UTEXT_PROVIDER_HAS_META_DATA = 4,
    /**
     * Text provider owns the text storage.
     *  Generally occurs as the result of a deep clone of the UText.
     *  When closing the UText, the associated text must
     *  also be closed/deleted/freed/ whatever is appropriate.
     * @stable ICU 3.6
     */
     UTEXT_PROVIDER_OWNS_TEXT = 5
};

/**
  * Function type declaration for UText.clone().
  *
  *  clone a UText.  Much like opening a UText where the source text is itself
  *  another UText.
  *
  *  A deep clone will copy both the UText data structures and the underlying text.
  *  The original and cloned UText will operate completely independently; modifications
  *  made to the text in one will not effect the other.  Text providers are not
  *  required to support deep clones.  The user of clone() must check the status return
  *  and be prepared to handle failures.
  *
  *  A shallow clone replicates only the UText data structures; it does not make
  *  a copy of the underlying text.  Shallow clones can be used as an efficient way to
  *  have multiple iterators active in a single text string that is not being
  *  modified.
  *
  *  A shallow clone operation must not fail except for truly exceptional conditions such
  *  as memory allocation failures.
  *
  *  A UText and its clone may be safely concurrently accessed by separate threads.
  *  This is true for both shallow and deep clones.
  *  It is the responsibility of the Text Provider to ensure that this thread safety
  *  constraint is met.

  *
  *  @param dest   A UText struct to be filled in with the result of the clone operation,
  *                or NULL if the clone function should heap-allocate a new UText struct.
  *  @param src    The UText to be cloned.
  *  @param deep   TRUE to request a deep clone, FALSE for a shallow clone.
  *  @param status Errors are returned here.  For deep clones, U_UNSUPPORTED_ERROR
  *                should be returned if the text provider is unable to clone the
  *                original text.
  *  @return       The newly created clone, or NULL if the clone operation failed.
  *
  * @stable ICU 3.4
  */
typedef UText * U_CALLCONV
UTextClone(UText *dest, const UText *src, UBool deep, UErrorCode *status);

/**
 * Function type declaration for UText.nativeLength().
 *
 * @param ut the UText to get the length of.
 * @return the length, in the native units of the original text string.
 * @see UText
 * @stable ICU 3.4
 */
typedef int64_t U_CALLCONV
UTextNativeLength(UText *ut);

/**
 * Function type declaration for UText.access().  Get the description of the text chunk
 *  containing the text at a requested native index.  The UText's iteration
 *  position will be left at the requested index.  If the index is out
 *  of bounds, the iteration position will be left at the start or end
 *  of the string, as appropriate.
 *
 *  Chunks must begin and end on code point boundaries.  A single code point
 *  comprised of multiple storage units must never span a chunk boundary.
 *
 *
 * @param ut          the UText being accessed.
 * @param nativeIndex Requested index of the text to be accessed.
 * @param forward     If TRUE, then the returned chunk must contain text
 *                    starting from the index, so that start<=index<limit.
 *                    If FALSE, then the returned chunk must contain text
 *                    before the index, so that start<index<=limit.
 * @return            True if the requested index could be accessed.  The chunk
 *                    will contain the requested text.
 *                    False value if a chunk cannot be accessed
 *                    (the requested index is out of bounds).
 *
 * @see UText
 * @stable ICU 3.4
 */
typedef UBool U_CALLCONV
UTextAccess(UText *ut, int64_t nativeIndex, UBool forward);

/**
 * Function type declaration for UText.extract().
 *
 * Extract text from a UText into a UChar buffer.  The range of text to be extracted
 * is specified in the native indices of the UText provider.  These may not necessarily
 * be UTF-16 indices.
 *

 * The size (number of 16 bit UChars) in the data to be extracted is returned.  The
 * full amount is returned, even when the specified buffer size is smaller.
 *

 * The extracted string will (if you are a user) / must (if you are a text provider)
 * be NUL-terminated if there is sufficient space in the destination buffer.
 *
 * @param  ut            the UText from which to extract data.
 * @param  nativeStart   the native index of the first character to extract.
 * @param  nativeLimit   the native string index of the position following the last
 *                       character to extract.
 * @param  dest          the UChar (UTF-16) buffer into which the extracted text is placed
 * @param  destCapacity  The size, in UChars, of the destination buffer.  May be zero
 *                       for precomputing the required size.
 * @param  status        receives any error status.
 *                       If U_BUFFER_OVERFLOW_ERROR: Returns number of UChars for
 *                       preflighting.
 * @return Number of UChars in the data.  Does not include a trailing NUL.
 *
 * @stable ICU 3.4
 */
typedef int32_t U_CALLCONV
UTextExtract(UText *ut,
             int64_t nativeStart, int64_t nativeLimit,
             UChar *dest, int32_t destCapacity,
             UErrorCode *status);

/**
 * Function type declaration for UText.replace().
 *
 * Replace a range of the original text with a replacement text.
 *
 * Leaves the current iteration position at the position following the
 *  newly inserted replacement text.
 *
 * This function need only be implemented on UText types that support writing.
 *
 * When using this function, there should be only a single UText opened onto the
 * underlying native text string.  The function is responsible for updating the
 * text chunk within the UText to reflect the updated iteration position,
 * taking into account any changes to the underlying string's structure caused
 * by the replace operation.
 *
 * @param ut               the UText representing the text to be operated on.
 * @param nativeStart      the index of the start of the region to be replaced
 * @param nativeLimit      the index of the character following the region to be replaced.
 * @param replacementText  pointer to the replacement text
 * @param replacmentLength length of the replacement text in UChars, or -1 if the text is NUL terminated.
 * @param status           receives any error status.  Possible errors include
 *                         U_NO_WRITE_PERMISSION
 *
 * @return The signed number of (native) storage units by which
 *         the length of the text expanded or contracted.
 *
 * @stable ICU 3.4
 */
typedef int32_t U_CALLCONV
UTextReplace(UText *ut,
             int64_t nativeStart, int64_t nativeLimit,
             const UChar *replacementText, int32_t replacmentLength,
             UErrorCode *status);

/**
 * Function type declaration for UText.copy().
 *
 * Copy or move a substring from one position to another within the text,
 * while retaining any metadata associated with the text.
 * This function is used to duplicate or reorder substrings.
 * The destination index must not overlap the source range.
 *
 * The text to be copied or moved is inserted at destIndex;
 * it does not replace or overwrite any existing text.
 *
 * This function need only be implemented for UText types that support writing.
 *
 * When using this function, there should be only a single UText opened onto the
 * underlying native text string.  The function is responsible for updating the
 * text chunk within the UText to reflect the updated iteration position,
 * taking into account any changes to the underlying string's structure caused
 * by the replace operation.
 *
 * @param ut           The UText representing the text to be operated on.
 * @param nativeStart  The index of the start of the region to be copied or moved
 * @param nativeLimit  The index of the character following the region to be replaced.
 * @param nativeDest   The destination index to which the source substring is copied or moved.
 * @param move         If TRUE, then the substring is moved, not copied/duplicated.
 * @param status       receives any error status.  Possible errors include U_NO_WRITE_PERMISSION
 *
 * @stable ICU 3.4
 */
typedef void U_CALLCONV
UTextCopy(UText *ut,
          int64_t nativeStart, int64_t nativeLimit,
          int64_t nativeDest,
          UBool move,
          UErrorCode *status);

/**
 * Function type declaration for UText.mapOffsetToNative().
 * Map from the current UChar offset within the current text chunk to
 *  the corresponding native index in the original source text.
 *
 * This is required only for text providers that do not use native UTF-16 indexes.
 *
 * @param ut     the UText.
 * @return Absolute (native) index corresponding to chunkOffset in the current chunk.
 *         The returned native index should always be to a code point boundary.
 *
 * @stable ICU 3.4
 */
typedef int64_t U_CALLCONV
UTextMapOffsetToNative(const UText *ut);

/**
 * Function type declaration for UText.mapIndexToUTF16().
 * Map from a native index to a UChar offset within a text chunk.
 * Behavior is undefined if the native index does not fall within the
 *   current chunk.
 *
 * This function is required only for text providers that do not use native UTF-16 indexes.
 *
 * @param ut          The UText containing the text chunk.
 * @param nativeIndex Absolute (native) text index, chunk->start<=index<=chunk->limit.
 * @return            Chunk-relative UTF-16 offset corresponding to the specified native
 *                    index.
 *
 * @stable ICU 3.4
 */
typedef int32_t U_CALLCONV
UTextMapNativeIndexToUTF16(const UText *ut, int64_t nativeIndex);

/**
 * Function type declaration for UText.utextClose().
 *
 * A Text Provider close function is only required for provider types that make
 *  allocations in their open function (or other functions) that must be
 *  cleaned when the UText is closed.
 *
 * The allocation of the UText struct itself and any "extra" storage
 * associated with the UText is handled by the common UText implementation
 * and does not require provider specific cleanup in a close function.
 *
 * Most UText provider implementations do not need to implement this function.
 *
 * @param ut A UText object to be closed.
 *
 * @stable ICU 3.4
 */
typedef void U_CALLCONV
UTextClose(UText *ut);

/**
  *   (public)  Function dispatch table for UText.
  *             Conceptually very much like a C++ Virtual Function Table.
  *             This struct defines the organization of the table.
  *             Each text provider implementation must provide an
  *              actual table that is initialized with the appropriate functions
  *              for the type of text being handled.
  *   @stable ICU 3.6
  */
struct UTextFuncs {
    /**
     *   (public)  Function table size, sizeof(UTextFuncs)
     *             Intended for use should the table grow to accommodate added
     *             functions in the future, to allow tests for older format
     *             function tables that do not contain the extensions.
     *
     *             Fields are placed for optimal alignment on
     *             32/64/128-bit-pointer machines, by normally grouping together
     *             4 32-bit fields,
     *             4 pointers,
     *             2 64-bit fields
     *             in sequence.
     *   @stable ICU 3.6
     */
    int32_t       tableSize;

    /**
      *   (private)  Alignment padding.
      *              Do not use, reserved for use by the UText framework only.
      *   @internal
      */
    int32_t       reserved1, /** @internal */ reserved2, /** @internal */ reserved3;

    /**
     * (public) Function pointer for UTextClone
     *
     * @see UTextClone
     * @stable ICU 3.6
     */
    UTextClone *clone;

    /**
     * (public) function pointer for UTextLength
     * May be expensive to compute!
     *
     * @see UTextLength
     * @stable ICU 3.6
     */
    UTextNativeLength *nativeLength;

    /**
     * (public) Function pointer for UTextAccess.
     *
     * @see UTextAccess
     * @stable ICU 3.6
     */
    UTextAccess *access;

    /**
     * (public) Function pointer for UTextExtract.
     *
     * @see UTextExtract
     * @stable ICU 3.6
     */
    UTextExtract *extract;

    /**
     * (public) Function pointer for UTextReplace.
     *
     * @see UTextReplace
     * @stable ICU 3.6
     */
    UTextReplace *replace;

    /**
     * (public) Function pointer for UTextCopy.
     *
     * @see UTextCopy
     * @stable ICU 3.6
     */
    UTextCopy *copy;

    /**
     * (public) Function pointer for UTextMapOffsetToNative.
     *
     * @see UTextMapOffsetToNative
     * @stable ICU 3.6
     */
    UTextMapOffsetToNative *mapOffsetToNative;

    /**
     * (public) Function pointer for UTextMapNativeIndexToUTF16.
     *
     * @see UTextMapNativeIndexToUTF16
     * @stable ICU 3.6
     */
    UTextMapNativeIndexToUTF16 *mapNativeIndexToUTF16;

    /**
     * (public) Function pointer for UTextClose.
      *
      * @see UTextClose
      * @stable ICU 3.6
      */
    UTextClose  *close;

    /**
      * (private)  Spare function pointer
      * @internal
      */
    UTextClose  *spare1;

    /**
      * (private)  Spare function pointer
      * @internal
      */
    UTextClose  *spare2;

    /**
      * (private)  Spare function pointer
      * @internal
      */
    UTextClose  *spare3;

};
/**
 * Function dispatch table for UText
 * @see UTextFuncs
 */
typedef struct UTextFuncs UTextFuncs;

 /**
  *   UText struct.  Provides the interface between the generic UText access code
  *                  and the UText provider code that works on specific kinds of
  *                  text  (UTF-8, noncontiguous UTF-16, whatever.)
  *
  *                  Applications that are using predefined types of text providers
  *                  to pass text data to ICU services will have no need to view the
  *                  internals of the UText structs that they open.
  *
  * @stable ICU 3.6
  */
struct UText {
    /**
     *     (private)  Magic.  Used to help detect when UText functions are handed
     *                        invalid or uninitialized UText structs.
     *                        utext_openXYZ() functions take an initialized,
     *                        but not necessarily open, UText struct as an
     *                        optional fill-in parameter.  This magic field
     *                        is used to check for that initialization.
     *                        Text provider close functions must NOT clear
     *                        the magic field because that would prevent
     *                        reuse of the UText struct.
     * @internal
     */
    uint32_t       magic;

    /**
     *     (private)  Flags for managing the allocation and freeing of
     *                memory associated with this UText.
     * @internal
     */
    int32_t        flags;

    /**
      *  Text provider properties.  This set of flags is maintained by the
      *                             text provider implementation.
      *  @stable ICU 3.4
      */
    int32_t         providerProperties;

    /**
     * (public) sizeOfStruct=sizeof(UText)
     * Allows possible backward compatible extension.
     *
     * @stable ICU 3.4
     */
    int32_t         sizeOfStruct;

    /* ------ 16 byte alignment boundary -----------  */

    /**
      *  (protected) Native index of the first character position following
      *              the current chunk.
      *  @stable ICU 3.6
      */
    int64_t         chunkNativeLimit;

    /**
     *   (protected)  Size in bytes of the extra space (pExtra).
     *  @stable ICU 3.4
     */
    int32_t        extraSize;

    /**
      *    (protected) The highest chunk offset where native indexing and
      *    chunk (UTF-16) indexing correspond.  For UTF-16 sources, value
      *    will be equal to chunkLength.
      *
      *    @stable ICU 3.6
      */
    int32_t         nativeIndexingLimit;

    /* ---- 16 byte alignment boundary------ */

    /**
     *  (protected) Native index of the first character in the text chunk.
     *  @stable ICU 3.6
     */
    int64_t         chunkNativeStart;

    /**
     *  (protected) Current iteration position within the text chunk (UTF-16 buffer).
     *  This is the index to the character that will be returned by utext_next32().
     *  @stable ICU 3.6
     */
    int32_t         chunkOffset;

    /**
     *  (protected) Length the text chunk (UTF-16 buffer), in UChars.
     *  @stable ICU 3.6
     */
    int32_t         chunkLength;

    /* ---- 16  byte alignment boundary-- */

    /**
     *  (protected)  pointer to a chunk of text in UTF-16 format.
     *  May refer either to original storage of the source of the text, or
     *  if conversion was required, to a buffer owned by the UText.
     *  @stable ICU 3.6
     */
    const UChar    *chunkContents;

     /**
      * (public)     Pointer to Dispatch table for accessing functions for this UText.
      * @stable ICU 3.6
      */
    const UTextFuncs     *pFuncs;

    /**
     *  (protected)  Pointer to additional space requested by the
     *               text provider during the utext_open operation.
     * @stable ICU 3.4
     */
    void          *pExtra;

    /**
     * (protected) Pointer to string or text-containing object or similar.
     * This is the source of the text that this UText is wrapping, in a format
     *  that is known to the text provider functions.
     * @stable ICU 3.4
     */
    const void   *context;

    /* --- 16 byte alignment boundary--- */

    /**
     * (protected) Pointer fields available for use by the text provider.
     * Not used by UText common code.
     * @stable ICU 3.6
     */
    const void     *p;
    /**
     * (protected) Pointer fields available for use by the text provider.
     * Not used by UText common code.
     * @stable ICU 3.6
     */
    const void     *q;
     /**
     * (protected) Pointer fields available for use by the text provider.
     * Not used by UText common code.
     * @stable ICU 3.6
      */
    const void     *r;

    /**
      *  Private field reserved for future use by the UText framework
      *     itself.  This is not to be touched by the text providers.
      * @internal ICU 3.4
      */
    void           *privP;

    /* --- 16 byte alignment boundary--- */

    /**
      * (protected) Integer field reserved for use by the text provider.
      * Not used by the UText framework, or by the client (user) of the UText.
      * @stable ICU 3.4
      */
    int64_t         a;

    /**
      * (protected) Integer field reserved for use by the text provider.
      * Not used by the UText framework, or by the client (user) of the UText.
      * @stable ICU 3.4
      */
    int32_t         b;

    /**
      * (protected) Integer field reserved for use by the text provider.
      * Not used by the UText framework, or by the client (user) of the UText.
      * @stable ICU 3.4
      */
    int32_t         c;

    /*  ---- 16 byte alignment boundary---- */

    /**
      *  Private field reserved for future use by the UText framework
      *     itself.  This is not to be touched by the text providers.
      * @internal ICU 3.4
      */
    int64_t         privA;
    /**
      *  Private field reserved for future use by the UText framework
      *     itself.  This is not to be touched by the text providers.
      * @internal ICU 3.4
      */
    int32_t         privB;
    /**
      *  Private field reserved for future use by the UText framework
      *     itself.  This is not to be touched by the text providers.
      * @internal ICU 3.4
      */
    int32_t         privC;
};

/**
 *  Common function for use by Text Provider implementations to allocate and/or initialize
 *  a new UText struct.  To be called in the implementation of utext_open() functions.
 *  If the supplied UText parameter is null, a new UText struct will be allocated on the heap.
 *  If the supplied UText is already open, the provider's close function will be called
 *  so that the struct can be reused by the open that is in progress.
 *
 * @param ut   pointer to a UText struct to be re-used, or null if a new UText
 *             should be allocated.
 * @param extraSpace The amount of additional space to be allocated as part
 *             of this UText, for use by types of providers that require
 *             additional storage.
 * @param status Errors are returned here.
 * @return pointer to the UText, allocated if necessary, with extra space set up if requested.
 * @stable ICU 3.4
 */
U_STABLE UText * U_EXPORT2
utext_setup(UText *ut, int32_t extraSpace, UErrorCode *status);

// do not use #ifndef U_HIDE_INTERNAL_API around the following!
/**
  * @internal
  *  Value used to help identify correctly initialized UText structs.
  *  Note:  must be publicly visible so that UTEXT_INITIALIZER can access it.
  */
enum {
    UTEXT_MAGIC = 0x345ad82c
};

/**
 * initializer to be used with local (stack) instances of a UText
 *  struct.  UText structs must be initialized before passing
 *  them to one of the utext_open functions.
 *
 * @stable ICU 3.6
 */
#define UTEXT_INITIALIZER {                                        \
                  UTEXT_MAGIC,          /* magic                */ \
                  0,                    /* flags                */ \
                  0,                    /* providerProps        */ \
                  sizeof(UText),        /* sizeOfStruct         */ \
                  0,                    /* chunkNativeLimit     */ \
                  0,                    /* extraSize            */ \
                  0,                    /* nativeIndexingLimit  */ \
                  0,                    /* chunkNativeStart     */ \
                  0,                    /* chunkOffset          */ \
                  0,                    /* chunkLength          */ \
                  NULL,                 /* chunkContents        */ \
                  NULL,                 /* pFuncs               */ \
                  NULL,                 /* pExtra               */ \
                  NULL,                 /* context              */ \
                  NULL, NULL, NULL,     /* p, q, r              */ \
                  NULL,                 /* privP                */ \
                  0, 0, 0,              /* a, b, c              */ \
                  0, 0, 0               /* privA,B,C,           */ \
                  }

U_CDECL_END

#if U_SHOW_CPLUSPLUS_API

U_NAMESPACE_BEGIN

/**
 * \class LocalUTextPointer
 * "Smart pointer" class, closes a UText via utext_close().
 * For most methods see the LocalPointerBase base class.
 *
 * @see LocalPointerBase
 * @see LocalPointer
 * @stable ICU 4.4
 */
U_DEFINE_LOCAL_OPEN_POINTER(LocalUTextPointer, UText, utext_close);

U_NAMESPACE_END

#endif

#endif


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2002-2016, International Business Machines
* Corporation and others.  All Rights Reserved.
**********************************************************************
*/
#ifndef _UCURR_H_
#define _UCURR_H_

#include "unicode/utypes.h"
#include "unicode/uenum.h"

/**
 * \file
 * \brief C API: Encapsulates information about a currency.
 *
 * The ucurr API encapsulates information about a currency, as defined by
 * ISO 4217.  A currency is represented by a 3-character string
 * containing its ISO 4217 code.  This API can return various data
 * necessary the proper display of a currency:
 *
 *

A display symbol, for a specific locale
 *
The number of fraction digits to display
 *
A rounding increment
 *

 *
 * The <tt>DecimalFormat</tt> class uses these data to display
 * currencies.
 * @author Alan Liu
 * @since ICU 2.2
 */

#if !UCONFIG_NO_FORMATTING

/**
 * Currency Usage used for Decimal Format
 * @stable ICU 54
 */
enum UCurrencyUsage {
    /**
     * a setting to specify currency usage which determines currency digit
     * and rounding for standard usage, for example: "50.00 NT$"
     * used as DEFAULT value
     * @stable ICU 54
     */
    UCURR_USAGE_STANDARD=0,
    /**
     * a setting to specify currency usage which determines currency digit
     * and rounding for cash usage, for example: "50 NT$"
     * @stable ICU 54
     */
    UCURR_USAGE_CASH=1,
#ifndef U_HIDE_DEPRECATED_API
    /**
     * One higher than the last enum UCurrencyUsage constant.
     * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
     */
    UCURR_USAGE_COUNT=2
#endif  // U_HIDE_DEPRECATED_API
};
/** Currency Usage used for Decimal Format */
typedef enum UCurrencyUsage UCurrencyUsage;

/**
 * Finds a currency code for the given locale.
 * @param locale the locale for which to retrieve a currency code.
 *               Currency can be specified by the "currency" keyword
 *               in which case it overrides the default currency code
 * @param buff   fill in buffer. Can be NULL for preflighting.
 * @param buffCapacity capacity of the fill in buffer. Can be 0 for
 *               preflighting. If it is non-zero, the buff parameter
 *               must not be NULL.
 * @param ec error code
 * @return length of the currency string. It should always be 3. If 0,
 *                currency couldn't be found or the input values are
 *                invalid.
 * @stable ICU 2.8
 */
U_STABLE int32_t U_EXPORT2
ucurr_forLocale(const char* locale,
                UChar* buff,
                int32_t buffCapacity,
                UErrorCode* ec);

/**
 * Selector constants for ucurr_getName().
 *
 * @see ucurr_getName
 * @stable ICU 2.6
 */
typedef enum UCurrNameStyle {
    /**
     * Selector for ucurr_getName indicating a symbolic name for a
     * currency, such as "$" for USD.
     * @stable ICU 2.6
     */
    UCURR_SYMBOL_NAME,

    /**
     * Selector for ucurr_getName indicating the long name for a
     * currency, such as "US Dollar" for USD.
     * @stable ICU 2.6
     */
    UCURR_LONG_NAME,

    /**
     * Selector for getName() indicating the narrow currency symbol.
     * The narrow currency symbol is similar to the regular currency
     * symbol, but it always takes the shortest form: for example,
     * "$" instead of "US$" for USD in en-CA.
     *
     * @stable ICU 61
     */
    UCURR_NARROW_SYMBOL_NAME
} UCurrNameStyle;

#if !UCONFIG_NO_SERVICE
/**
 * @stable ICU 2.6
 */
typedef const void* UCurrRegistryKey;

/**
 * Register an (existing) ISO 4217 currency code for the given locale.
 * Only the country code and the two variants EURO and PRE_EURO are
 * recognized.
 * @param isoCode the three-letter ISO 4217 currency code
 * @param locale  the locale for which to register this currency code
 * @param status the in/out status code
 * @return a registry key that can be used to unregister this currency code, or NULL
 * if there was an error.
 * @stable ICU 2.6
 */
U_STABLE UCurrRegistryKey U_EXPORT2
ucurr_register(const UChar* isoCode,
                   const char* locale,
                   UErrorCode* status);
/**
 * Unregister the previously-registered currency definitions using the
 * URegistryKey returned from ucurr_register.  Key becomes invalid after
 * a successful call and should not be used again.  Any currency
 * that might have been hidden by the original ucurr_register call is
 * restored.
 * @param key the registry key returned by a previous call to ucurr_register
 * @param status the in/out status code, no special meanings are assigned
 * @return TRUE if the currency for this key was successfully unregistered
 * @stable ICU 2.6
 */
U_STABLE UBool U_EXPORT2
ucurr_unregister(UCurrRegistryKey key, UErrorCode* status);
#endif /* UCONFIG_NO_SERVICE */

/**
 * Returns the display name for the given currency in the
 * given locale.  For example, the display name for the USD
 * currency object in the en_US locale is "$".
 * @param currency null-terminated 3-letter ISO 4217 code
 * @param locale locale in which to display currency
 * @param nameStyle selector for which kind of name to return
 * @param isChoiceFormat always set to FALSE, or can be NULL;
 *     display names are static strings;
 *     since ICU 4.4, ChoiceFormat patterns are no longer supported
 * @param len fill-in parameter to receive length of result
 * @param ec error code
 * @return pointer to display string of 'len' UChars.  If the resource
 * data contains no entry for 'currency', then 'currency' itself is
 * returned.
 * @stable ICU 2.6
 */
U_STABLE const UChar* U_EXPORT2
ucurr_getName(const UChar* currency,
              const char* locale,
              UCurrNameStyle nameStyle,
              UBool* isChoiceFormat,
              int32_t* len,
              UErrorCode* ec);

/**
 * Returns the plural name for the given currency in the
 * given locale.  For example, the plural name for the USD
 * currency object in the en_US locale is "US dollar" or "US dollars".
 * @param currency null-terminated 3-letter ISO 4217 code
 * @param locale locale in which to display currency
 * @param isChoiceFormat always set to FALSE, or can be NULL;
 *     display names are static strings;
 *     since ICU 4.4, ChoiceFormat patterns are no longer supported
 * @param pluralCount plural count
 * @param len fill-in parameter to receive length of result
 * @param ec error code
 * @return pointer to display string of 'len' UChars.  If the resource
 * data contains no entry for 'currency', then 'currency' itself is
 * returned.
 * @stable ICU 4.2
 */
U_STABLE const UChar* U_EXPORT2
ucurr_getPluralName(const UChar* currency,
                    const char* locale,
                    UBool* isChoiceFormat,
                    const char* pluralCount,
                    int32_t* len,
                    UErrorCode* ec);

/**
 * Returns the number of the number of fraction digits that should
 * be displayed for the given currency.
 * This is equivalent to ucurr_getDefaultFractionDigitsForUsage(currency,UCURR_USAGE_STANDARD,ec);
 *
 * Important: The number of fraction digits for a given currency is NOT
 * guaranteed to be constant across versions of ICU or CLDR. For example,
 * do NOT use this value as a mechanism for deciding the magnitude used
 * to store currency values in a database. You should use this value for
 * display purposes only.
 *
 * @param currency null-terminated 3-letter ISO 4217 code
 * @param ec input-output error code
 * @return a non-negative number of fraction digits to be
 * displayed, or 0 if there is an error
 * @stable ICU 3.0
 */
U_STABLE int32_t U_EXPORT2
ucurr_getDefaultFractionDigits(const UChar* currency,
                               UErrorCode* ec);

/**
 * Returns the number of the number of fraction digits that should
 * be displayed for the given currency with usage.
 *
 * Important: The number of fraction digits for a given currency is NOT
 * guaranteed to be constant across versions of ICU or CLDR. For example,
 * do NOT use this value as a mechanism for deciding the magnitude used
 * to store currency values in a database. You should use this value for
 * display purposes only.
 *
 * @param currency null-terminated 3-letter ISO 4217 code
 * @param usage enum usage for the currency
 * @param ec input-output error code
 * @return a non-negative number of fraction digits to be
 * displayed, or 0 if there is an error
 * @stable ICU 54
 */
U_STABLE int32_t U_EXPORT2
ucurr_getDefaultFractionDigitsForUsage(const UChar* currency,
                                       const UCurrencyUsage usage,
                                       UErrorCode* ec);

/**
 * Returns the rounding increment for the given currency, or 0.0 if no
 * rounding is done by the currency.
 * This is equivalent to ucurr_getRoundingIncrementForUsage(currency,UCURR_USAGE_STANDARD,ec);
 * @param currency null-terminated 3-letter ISO 4217 code
 * @param ec input-output error code
 * @return the non-negative rounding increment, or 0.0 if none,
 * or 0.0 if there is an error
 * @stable ICU 3.0
 */
U_STABLE double U_EXPORT2
ucurr_getRoundingIncrement(const UChar* currency,
                           UErrorCode* ec);

/**
 * Returns the rounding increment for the given currency, or 0.0 if no
 * rounding is done by the currency given usage.
 * @param currency null-terminated 3-letter ISO 4217 code
 * @param usage enum usage for the currency
 * @param ec input-output error code
 * @return the non-negative rounding increment, or 0.0 if none,
 * or 0.0 if there is an error
 * @stable ICU 54
 */
U_STABLE double U_EXPORT2
ucurr_getRoundingIncrementForUsage(const UChar* currency,
                                   const UCurrencyUsage usage,
                                   UErrorCode* ec);

/**
 * Selector constants for ucurr_openCurrencies().
 *
 * @see ucurr_openCurrencies
 * @stable ICU 3.2
 */
typedef enum UCurrCurrencyType {
    /**
     * Select all ISO-4217 currency codes.
     * @stable ICU 3.2
     */
    UCURR_ALL = INT32_MAX,
    /**
     * Select only ISO-4217 commonly used currency codes.
     * These currencies can be found in common use, and they usually have
     * bank notes or coins associated with the currency code.
     * This does not include fund codes, precious metals and other
     * various ISO-4217 codes limited to special financial products.
     * @stable ICU 3.2
     */
    UCURR_COMMON = 1,
    /**
     * Select ISO-4217 uncommon currency codes.
     * These codes respresent fund codes, precious metals and other
     * various ISO-4217 codes limited to special financial products.
     * A fund code is a monetary resource associated with a currency.
     * @stable ICU 3.2
     */
    UCURR_UNCOMMON = 2,
    /**
     * Select only deprecated ISO-4217 codes.
     * These codes are no longer in general public use.
     * @stable ICU 3.2
     */
    UCURR_DEPRECATED = 4,
    /**
     * Select only non-deprecated ISO-4217 codes.
     * These codes are in general public use.
     * @stable ICU 3.2
     */
    UCURR_NON_DEPRECATED = 8
} UCurrCurrencyType;

/**
 * Provides a UEnumeration object for listing ISO-4217 codes.
 * @param currType You can use one of several UCurrCurrencyType values for this
 *      variable. You can also | (or) them together to get a specific list of
 *      currencies. Most people will want to use the (UCURR_COMMON|UCURR_NON_DEPRECATED) value to
 *      get a list of current currencies.
 * @param pErrorCode Error code
 * @stable ICU 3.2
 */
U_STABLE UEnumeration * U_EXPORT2
ucurr_openISOCurrencies(uint32_t currType, UErrorCode *pErrorCode);

/**
  * Queries if the given ISO 4217 3-letter code is available on the specified date range.
  *
  * Note: For checking availability of a currency on a specific date, specify the date on both 'from' and 'to'
  *
  * When 'from' is U_DATE_MIN and 'to' is U_DATE_MAX, this method checks if the specified currency is available any time.
  * If 'from' and 'to' are same UDate value, this method checks if the specified currency is available on that date.
  *
  * @param isoCode
  *            The ISO 4217 3-letter code.
  *
  * @param from
  *            The lower bound of the date range, inclusive. When 'from' is U_DATE_MIN, check the availability
  *            of the currency any date before 'to'
  *
  * @param to
  *            The upper bound of the date range, inclusive. When 'to' is U_DATE_MAX, check the availability of
  *            the currency any date after 'from'
  *
  * @param errorCode
  *            ICU error code
   *
  * @return TRUE if the given ISO 4217 3-letter code is supported on the specified date range.
  *
  * @stable ICU 4.8
  */
U_STABLE UBool U_EXPORT2
ucurr_isAvailable(const UChar* isoCode,
             UDate from,
             UDate to,
             UErrorCode* errorCode);

/**
 * Finds the number of valid currency codes for the
 * given locale and date.
 * @param locale the locale for which to retrieve the
 *               currency count.
 * @param date   the date for which to retrieve the
 *               currency count for the given locale.
 * @param ec     error code
 * @return       the number of currency codes for the
 *               given locale and date.  If 0, currency
 *               codes couldn't be found for the input
 *               values are invalid.
 * @stable ICU 4.0
 */
U_STABLE int32_t U_EXPORT2
ucurr_countCurrencies(const char* locale,
                 UDate date,
                 UErrorCode* ec);

/**
 * Finds a currency code for the given locale and date
 * @param locale the locale for which to retrieve a currency code.
 *               Currency can be specified by the "currency" keyword
 *               in which case it overrides the default currency code
 * @param date   the date for which to retrieve a currency code for
 *               the given locale.
 * @param index  the index within the available list of currency codes
 *               for the given locale on the given date.
 * @param buff   fill in buffer. Can be NULL for preflighting.
 * @param buffCapacity capacity of the fill in buffer. Can be 0 for
 *               preflighting. If it is non-zero, the buff parameter
 *               must not be NULL.
 * @param ec     error code
 * @return       length of the currency string. It should always be 3.
 *               If 0, currency couldn't be found or the input values are
 *               invalid.
 * @stable ICU 4.0
 */
U_STABLE int32_t U_EXPORT2
ucurr_forLocaleAndDate(const char* locale,
                UDate date,
                int32_t index,
                UChar* buff,
                int32_t buffCapacity,
                UErrorCode* ec);

/**
 * Given a key and a locale, returns an array of string values in a preferred
 * order that would make a difference. These are all and only those values where
 * the open (creation) of the service with the locale formed from the input locale
 * plus input keyword and that value has different behavior than creation with the
 * input locale alone.
 * @param key           one of the keys supported by this service.  For now, only
 *                      "currency" is supported.
 * @param locale        the locale
 * @param commonlyUsed  if set to true it will return only commonly used values
 *                      with the given locale in preferred order.  Otherwise,
 *                      it will return all the available values for the locale.
 * @param status error status
 * @return a string enumeration over keyword values for the given key and the locale.
 * @stable ICU 4.2
 */
U_STABLE UEnumeration* U_EXPORT2
ucurr_getKeywordValuesForLocale(const char* key,
                                const char* locale,
                                UBool commonlyUsed,
                                UErrorCode* status);

/**
 * Returns the ISO 4217 numeric code for the currency.
 *
Note: If the ISO 4217 numeric code is not assigned for the currency or
 * the currency is unknown, this function returns 0.
 *
 * @param currency null-terminated 3-letter ISO 4217 code
 * @return The ISO 4217 numeric code of the currency
 * @stable ICU 49
 */
U_STABLE int32_t U_EXPORT2
ucurr_getNumericCode(const UChar* currency);

#endif /* #if !UCONFIG_NO_FORMATTING */

#endif