code: def maybe_cast_to_integer_array(
      arr: list | np.ndarray, dtype: np.dtype
  ) -> np.ndarray:
      """
      Takes any dtype and returns the casted version, raising for when data is
      incompatible with integer/unsigned integer dtypes.
  
      Parameters
      ----------
      arr : np.ndarray or list
          The array to cast.
      dtype : np.dtype
          The integer dtype to cast the array to.
  
      Returns
      -------
      ndarray
          Array of integer or unsigned integer dtype.
  
      Raises
      ------
      OverflowError : the dtype is incompatible with the data
      ValueError : loss of precision has occurred during casting
  
      Examples
      --------
      If you try to coerce negative values to unsigned integers, it raises:
  
      >>> pd.Series([-1], dtype="uint64")
      Traceback (most recent call last):
          ...
      OverflowError: Trying to coerce negative values to unsigned integers
  
      Also, if you try to coerce float values to integers, it raises:
  
      >>> maybe_cast_to_integer_array([1, 2, 3.5], dtype=np.dtype("int64"))
      Traceback (most recent call last):
          ...
      ValueError: Trying to coerce float values to integers
      """
      assert is_integer_dtype(dtype)
  
      try:
          if not isinstance(arr, np.ndarray):
              with warnings.catch_warnings():
                  # We already disallow dtype=uint w/ negative numbers
                  # (test_constructor_coercion_signed_to_unsigned) so safe to ignore.
                  warnings.filterwarnings(
                      "ignore",
                      "NumPy will stop allowing conversion of out-of-bound Python int",
                      DeprecationWarning,
                  )
                  casted = np.array(arr, dtype=dtype, copy=False)
          else:
              with warnings.catch_warnings():
                  warnings.filterwarnings(
                      "ignore", category=RuntimeWarning
                  )
                  casted = arr.astype(dtype, copy=False)
      except OverflowError as err:
          raise OverflowError(
              "The elements provided in the data cannot all be "
              f"casted to the dtype {dtype}"
          ) from err
  
      if isinstance(arr, np.ndarray) and arr.dtype == dtype:
          # avoid expensive array_equal check
          return casted
  
      with warnings.catch_warnings():
          warnings.filterwarnings("ignore", category=RuntimeWarning)
          if np.array_equal(arr, casted):
              return casted
  
      # We do this casting to allow for proper
      # data and dtype checking.
      #
      # We didn't do this earlier because NumPy
      # doesn't handle `uint64` correctly.
      arr = np.asarray(arr)
  
      if np.issubdtype(arr.dtype, str):
          if (casted.astype(str) == arr).all():
              return casted
          raise ValueError(
              f"string values cannot be losslessly cast to {dtype}"
          )
  
      if is_unsigned_integer_dtype(dtype) and (arr < 0).any():
          raise OverflowError(
              "Trying to coerce negative values to unsigned integers"
          )
  
      if is_float_dtype(arr.dtype):
          if not np.isfinite(arr).all():
              raise IntCastingNaNError(
                  "Cannot convert non-finite values (NA or inf) to integer"
              )
          raise ValueError("Trying to coerce float values to integers")
      if is_object_dtype(arr.dtype):
          raise ValueError("Trying to coerce float values to integers")
  
      if casted.dtype < arr.dtype:
          # GH#41734 e.g. [1, 200, 923442] and dtype="int8" -> overflows
          raise ValueError(
              f"Values are too large to be losslessly converted to {dtype}. "
              f"To cast anyway, use pd.Series(values).astype({dtype})"
          )
  
      if arr.dtype.kind in ["m", "M"]:
          # test_constructor_maskedarray_nonfloat
          raise TypeError(
              f"Constructing a Series or DataFrame from {arr.dtype} values and "
              f"dtype={dtype} is not supported. Use values.view({dtype}) instead."
          )
  
      # No known cases that get here, but raising explicitly to cover our bases.
      raise ValueError(f"values cannot be losslessly cast to {dtype}")
  
imports: from __future__ import annotations
  import datetime
  import functools
  from typing import TYPE_CHECKING, Any, Literal, Sized, TypeVar, cast, overload
  import warnings
  import numpy
  from pandas._libs import lib
  from pandas._libs.missing import NA, NAType, checknull
  from pandas._libs.tslibs import NaT, OutOfBoundsDatetime, OutOfBoundsTimedelta, Timedelta, Timestamp, get_unit_from_dtype, is_supported_unit
  from pandas._libs.tslibs.timedeltas import array_to_timedelta64
  from pandas._typing import ArrayLike, Dtype, DtypeObj, NumpyIndexT, Scalar, npt
  from pandas.errors import IntCastingNaNError, LossySetitemError
  from pandas.core.dtypes.common import ensure_int8, ensure_int16, ensure_int32, ensure_int64, ensure_object, ensure_str, is_bool, is_bool_dtype, is_complex, is_complex_dtype, is_datetime64_dtype, is_extension_array_dtype, is_float, is_float_dtype, is_integer, is_integer_dtype, is_numeric_dtype, is_object_dtype, is_scalar, is_signed_integer_dtype, is_string_dtype, is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype
  from pandas.core.dtypes.dtypes import BaseMaskedDtype, CategoricalDtype, DatetimeTZDtype, ExtensionDtype, IntervalDtype, PandasExtensionDtype, PeriodDtype
  from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndex, ABCSeries
  from pandas.core.dtypes.inference import is_list_like
  from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, na_value_for_dtype, notna
  from pandas.io._util import _arrow_dtype_mapping
label_desc: Use image node_id 45 for calling a global function with example usage: maybe_cast_to_integer_array(arr, dtype) and returns: casted, casted, casted