+/**
+ * UText, replace entire contents of the destination UText with a substring of the source UText.
+ *
+ * @param src The source UText
+ * @param dest The destination UText. Must be writable.
+ * May be NULL, in which case a new UText will be allocated.
+ * @param start Start index of source substring.
+ * @param limit Limit index of source substring.
+ * @param status An error code.
+ */
+static UText *utext_extract_replace(UText *src, UText *dest, int64_t start, int64_t limit, UErrorCode *status) {
+ if (U_FAILURE(*status)) {
+ return dest;
+ }
+ if (start == limit) {
+ if (dest) {
+ utext_replace(dest, 0, utext_nativeLength(dest), NULL, 0, status);
+ return dest;
+ } else {
+ return utext_openUChars(NULL, NULL, 0, status);
+ }
+ }
+ int32_t length = utext_extract(src, start, limit, NULL, 0, status);
+ if (*status != U_BUFFER_OVERFLOW_ERROR && U_FAILURE(*status)) {
+ return dest;
+ }
+ *status = U_ZERO_ERROR;
+ MaybeStackArray<UChar, 40> buffer;
+ if (length >= buffer.getCapacity()) {
+ UChar *newBuf = buffer.resize(length+1); // Leave space for terminating Nul.
+ if (newBuf == NULL) {
+ *status = U_MEMORY_ALLOCATION_ERROR;
+ }
+ }
+ utext_extract(src, start, limit, buffer.getAlias(), length+1, status);
+ if (dest) {
+ utext_replace(dest, 0, utext_nativeLength(dest), buffer.getAlias(), length, status);
+ return dest;
+ }
+
+ // Caller did not provide a prexisting UText.
+ // Open a new one, and have it adopt the text buffer storage.
+ if (U_FAILURE(*status)) {
+ return NULL;
+ }
+ int32_t ownedLength = 0;
+ UChar *ownedBuf = buffer.orphanOrClone(length+1, ownedLength);
+ if (ownedBuf == NULL) {
+ *status = U_MEMORY_ALLOCATION_ERROR;
+ return NULL;
+ }
+ UText *result = utext_openUChars(NULL, ownedBuf, length, status);
+ if (U_FAILURE(*status)) {
+ uprv_free(ownedBuf);
+ return NULL;
+ }
+ result->providerProperties |= (1 << UTEXT_PROVIDER_OWNS_TEXT);
+ return result;
+}
+
+