merge heads
diff --git a/Include/unicodeobject.h b/Include/unicodeobject.h
index c41d787..bba1c23 100644
--- a/Include/unicodeobject.h
+++ b/Include/unicodeobject.h
@@ -795,7 +795,9 @@
     Py_ssize_t *size            /* number of characters of the result */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void*) _PyUnicode_AsKind(PyObject *s, unsigned int kind);
+#endif
 
 #endif
 
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
index 9971f5c..51cd855 100644
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -10446,6 +10446,11 @@
     int kind;
     Py_ssize_t length;
 
+    if (PyUnicode_READY(self) == -1)
+        return NULL;
+
+    end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
+
     if (start == 0 && end == PyUnicode_GET_LENGTH(self))
     {
         if (PyUnicode_CheckExact(self)) {
@@ -10460,13 +10465,11 @@
     if (length == 1)
         return unicode_getitem((PyUnicodeObject*)self, start);
 
-    if (start < 0 || end < 0 || end > PyUnicode_GET_LENGTH(self)) {
+    if (start < 0 || end < 0) {
         PyErr_SetString(PyExc_IndexError, "string index out of range");
         return NULL;
     }
 
-    if (PyUnicode_READY(self) == -1)
-        return NULL;
     kind = PyUnicode_KIND(self);
     data = PyUnicode_1BYTE_DATA(self);
     return PyUnicode_FromKindAndData(kind,