text:
package com.github.blackshadowwalker.spring.retrofit.factory;

import com.github.blackshadowwalker.spring.retrofit.exception.RetrofitRpcInvockException;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.*;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import static com.google.gson.internal.$Gson$Types.getRawType;

/**
 * Created by hoopa on 2017/5/20.
 */
public class StringConvertFactory extends Converter.Factory {

    public static StringConvertFactory create() {
        StringConvertFactory f = new StringConvertFactory();
        return f;
    }

    public Converter<ResponseBody, String> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (String.class == type) {
            return StringConverter.INSTANCE;
        }
        return null;
    }

    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return null;
    }

    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return null;
    }

}


text:
use super::*;
use crate::cmp::Ordering::{self, Equal, Greater, Less};
use crate::intrinsics;
use crate::slice::{self, SliceIndex};

#[lang = "mut_ptr"]
impl<T: ?Sized> *mut T {
    /// Returns `true` if the pointer is null.
    ///
    /// Note that unsized types have many possible null pointers, as only the
    /// raw data pointer is considered, not their length, vtable, etc.
    /// Therefore, two pointers that are null may still not compare equal to
    /// each other.
    ///
    /// ## Behavior during const evaluation
    ///
    /// When this function is used during const evaluation, it may return `false` for pointers
    /// that turn out to be null at runtime. Specifically, when a pointer to some memory
    /// is offset beyond its bounds in such a way that the resulting pointer is null,
    /// the function will still return `false`. There is no way for CTFE to know
    /// the absolute position of that memory, so we cannot tell if the pointer is
    /// null or not.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let mut s = [1, 2, 3];
    /// let ptr: *mut u32 = s.as_mut_ptr();
    /// assert!(!ptr.is_null());
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")]
    #[inline]
    pub const fn is_null(self) -> bool {
        // Compare via a cast to a thin pointer, so fat pointers are only
        // considering their "data" part for null-ness.
        (self as *mut u8).guaranteed_eq(null_mut())
    }

    /// Casts to a pointer of another type.
    #[stable(feature = "ptr_cast", since = "1.38.0")]
    #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")]
    #[inline(always)]
    pub const fn cast(self) -> *mut U {
        self as _
    }

    /// Decompose a (possibly wide) pointer into its address and metadata components.
    ///
    /// The pointer can be later reconstructed with [`from_raw_parts_mut`].
    #[unstable(feature = "ptr_metadata", issue = "81513")]
    #[rustc_const_unstable(feature = "ptr_metadata", issue = "81513")]
    #[inline]
    pub const fn to_raw_parts(self) -> (*mut (), <T as super::Pointee>::Metadata) {
        (self.cast(), super::metadata(self))
    }

    /// Returns `None` if the pointer is null, or else returns a shared reference to
    /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_ref`]
    /// must be used instead.
    ///
    /// For the mutable counterpart see [`as_mut`].
    ///
    /// [`as_uninit_ref`]: #method.as_uninit_ref-1
    /// [`as_mut`]: #method.as_mut
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that *either* the pointer is null *or*
    /// all of the following is true:
    ///
    /// * The pointer must be properly aligned.
    ///
    /// * It must be "dereferencable" in the sense defined in [the module documentation].
    ///
    /// * The pointer must point to an initialized instance of `T`.
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, for the duration of this lifetime, the memory the pointer points to must
    ///   not get mutated (except inside `UnsafeCell`).
    ///
    /// This applies even if the result of this method is unused!
    /// (The part about being initialized is not yet fully decided, but until
    /// it is, the only safe approach is to ensure that they are indeed initialized.)
    ///
    /// [the module documentation]: crate::ptr#safety
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
    ///
    /// unsafe {
    ///     if let Some(val_back) = ptr.as_ref() {
    ///         println!("We got back the value: {}!", val_back);
    ///     }
    /// }
    /// ```
    ///
    /// # Null-unchecked version
    ///
    /// If you are sure the pointer can never be null and are looking for some kind of
    /// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>`, know that you can
    /// dereference the pointer directly.
    ///
    /// ```
    /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
    ///
    /// unsafe {
    ///     let val_back = &*ptr;
    ///     println!("We got back the value: {}!", val_back);
    /// }
    /// ```
    #[stable(feature = "ptr_as_ref", since = "1.9.0")]
    #[inline]
    pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
        // SAFETY: the caller must guarantee that `self` is valid for a
        // reference if it isn't null.
        if self.is_null() { None } else { unsafe { Some(&*self) } }
    }

    /// Returns `None` if the pointer is null, or else returns a shared reference to
    /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
    /// that the value has to be initialized.
    ///
    /// For the mutable counterpart see [`as_uninit_mut`].
    ///
    /// [`as_ref`]: #method.as_ref-1
    /// [`as_uninit_mut`]: #method.as_uninit_mut
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that *either* the pointer is null *or*
    /// all of the following is true:
    ///
    /// * The pointer must be properly aligned.
    ///
    /// * It must be "dereferencable" in the sense defined in [the module documentation].
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, for the duration of this lifetime, the memory the pointer points to must
    ///   not get mutated (except inside `UnsafeCell`).
    ///
    /// This applies even if the result of this method is unused!
    ///
    /// [the module documentation]: crate::ptr#safety
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// #![feature(ptr_as_uninit)]
    ///
    /// let ptr: *mut u8 = &mut 10u8 as *mut u8;
    ///
    /// unsafe {
    ///     if let Some(val_back) = ptr.as_uninit_ref() {
    ///         println!("We got back the value: {}!", val_back.assume_init());
    ///     }
    /// }
    /// ```
    #[inline]
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
    pub unsafe fn as_uninit_ref<'a>(self) -> Option<&'a MaybeUninit<T>>
    where
        T: Sized,
    {
        // SAFETY: the caller must guarantee that `self` meets all the
        // requirements for a reference.
        if self.is_null() { None } else { Some(unsafe { &*(self as *const MaybeUninit<T>) }) }
    }

    /// Calculates the offset from a pointer.
    ///
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
    /// offset of `3 * size_of::<T>()` bytes.
    ///
    /// # Safety
    ///
    /// If any of the following conditions are violated, the result is Undefined
    /// Behavior:
    ///
    /// * Both the starting and resulting pointer must be either in bounds or one
    ///   byte past the end of the same [allocated object].
    ///
    /// * The computed offset, **in bytes**, cannot overflow an `isize`.
    ///
    /// * The offset being in bounds cannot rely on "wrapping around" the address
    ///   space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
    ///
    /// The compiler and standard library generally tries to ensure allocations
    /// never reach a size where an offset is a concern. For instance, `Vec`
    /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
    /// `vec.as_ptr().add(vec.len())` is always safe.
    ///
    /// Most platforms fundamentally can't even construct such an allocation.
    /// For instance, no known 64-bit platform can ever serve a request
    /// for 263 bytes due to page-table limitations or splitting the address space.
    /// However, some 32-bit and 16-bit platforms may successfully serve a request for
    /// more than `isize::MAX` bytes with things like Physical Address
    /// Extension. As such, memory acquired directly from allocators or memory
    /// mapped files *may* be too large to handle with this function.
    ///
    /// Consider using [`wrapping_offset`] instead if these constraints are
    /// difficult to satisfy. The only advantage of this method is that it
    /// enables more aggressive compiler optimizations.
    ///
    /// [`wrapping_offset`]: #method.wrapping_offset
    /// [allocated object]: crate::ptr#allocated-object
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let mut s = [1, 2, 3];
    /// let ptr: *mut u32 = s.as_mut_ptr();
    ///
    /// unsafe {
    ///     println!("{}", *ptr.offset(1));
    ///     println!("{}", *ptr.offset(2));
    /// }
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    #[must_use = "returns a new pointer rather than modifying its argument"]
    #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
    #[inline(always)]
    pub const unsafe fn offset(self, count: isize) -> *mut T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `offset`.
        // The obtained pointer is valid for writes since the caller must
        // guarantee that it points to the same allocated object as `self`.
        unsafe { intrinsics::offset(self, count) as *mut T }
    }

    /// Calculates the offset from a pointer using wrapping arithmetic.
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
    /// offset of `3 * size_of::<T>()` bytes.
    ///
    /// # Safety
    ///
    /// This operation itself is always safe, but using the resulting pointer is not.
    ///
    /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
    /// be used to read or write other allocated objects.
    ///
    /// In other words, `let z = x.wrapping_offset((y as isize) - (x as isize))` does *not* make `z`
    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
    /// `x` and `y` point into the same allocated object.
    ///
    /// Compared to [`offset`], this method basically delays the requirement of staying within the
    /// same allocated object: [`offset`] is immediate Undefined Behavior when crossing object
    /// boundaries; `wrapping_offset` produces a pointer but still leads to Undefined Behavior if a
    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`offset`]
    /// can be optimized better and is thus preferable in performance-sensitive code.
    ///
    /// The delayed check only considers the value of the pointer that was dereferenced, not the
    /// intermediate values used during the computation of the final result. For example,
    /// `x.wrapping_offset(o).wrapping_offset(o.wrapping_neg())` is always the same as `x`. In other
    /// words, leaving the allocated object and then re-entering it later is permitted.
    ///
    /// [`offset`]: #method.offset
    /// [allocated object]: crate::ptr#allocated-object
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// // Iterate using a raw pointer in increments of two elements
    /// let mut data = [1u8, 2, 3, 4, 5];
    /// let mut ptr: *mut u8 = data.as_mut_ptr();
    /// let step = 2;
    /// let end_rounded_up = ptr.wrapping_offset(6);
    ///
    /// while ptr != end_rounded_up {
    ///     unsafe {
    ///         *ptr = 0;
    ///     }
    ///     ptr = ptr.wrapping_offset(step);
    /// }
    /// assert_eq!(&data, &[0, 2, 0, 4, 0]);
    /// ```
    #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
    #[must_use = "returns a new pointer rather than modifying its argument"]
    #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
    #[inline(always)]
    pub const fn wrapping_offset(self, count: isize) -> *mut T
    where
        T: Sized,
    {
        // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called.
        unsafe { intrinsics::arith_offset(self, count) as *mut T }
    }

    /// Returns `None` if the pointer is null, or else returns a unique reference to
    /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`]
    /// must be used instead.
    ///
    /// For the shared counterpart see [`as_ref`].
    ///
    /// [`as_uninit_mut`]: #method.as_uninit_mut
    /// [`as_ref`]: #method.as_ref-1
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that *either* the pointer is null *or*
    /// all of the following is true:
    ///
    /// * The pointer must be properly aligned.
    ///
    /// * It must be "dereferencable" in the sense defined in [the module documentation].
    ///
    /// * The pointer must point to an initialized instance of `T`.
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, for the duration of this lifetime, the memory the pointer points to must
    ///   not get accessed (read or written) through any other pointer.
    ///
    /// This applies even if the result of this method is unused!
    /// (The part about being initialized is not yet fully decided, but until
    /// it is, the only safe approach is to ensure that they are indeed initialized.)
    ///
    /// [the module documentation]: crate::ptr#safety
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let mut s = [1, 2, 3];
    /// let ptr: *mut u32 = s.as_mut_ptr();
    /// let first_value = unsafe { ptr.as_mut().unwrap() };
    /// *first_value = 4;
    /// # assert_eq!(s, [4, 2, 3]);
    /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
    /// ```
    ///
    /// # Null-unchecked version
    ///
    /// If you are sure the pointer can never be null and are looking for some kind of
    /// `as_mut_unchecked` that returns the `&mut T` instead of `Option<&mut T>`, know that
    /// you can dereference the pointer directly.
    ///
    /// ```
    /// let mut s = [1, 2, 3];
    /// let ptr: *mut u32 = s.as_mut_ptr();
    /// let first_value = unsafe { &mut *ptr };
    /// *first_value = 4;
    /// # assert_eq!(s, [4, 2, 3]);
    /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
    /// ```
    #[stable(feature = "ptr_as_ref", since = "1.9.0")]
    #[inline]
    pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
        // SAFETY: the caller must guarantee that `self` is be valid for
        // a mutable reference if it isn't null.
        if self.is_null() { None } else { unsafe { Some(&mut *self) } }
    }

    /// Returns `None` if the pointer is null, or else returns a unique reference to
    /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
    /// that the value has to be initialized.
    ///
    /// For the shared counterpart see [`as_uninit_ref`].
    ///
    /// [`as_mut`]: #method.as_mut
    /// [`as_uninit_ref`]: #method.as_uninit_ref-1
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that *either* the pointer is null *or*
    /// all of the following is true:
    ///
    /// * The pointer must be properly aligned.
    ///
    /// * It must be "dereferencable" in the sense defined in [the module documentation].
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, for the duration of this lifetime, the memory the pointer points to must
    ///   not get accessed (read or written) through any other pointer.
    ///
    /// This applies even if the result of this method is unused!
    ///
    /// [the module documentation]: crate::ptr#safety
    #[inline]
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
    pub unsafe fn as_uninit_mut<'a>(self) -> Option<&'a mut MaybeUninit<T>>
    where
        T: Sized,
    {
        // SAFETY: the caller must guarantee that `self` meets all the
        // requirements for a reference.
        if self.is_null() { None } else { Some(unsafe { &mut *(self as *mut MaybeUninit<T>) }) }
    }

    /// Returns whether two pointers are guaranteed to be equal.
    ///
    /// At runtime this function behaves like `self == other`.
    /// However, in some contexts (e.g., compile-time evaluation),
    /// it is not always possible to determine equality of two pointers, so this function may
    /// spuriously return `false` for pointers that later actually turn out to be equal.
    /// But when it returns `true`, the pointers are guaranteed to be equal.
    ///
    /// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
    /// comparisons for which both functions return `false`.
    ///
    /// [`guaranteed_ne`]: #method.guaranteed_ne
    ///
    /// The return value may change depending on the compiler version and unsafe code might not
    /// rely on the result of this function for soundness. It is suggested to only use this function
    /// for performance optimizations where spurious `false` return values by this function do not
    /// affect the outcome, but just the performance.
    /// The consequences of using this method to make runtime and compile-time code behave
    /// differently have not been explored. This method should not be used to introduce such
    /// differences, and it should also not be stabilized before we have a better understanding
    /// of this issue.
    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
    #[inline]
    pub const fn guaranteed_eq(self, other: *mut T) -> bool
    where
        T: Sized,
    {
        intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
    }

    /// Returns whether two pointers are guaranteed to be unequal.
    ///
    /// At runtime this function behaves like `self != other`.
    /// However, in some contexts (e.g., compile-time evaluation),
    /// it is not always possible to determine the inequality of two pointers, so this function may
    /// spuriously return `false` for pointers that later actually turn out to be unequal.
    /// But when it returns `true`, the pointers are guaranteed to be unequal.
    ///
    /// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
    /// comparisons for which both functions return `false`.
    ///
    /// [`guaranteed_eq`]: #method.guaranteed_eq
    ///
    /// The return value may change depending on the compiler version and unsafe code might not
    /// rely on the result of this function for soundness. It is suggested to only use this function
    /// for performance optimizations where spurious `false` return values by this function do not
    /// affect the outcome, but just the performance.
    /// The consequences of using this method to make runtime and compile-time code behave
    /// differently have not been explored. This method should not be used to introduce such
    /// differences, and it should also not be stabilized before we have a better understanding
    /// of this issue.
    #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
    #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
    #[inline]
    pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
    where
        T: Sized,
    {
        intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
    }

    /// Calculates the distance between two pointers. The returned value is in
    /// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
    ///
    /// This function is the inverse of [`offset`].
    ///
    /// [`offset`]: #method.offset-1
    ///
    /// # Safety
    ///
    /// If any of the following conditions are violated, the result is Undefined
    /// Behavior:
    ///
    /// * Both the starting and other pointer must be either in bounds or one
    ///   byte past the end of the same [allocated object].
    ///
    /// * Both pointers must be *derived from* a pointer to the same object.
    ///   (See below for an example.)
    ///
    /// * The distance between the pointers, in bytes, must be an exact multiple
    ///   of the size of `T`.
    ///
    /// * The distance between the pointers, **in bytes**, cannot overflow an `isize`.
    ///
    /// * The distance being in bounds cannot rely on "wrapping around" the address space.
    ///
    /// Rust types are never larger than `isize::MAX` and Rust allocations never wrap around the
    /// address space, so two pointers within some value of any Rust type `T` will always satisfy
    /// the last two conditions. The standard library also generally ensures that allocations
    /// never reach a size where an offset is a concern. For instance, `Vec` and `Box` ensure they
    /// never allocate more than `isize::MAX` bytes, so `ptr_into_vec.offset_from(vec.as_ptr())`
    /// always satisfies the last two conditions.
    ///
    /// Most platforms fundamentally can't even construct such a large allocation.
    /// For instance, no known 64-bit platform can ever serve a request
    /// for 263 bytes due to page-table limitations or splitting the address space.
    /// However, some 32-bit and 16-bit platforms may successfully serve a request for
    /// more than `isize::MAX` bytes with things like Physical Address
    /// Extension. As such, memory acquired directly from allocators or memory
    /// mapped files *may* be too large to handle with this function.
    /// (Note that [`offset`] and [`add`] also have a similar limitation and hence cannot be used on
    /// such large allocations either.)
    ///
    /// [`add`]: #method.add
    /// [allocated object]: crate::ptr#allocated-object
    ///
    /// # Panics
    ///
    /// This function panics if `T` is a Zero-Sized Type ("ZST").
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let mut a = [0; 5];
    /// let ptr1: *mut i32 = &mut a[1];
    /// let ptr2: *mut i32 = &mut a[3];
    /// unsafe {
    ///     assert_eq!(ptr2.offset_from(ptr1), 2);
    ///     assert_eq!(ptr1.offset_from(ptr2), -2);
    ///     assert_eq!(ptr1.offset(2), ptr2);
    ///     assert_eq!(ptr2.offset(-2), ptr1);
    /// }
    /// ```
    ///
    /// *Incorrect* usage:
    ///
    /// ```rust,no_run
    /// let ptr1 = Box::into_raw(Box::new(0u8));
    /// let ptr2 = Box::into_raw(Box::new(1u8));
    /// let diff = (ptr2 as isize).wrapping_sub(ptr1 as isize);
    /// // Make ptr2_other an "alias" of ptr2, but derived from ptr1.
    /// let ptr2_other = (ptr1 as *mut u8).wrapping_offset(diff);
    /// assert_eq!(ptr2 as usize, ptr2_other as usize);
    /// // Since ptr2_other and ptr2 are derived from pointers to different objects,
    /// // computing their offset is undefined behavior, even though
    /// // they point to the same address!
    /// unsafe {
    ///     let zero = ptr2_other.offset_from(ptr2); // Undefined Behavior
    /// }
    /// ```
    #[stable(feature = "ptr_offset_from", since = "1.47.0")]
    #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
    #[inline(always)]
    pub const unsafe fn offset_from(self, origin: *const T) -> isize
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `offset_from`.
        unsafe { (self as *const T).offset_from(origin) }
    }

    /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
    ///
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
    /// offset of `3 * size_of::<T>()` bytes.
    ///
    /// # Safety
    ///
    /// If any of the following conditions are violated, the result is Undefined
    /// Behavior:
    ///
    /// * Both the starting and resulting pointer must be either in bounds or one
    ///   byte past the end of the same [allocated object].
    ///
    /// * The computed offset, **in bytes**, cannot overflow an `isize`.
    ///
    /// * The offset being in bounds cannot rely on "wrapping around" the address
    ///   space. That is, the infinite-precision sum must fit in a `usize`.
    ///
    /// The compiler and standard library generally tries to ensure allocations
    /// never reach a size where an offset is a concern. For instance, `Vec`
    /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
    /// `vec.as_ptr().add(vec.len())` is always safe.
    ///
    /// Most platforms fundamentally can't even construct such an allocation.
    /// For instance, no known 64-bit platform can ever serve a request
    /// for 263 bytes due to page-table limitations or splitting the address space.
    /// However, some 32-bit and 16-bit platforms may successfully serve a request for
    /// more than `isize::MAX` bytes with things like Physical Address
    /// Extension. As such, memory acquired directly from allocators or memory
    /// mapped files *may* be too large to handle with this function.
    ///
    /// Consider using [`wrapping_add`] instead if these constraints are
    /// difficult to satisfy. The only advantage of this method is that it
    /// enables more aggressive compiler optimizations.
    ///
    /// [`wrapping_add`]: #method.wrapping_add
    /// [allocated object]: crate::ptr#allocated-object
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let s: &str = "123";
    /// let ptr: *const u8 = s.as_ptr();
    ///
    /// unsafe {
    ///     println!("{}", *ptr.add(1) as char);
    ///     println!("{}", *ptr.add(2) as char);
    /// }
    /// ```
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[must_use = "returns a new pointer rather than modifying its argument"]
    #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
    #[inline(always)]
    pub const unsafe fn add(self, count: usize) -> Self
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `offset`.
        unsafe { self.offset(count as isize) }
    }

    /// Calculates the offset from a pointer (convenience for
    /// `.offset((count as isize).wrapping_neg())`).
    ///
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
    /// offset of `3 * size_of::<T>()` bytes.
    ///
    /// # Safety
    ///
    /// If any of the following conditions are violated, the result is Undefined
    /// Behavior:
    ///
    /// * Both the starting and resulting pointer must be either in bounds or one
    ///   byte past the end of the same [allocated object].
    ///
    /// * The computed offset cannot exceed `isize::MAX` **bytes**.
    ///
    /// * The offset being in bounds cannot rely on "wrapping around" the address
    ///   space. That is, the infinite-precision sum must fit in a usize.
    ///
    /// The compiler and standard library generally tries to ensure allocations
    /// never reach a size where an offset is a concern. For instance, `Vec`
    /// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
    /// `vec.as_ptr().add(vec.len()).sub(vec.len())` is always safe.
    ///
    /// Most platforms fundamentally can't even construct such an allocation.
    /// For instance, no known 64-bit platform can ever serve a request
    /// for 263 bytes due to page-table limitations or splitting the address space.
    /// However, some 32-bit and 16-bit platforms may successfully serve a request for
    /// more than `isize::MAX` bytes with things like Physical Address
    /// Extension. As such, memory acquired directly from allocators or memory
    /// mapped files *may* be too large to handle with this function.
    ///
    /// Consider using [`wrapping_sub`] instead if these constraints are
    /// difficult to satisfy. The only advantage of this method is that it
    /// enables more aggressive compiler optimizations.
    ///
    /// [`wrapping_sub`]: #method.wrapping_sub
    /// [allocated object]: crate::ptr#allocated-object
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// let s: &str = "123";
    ///
    /// unsafe {
    ///     let end: *const u8 = s.as_ptr().add(3);
    ///     println!("{}", *end.sub(1) as char);
    ///     println!("{}", *end.sub(2) as char);
    /// }
    /// ```
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[must_use = "returns a new pointer rather than modifying its argument"]
    #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
    #[inline]
    pub const unsafe fn sub(self, count: usize) -> Self
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `offset`.
        unsafe { self.offset((count as isize).wrapping_neg()) }
    }

    /// Calculates the offset from a pointer using wrapping arithmetic.
    /// (convenience for `.wrapping_offset(count as isize)`)
    ///
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
    /// offset of `3 * size_of::<T>()` bytes.
    ///
    /// # Safety
    ///
    /// This operation itself is always safe, but using the resulting pointer is not.
    ///
    /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
    /// be used to read or write other allocated objects.
    ///
    /// In other words, `let z = x.wrapping_add((y as usize) - (x as usize))` does *not* make `z`
    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
    /// `x` and `y` point into the same allocated object.
    ///
    /// Compared to [`add`], this method basically delays the requirement of staying within the
    /// same allocated object: [`add`] is immediate Undefined Behavior when crossing object
    /// boundaries; `wrapping_add` produces a pointer but still leads to Undefined Behavior if a
    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`add`]
    /// can be optimized better and is thus preferable in performance-sensitive code.
    ///
    /// The delayed check only considers the value of the pointer that was dereferenced, not the
    /// intermediate values used during the computation of the final result. For example,
    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
    /// allocated object and then re-entering it later is permitted.
    ///
    /// [`add`]: #method.add
    /// [allocated object]: crate::ptr#allocated-object
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// // Iterate using a raw pointer in increments of two elements
    /// let data = [1u8, 2, 3, 4, 5];
    /// let mut ptr: *const u8 = data.as_ptr();
    /// let step = 2;
    /// let end_rounded_up = ptr.wrapping_add(6);
    ///
    /// // This loop prints "1, 3, 5, "
    /// while ptr != end_rounded_up {
    ///     unsafe {
    ///         print!("{}, ", *ptr);
    ///     }
    ///     ptr = ptr.wrapping_add(step);
    /// }
    /// ```
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[must_use = "returns a new pointer rather than modifying its argument"]
    #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
    #[inline(always)]
    pub const fn wrapping_add(self, count: usize) -> Self
    where
        T: Sized,
    {
        self.wrapping_offset(count as isize)
    }

    /// Calculates the offset from a pointer using wrapping arithmetic.
    /// (convenience for `.wrapping_offset((count as isize).wrapping_neg())`)
    ///
    /// `count` is in units of T; e.g., a `count` of 3 represents a pointer
    /// offset of `3 * size_of::<T>()` bytes.
    ///
    /// # Safety
    ///
    /// This operation itself is always safe, but using the resulting pointer is not.
    ///
    /// The resulting pointer "remembers" the [allocated object] that `self` points to; it must not
    /// be used to read or write other allocated objects.
    ///
    /// In other words, `let z = x.wrapping_sub((x as usize) - (y as usize))` does *not* make `z`
    /// the same as `y` even if we assume `T` has size `1` and there is no overflow: `z` is still
    /// attached to the object `x` is attached to, and dereferencing it is Undefined Behavior unless
    /// `x` and `y` point into the same allocated object.
    ///
    /// Compared to [`sub`], this method basically delays the requirement of staying within the
    /// same allocated object: [`sub`] is immediate Undefined Behavior when crossing object
    /// boundaries; `wrapping_sub` produces a pointer but still leads to Undefined Behavior if a
    /// pointer is dereferenced when it is out-of-bounds of the object it is attached to. [`sub`]
    /// can be optimized better and is thus preferable in performance-sensitive code.
    ///
    /// The delayed check only considers the value of the pointer that was dereferenced, not the
    /// intermediate values used during the computation of the final result. For example,
    /// `x.wrapping_add(o).wrapping_sub(o)` is always the same as `x`. In other words, leaving the
    /// allocated object and then re-entering it later is permitted.
    ///
    /// [`sub`]: #method.sub
    /// [allocated object]: crate::ptr#allocated-object
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// // Iterate using a raw pointer in increments of two elements (backwards)
    /// let data = [1u8, 2, 3, 4, 5];
    /// let mut ptr: *const u8 = data.as_ptr();
    /// let start_rounded_down = ptr.wrapping_sub(2);
    /// ptr = ptr.wrapping_add(4);
    /// let step = 2;
    /// // This loop prints "5, 3, 1, "
    /// while ptr != start_rounded_down {
    ///     unsafe {
    ///         print!("{}, ", *ptr);
    ///     }
    ///     ptr = ptr.wrapping_sub(step);
    /// }
    /// ```
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[must_use = "returns a new pointer rather than modifying its argument"]
    #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
    #[inline]
    pub const fn wrapping_sub(self, count: usize) -> Self
    where
        T: Sized,
    {
        self.wrapping_offset((count as isize).wrapping_neg())
    }

    /// Sets the pointer value to `ptr`.
    ///
    /// In case `self` is a (fat) pointer to an unsized type, this operation
    /// will only affect the pointer part, whereas for (thin) pointers to
    /// sized types, this has the same effect as a simple assignment.
    ///
    /// The resulting pointer will have provenance of `val`, i.e., for a fat
    /// pointer, this operation is semantically the same as creating a new
    /// fat pointer with the data pointer value of `val` but the metadata of
    /// `self`.
    ///
    /// # Examples
    ///
    /// This function is primarily useful for allowing byte-wise pointer
    /// arithmetic on potentially fat pointers:
    ///
    /// ```
    /// #![feature(set_ptr_value)]
    /// # use core::fmt::Debug;
    /// let mut arr: [i32; 3] = [1, 2, 3];
    /// let mut ptr = arr.as_mut_ptr() as *mut dyn Debug;
    /// let thin = ptr as *mut u8;
    /// unsafe {
    ///     ptr = ptr.set_ptr_value(thin.add(8));
    ///     # assert_eq!(*(ptr as *mut i32), 3);
    ///     println!("{:?}", &*ptr); // will print "3"
    /// }
    /// ```
    #[unstable(feature = "set_ptr_value", issue = "75091")]
    #[must_use = "returns a new pointer rather than modifying its argument"]
    #[inline]
    pub fn set_ptr_value(mut self, val: *mut u8) -> Self {
        let thin = &mut self as *mut *mut T as *mut *mut u8;
        // SAFETY: In case of a thin pointer, this operations is identical
        // to a simple assignment. In case of a fat pointer, with the current
        // fat pointer layout implementation, the first field of such a
        // pointer is always the data pointer, which is likewise assigned.
        unsafe { *thin = val };
        self
    }

    /// Reads the value from `self` without moving it. This leaves the
    /// memory in `self` unchanged.
    ///
    /// See [`ptr::read`] for safety concerns and examples.
    ///
    /// [`ptr::read`]: crate::ptr::read()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
    #[inline(always)]
    pub const unsafe fn read(self) -> T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for ``.
        unsafe { read(self) }
    }

    /// Performs a volatile read of the value from `self` without moving it. This
    /// leaves the memory in `self` unchanged.
    ///
    /// Volatile operations are intended to act on I/O memory, and are guaranteed
    /// to not be elided or reordered by the compiler across other volatile
    /// operations.
    ///
    /// See [`ptr::read_volatile`] for safety concerns and examples.
    ///
    /// [`ptr::read_volatile`]: crate::ptr::read_volatile()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub unsafe fn read_volatile(self) -> T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `read_volatile`.
        unsafe { read_volatile(self) }
    }

    /// Reads the value from `self` without moving it. This leaves the
    /// memory in `self` unchanged.
    ///
    /// Unlike `read`, the pointer may be unaligned.
    ///
    /// See [`ptr::read_unaligned`] for safety concerns and examples.
    ///
    /// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
    #[inline(always)]
    pub const unsafe fn read_unaligned(self) -> T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `read_unaligned`.
        unsafe { read_unaligned(self) }
    }

    /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
    /// and destination may overlap.
    ///
    /// NOTE: this has the *same* argument order as [`ptr::copy`].
    ///
    /// See [`ptr::copy`] for safety concerns and examples.
    ///
    /// [`ptr::copy`]: crate::ptr::copy()
    #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub const unsafe fn copy_to(self, dest: *mut T, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy`.
        unsafe { copy(self, dest, count) }
    }

    /// Copies `count * size_of<T>` bytes from `self` to `dest`. The source
    /// and destination may *not* overlap.
    ///
    /// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
    ///
    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
    ///
    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
    #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub const unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
        unsafe { copy_nonoverlapping(self, dest, count) }
    }

    /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
    /// and destination may overlap.
    ///
    /// NOTE: this has the *opposite* argument order of [`ptr::copy`].
    ///
    /// See [`ptr::copy`] for safety concerns and examples.
    ///
    /// [`ptr::copy`]: crate::ptr::copy()
    #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub const unsafe fn copy_from(self, src: *const T, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy`.
        unsafe { copy(src, self, count) }
    }

    /// Copies `count * size_of<T>` bytes from `src` to `self`. The source
    /// and destination may *not* overlap.
    ///
    /// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
    ///
    /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
    ///
    /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
    #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub const unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
        unsafe { copy_nonoverlapping(src, self, count) }
    }

    /// Executes the destructor (if any) of the pointed-to value.
    ///
    /// See [`ptr::drop_in_place`] for safety concerns and examples.
    ///
    /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub unsafe fn drop_in_place(self) {
        // SAFETY: the caller must uphold the safety contract for `drop_in_place`.
        unsafe { drop_in_place(self) }
    }

    /// Overwrites a memory location with the given value without reading or
    /// dropping the old value.
    ///
    /// See [`ptr::write`] for safety concerns and examples.
    ///
    /// [`ptr::write`]: crate::ptr::write()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
    #[inline(always)]
    pub const unsafe fn write(self, val: T)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write`.
        unsafe { write(self, val) }
    }

    /// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
    /// bytes of memory starting at `self` to `val`.
    ///
    /// See [`ptr::write_bytes`] for safety concerns and examples.
    ///
    /// [`ptr::write_bytes`]: crate::ptr::write_bytes()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub unsafe fn write_bytes(self, val: u8, count: usize)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write_bytes`.
        unsafe { write_bytes(self, val, count) }
    }

    /// Performs a volatile write of a memory location with the given value without
    /// reading or dropping the old value.
    ///
    /// Volatile operations are intended to act on I/O memory, and are guaranteed
    /// to not be elided or reordered by the compiler across other volatile
    /// operations.
    ///
    /// See [`ptr::write_volatile`] for safety concerns and examples.
    ///
    /// [`ptr::write_volatile`]: crate::ptr::write_volatile()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub unsafe fn write_volatile(self, val: T)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write_volatile`.
        unsafe { write_volatile(self, val) }
    }

    /// Overwrites a memory location with the given value without reading or
    /// dropping the old value.
    ///
    /// Unlike `write`, the pointer may be unaligned.
    ///
    /// See [`ptr::write_unaligned`] for safety concerns and examples.
    ///
    /// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
    #[inline(always)]
    pub const unsafe fn write_unaligned(self, val: T)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `write_unaligned`.
        unsafe { write_unaligned(self, val) }
    }

    /// Replaces the value at `self` with `src`, returning the old
    /// value, without dropping either.
    ///
    /// See [`ptr::replace`] for safety concerns and examples.
    ///
    /// [`ptr::replace`]: crate::ptr::replace()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[inline(always)]
    pub unsafe fn replace(self, src: T) -> T
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `replace`.
        unsafe { replace(self, src) }
    }

    /// Swaps the values at two mutable locations of the same type, without
    /// deinitializing either. They may overlap, unlike `mem::swap` which is
    /// otherwise equivalent.
    ///
    /// See [`ptr::swap`] for safety concerns and examples.
    ///
    /// [`ptr::swap`]: crate::ptr::swap()
    #[stable(feature = "pointer_methods", since = "1.26.0")]
    #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
    #[inline(always)]
    pub const unsafe fn swap(self, with: *mut T)
    where
        T: Sized,
    {
        // SAFETY: the caller must uphold the safety contract for `swap`.
        unsafe { swap(self, with) }
    }

    /// Computes the offset that needs to be applied to the pointer in order to make it aligned to
    /// `align`.
    ///
    /// If it is not possible to align the pointer, the implementation returns
    /// `usize::MAX`. It is permissible for the implementation to *always*
    /// return `usize::MAX`. Only your algorithm's performance can depend
    /// on getting a usable offset here, not its correctness.
    ///
    /// The offset is expressed in number of `T` elements, and not bytes. The value returned can be
    /// used with the `wrapping_add` method.
    ///
    /// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
    /// beyond the allocation that the pointer points into. It is up to the caller to ensure that
    /// the returned offset is correct in all terms other than alignment.
    ///
    /// # Panics
    ///
    /// The function panics if `align` is not a power-of-two.
    ///
    /// # Examples
    ///
    /// Accessing adjacent `u8` as `u16`
    ///
    /// ```
    /// # fn foo(n: usize) {
    /// # use std::mem::align_of;
    /// # unsafe {
    /// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
    /// let ptr = x.as_ptr().add(n) as *const u8;
    /// let offset = ptr.align_offset(align_of::<u16>());
    /// if offset < x.len() - n - 1 {
    ///     let u16_ptr = ptr.add(offset) as *const u16;
    ///     assert_ne!(*u16_ptr, 500);
    /// } else {
    ///     // while the pointer can be aligned via `offset`, it would point
    ///     // outside the allocation
    /// }
    /// # } }
    /// ```
    #[stable(feature = "align_offset", since = "1.36.0")]
    #[rustc_const_unstable(feature = "const_align_offset", issue = "90962")]
    pub const fn align_offset(self, align: usize) -> usize
    where
        T: Sized,
    {
        if !align.is_power_of_two() {
            panic!("align_offset: align is not a power-of-two");
        }

        fn rt_impl<T>(p: *mut T, align: usize) -> usize {
            // SAFETY: `align` has been checked to be a power of 2 above
            unsafe { align_offset(p, align) }
        }

        const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
            usize::MAX
        }

        // SAFETY:
        // It is permisseble for `align_offset` to always return `usize::MAX`,
        // algorithm correctness can not depend on `align_offset` returning non-max values.
        //
        // As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
        unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
    }
}

#[lang = "mut_slice_ptr"]
impl<T> *mut [T] {
    /// Returns the length of a raw slice.
    ///
    /// The returned value is the number of **elements**, not the number of bytes.
    ///
    /// This function is safe, even when the raw slice cannot be cast to a slice
    /// reference because the pointer is null or unaligned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(slice_ptr_len)]
    /// use std::ptr;
    ///
    /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
    /// assert_eq!(slice.len(), 3);
    /// ```
    #[inline(always)]
    #[unstable(feature = "slice_ptr_len", issue = "71146")]
    #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
    pub const fn len(self) -> usize {
        metadata(self)
    }

    /// Returns a raw pointer to the slice's buffer.
    ///
    /// This is equivalent to casting `self` to `*mut T`, but more type-safe.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #![feature(slice_ptr_get)]
    /// use std::ptr;
    ///
    /// let slice: *mut [i8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 3);
    /// assert_eq!(slice.as_mut_ptr(), 0 as *mut i8);
    /// ```
    #[inline(always)]
    #[unstable(feature = "slice_ptr_get", issue = "74265")]
    #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")]
    pub const fn as_mut_ptr(self) -> *mut T {
        self as *mut T
    }

    /// Returns a raw pointer to an element or subslice, without doing bounds
    /// checking.
    ///
    /// Calling this method with an out-of-bounds index or when `self` is not dereferencable
    /// is *[undefined behavior]* even if the resulting pointer is not used.
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(slice_ptr_get)]
    ///
    /// let x = &mut [1, 2, 4] as *mut [i32];
    ///
    /// unsafe {
    ///     assert_eq!(x.get_unchecked_mut(1), x.as_mut_ptr().add(1));
    /// }
    /// ```
    #[unstable(feature = "slice_ptr_get", issue = "74265")]
    #[inline(always)]
    pub unsafe fn get_unchecked_mut(self, index: I) -> *mut I::Output
    where
        I: SliceIndex<[T]>,
    {
        // SAFETY: the caller ensures that `self` is dereferencable and `index` in-bounds.
        unsafe { index.get_unchecked_mut(self) }
    }

    /// Returns `None` if the pointer is null, or else returns a shared slice to
    /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require
    /// that the value has to be initialized.
    ///
    /// For the mutable counterpart see [`as_uninit_slice_mut`].
    ///
    /// [`as_ref`]: #method.as_ref-1
    /// [`as_uninit_slice_mut`]: #method.as_uninit_slice_mut
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that *either* the pointer is null *or*
    /// all of the following is true:
    ///
    /// * The pointer must be [valid] for reads for `ptr.len() * mem::size_of::<T>()` many bytes,
    ///   and it must be properly aligned. This means in particular:
    ///
    ///     * The entire memory range of this slice must be contained within a single [allocated object]!
    ///       Slices can never span across multiple allocated objects.
    ///
    ///     * The pointer must be aligned even for zero-length slices. One
    ///       reason for this is that enum layout optimizations may rely on references
    ///       (including slices of any length) being aligned and non-null to distinguish
    ///       them from other data. You can obtain a pointer that is usable as `data`
    ///       for zero-length slices using [`NonNull::dangling()`].
    ///
    /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
    ///   See the safety documentation of [`pointer::offset`].
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, for the duration of this lifetime, the memory the pointer points to must
    ///   not get mutated (except inside `UnsafeCell`).
    ///
    /// This applies even if the result of this method is unused!
    ///
    /// See also [`slice::from_raw_parts`][].
    ///
    /// [valid]: crate::ptr#safety
    /// [allocated object]: crate::ptr#allocated-object
    #[inline]
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
    pub unsafe fn as_uninit_slice<'a>(self) -> Option<&'a [MaybeUninit<T>]> {
        if self.is_null() {
            None
        } else {
            // SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
            Some(unsafe { slice::from_raw_parts(self as *const MaybeUninit<T>, self.len()) })
        }
    }

    /// Returns `None` if the pointer is null, or else returns a unique slice to
    /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require
    /// that the value has to be initialized.
    ///
    /// For the shared counterpart see [`as_uninit_slice`].
    ///
    /// [`as_mut`]: #method.as_mut
    /// [`as_uninit_slice`]: #method.as_uninit_slice-1
    ///
    /// # Safety
    ///
    /// When calling this method, you have to ensure that *either* the pointer is null *or*
    /// all of the following is true:
    ///
    /// * The pointer must be [valid] for reads and writes for `ptr.len() * mem::size_of::<T>()`
    ///   many bytes, and it must be properly aligned. This means in particular:
    ///
    ///     * The entire memory range of this slice must be contained within a single [allocated object]!
    ///       Slices can never span across multiple allocated objects.
    ///
    ///     * The pointer must be aligned even for zero-length slices. One
    ///       reason for this is that enum layout optimizations may rely on references
    ///       (including slices of any length) being aligned and non-null to distinguish
    ///       them from other data. You can obtain a pointer that is usable as `data`
    ///       for zero-length slices using [`NonNull::dangling()`].
    ///
    /// * The total size `ptr.len() * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
    ///   See the safety documentation of [`pointer::offset`].
    ///
    /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
    ///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
    ///   In particular, for the duration of this lifetime, the memory the pointer points to must
    ///   not get accessed (read or written) through any other pointer.
    ///
    /// This applies even if the result of this method is unused!
    ///
    /// See also [`slice::from_raw_parts_mut`][].
    ///
    /// [valid]: crate::ptr#safety
    /// [allocated object]: crate::ptr#allocated-object
    #[inline]
    #[unstable(feature = "ptr_as_uninit", issue = "75402")]
    pub unsafe fn as_uninit_slice_mut<'a>(self) -> Option<&'a mut [MaybeUninit<T>]> {
        if self.is_null() {
            None
        } else {
            // SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
            Some(unsafe { slice::from_raw_parts_mut(self as *mut MaybeUninit<T>, self.len()) })
        }
    }
}

// Equality for pointers
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> PartialEq for *mut T {
    #[inline(always)]
    fn eq(&self, other: &*mut T) -> bool {
        *self == *other
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Eq for *mut T {}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Ord for *mut T {
    #[inline]
    fn cmp(&self, other: &*mut T) -> Ordering {
        if self < other {
            Less
        } else if self == other {
            Equal
        } else {
            Greater
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> PartialOrd for *mut T {
    #[inline(always)]
    fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> {
        Some(self.cmp(other))
    }

    #[inline(always)]
    fn lt(&self, other: &*mut T) -> bool {
        *self < *other
    }

    #[inline(always)]
    fn le(&self, other: &*mut T) -> bool {
        *self <= *other
    }

    #[inline(always)]
    fn gt(&self, other: &*mut T) -> bool {
        *self > *other
    }

    #[inline(always)]
    fn ge(&self, other: &*mut T) -> bool {
        *self >= *other
    }
}

redpajama_set_name: RedPajamaGithub


text:
package terminals;

import problem.StarCraftBuildOrderProblem;
import ec.*;
import ec.gp.*;
import ec.util.*;
import gPDataTypes.IntData;

public class ExistingZelots extends GPNode
{
public String toString() { return "ExistingZelot"; }

public int expectedChildren() { return 0; }

public void eval(final EvolutionState state,
                 final int thread,
                 final GPData input,
                 final ADFStack stack,
                 final GPIndividual individual,
                 final Problem problem)
    {
	IntData rd = ((IntData)(input));
    rd.x = ((StarCraftBuildOrderProblem)problem).existingZelots;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Documentation for C++/SDL 2.0 Tile Engine: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Documentation for C++/SDL 2.0 Tile Engine

Making a simple tile based engine

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Namespaces Functions Variables Enumerations

Player Member List

This is the complete list of members for Player, including all inherited members.

Box()	GameObject	inline

CheckMouseOver(const Vector2f &pos)	GameObject	virtual

Draw(Camera *cam=nullptr)	Player	virtual

GameObject() (defined in GameObject)	GameObject

GetMouseOver()	GameObject

HasTag(std::string tag)	GameObject

Load(Json::Value val)	Player	virtual

mImage (defined in GameObject)	GameObject	protected

Move(float deltaT)	Player	virtual

mPhysics	GameObject	protected

mTag	GameObject	protected

OnMouseDown()	GameObject	virtual

OnMouseEnter()	GameObject	virtual

OnMouseExit()	GameObject	virtual

OnMouseUp()	GameObject	virtual

Player() (defined in Player)	Player

Save()	Player	virtual

SetCollisionMap(CollisionMap map)	GameObject	inline

Update()	Player	virtual

~GameObject() (defined in GameObject)	GameObject	inlinevirtual

~Player() (defined in Player)	Player

<address class="footer">
Generated on Fri Aug 10 2012 14:02:31 for Documentation for C++/SDL 2.0 Tile Engine by

 1.8.1.2
</address>


text:
@implementation CollapseClick
@synthesize CollapseClickDelegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.isClickedArray = [[NSMutableArray alloc] initWithCapacity:[CollapseClickDelegate numberOfCellsForCollapseClick]];
        self.dataArray = [[NSMutableArray alloc] initWithCapacity:[CollapseClickDelegate numberOfCellsForCollapseClick]];
        [self reloadCollapseClick];
    }
    return self;
}

#pragma mark - Load Data
-(void)reloadCollapseClick {
    // Set Up: Height
    float totalHeight = 0;

    // If Arrays aren't Init'd, Init them
    if (!(self.isClickedArray)) {
        self.isClickedArray = [[NSMutableArray alloc] initWithCapacity:[CollapseClickDelegate numberOfCellsForCollapseClick]];
    }

    if (!(self.dataArray)) {
        self.dataArray = [[NSMutableArray alloc] initWithCapacity:[CollapseClickDelegate numberOfCellsForCollapseClick]];
    }

    // Make sure they are clear
    [self.isClickedArray removeAllObjects];
    [self.dataArray removeAllObjects];

    // Remove all subviews
    for (UIView *subview in self.subviews) {
        [subview removeFromSuperview];
    }

    // Add cells
    for (int xx = 0; xx < [CollapseClickDelegate numberOfCellsForCollapseClick]; xx++) {
        // Create Cell
        CollapseClickCell *cell = [CollapseClickCell newCollapseClickCellWithTitle:[CollapseClickDelegate titleForCollapseClickAtIndex:xx] index:xx content:[CollapseClickDelegate viewForCollapseClickContentViewAtIndex:xx]];

        // Set cell.TitleView's backgroundColor
//        if ([(id)CollapseClickDelegate respondsToSelector:@selector(colorForCollapseClickTitleViewAtIndex:)]) {
//            cell.TitleView.backgroundColor = [CollapseClickDelegate colorForCollapseClickTitleViewAtIndex:xx];
//        }
//        else {
//            cell.TitleView.backgroundColor = [UIColor colorWithWhite:0.4 alpha:1.0];
//        }

        // Set cell.TitleLabel's Color
//        if ([(id)CollapseClickDelegate respondsToSelector:@selector(colorForTitleLabelAtIndex:)]) {
//            cell.TitleLabel.textColor = [CollapseClickDelegate colorForTitleLabelAtIndex:xx];
//        }
//        else {
//            cell.TitleLabel.textColor = [UIColor whiteColor];
//        }

        // Set cell.TitleArrow's Color
//        if ([(id)CollapseClickDelegate respondsToSelector:@selector(colorForTitleArrowAtIndex:)]) {
//            [cell.TitleArrow drawWithColor:[CollapseClickDelegate colorForTitleArrowAtIndex:xx]];
//        }
//        else {
//            [cell.TitleArrow drawWithColor:[UIColor colorWithWhite:0.0 alpha:0.35]];
//        }

        // Set cell.ContentView's size
        cell.ContentView.frame = CGRectMake(0, kCCHeaderHeight + kCCPad, self.frame.size.width, cell.ContentView.frame.size.height);

        // Set cell's size
        cell.frame = CGRectMake(0, totalHeight, self.frame.size.width, kCCHeaderHeight);

        // Add target to Button
        [cell.TitleButton addTarget:self action:@selector(didSelectCollapseClickButton:) forControlEvents:UIControlEventTouchUpInside];

        // Add cell
        [self addSubview:cell];

        // Add to DataArray & isClickedArray
        [self.isClickedArray addObject:[NSNumber numberWithBool:NO]];
        [self.dataArray addObject:cell];

        // Calculate totalHeight
        totalHeight += kCCHeaderHeight + kCCPad;
    }

    // Set self's ContentSize and ContentOffset
    [self setContentSize:CGSizeMake(self.frame.size.width, totalHeight)];
    [self setContentOffset:CGPointZero];
}

#pragma mark - Reposition Cells
-(void)repositionCollapseClickCellsBelowIndex:(int)index withOffset:(float)offset {
    for (int yy = index+1; yy < self.dataArray.count; yy++) {
        CollapseClickCell *cell = [self.dataArray objectAtIndex:yy];
        cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y + offset, cell.frame.size.width, cell.frame.size.height);
    }

    // Resize self.ContentSize
    CollapseClickCell *lastCell = [self.dataArray objectAtIndex:self.dataArray.count - 1];
    [self setContentSize:CGSizeMake(self.frame.size.width, lastCell.frame.origin.y + lastCell.frame.size.height + kCCPad)];
}

#pragma mark - Did Click
-(void)didSelectCollapseClickButton:(UIButton *)titleButton {
    BOOL isOpen = NO;

    // Cell is OPEN -> CLOSED
    if ([[self.isClickedArray objectAtIndex:titleButton.tag] boolValue] == YES) {
        [self closeCollapseClickCellAtIndex:titleButton.tag animated:YES];
    }
    // Cell is CLOSED -> OPEN
    else {
        [self openCollapseClickCellAtIndex:titleButton.tag animated:YES];
        isOpen = YES;
    }

    // Call delegate method
    if ([(id)CollapseClickDelegate respondsToSelector:@selector(didClickCollapseClickCellAtIndex:isNowOpen:)]) {
        [CollapseClickDelegate didClickCollapseClickCellAtIndex:titleButton.tag isNowOpen:isOpen];
    }
}

#pragma mark - Open CollapseClickCell
-(void)openCollapseClickCellAtIndex:(int)index animated:(BOOL)animated {
    // Check if it's not open first
    if ([[self.isClickedArray objectAtIndex:index] boolValue] != YES) {
        float duration = 0;
        if (animated) {
            duration = 0.25;
        }
        [UIView animateWithDuration:duration animations:^{
            // Resize Cell
            CollapseClickCell *cell = [self.dataArray objectAtIndex:index];
            cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, cell.ContentView.frame.origin.y + cell.ContentView.frame.size.height + kCCPad);

            // Change Arrow orientation
            CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI/2);
            cell.TitleArrow.transform = transform;

            // Change isClickedArray
            [self.isClickedArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:YES]];

            // Reposition all CollapseClickCells below Cell
            [self repositionCollapseClickCellsBelowIndex:index withOffset:cell.ContentView.frame.size.height + kCCPad];
        }];
    }
}

-(void)openCollapseClickCellsWithIndexes:(NSArray *)indexArray animated:(BOOL)animated {
    // This works off of NSNumbers for each Index
    for (int ii = 0; ii < indexArray.count; ii++) {
        id indexID = indexArray[ii];
        if ([indexID isKindOfClass:[NSNumber class]]) {
            [self openCollapseClickCellAtIndex:[indexID intValue] animated:animated];
        }
    }

}

#pragma mark - Close CollapseClickCell
-(void)closeCollapseClickCellAtIndex:(int)index animated:(BOOL)animated {
    // Check if it's open first
    if ([[self.isClickedArray objectAtIndex:index] boolValue] == YES) {
        float duration = 0;
        if (animated) {
            duration = 0.25;
        }
        [UIView animateWithDuration:duration animations:^{
            // Resize Cell
            CollapseClickCell *cell = [self.dataArray objectAtIndex:index];
            cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, kCCHeaderHeight);

            // Change Arrow orientation
            CGAffineTransform transform = CGAffineTransformMakeRotation(0);
            cell.TitleArrow.transform = transform;

            // Change isClickedArray
            [self.isClickedArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:NO]];

            // Reposition all CollapseClickCells below Cell
            [self repositionCollapseClickCellsBelowIndex:index withOffset:-1*(cell.ContentView.frame.size.height + kCCPad)];
        }];
    }
}

-(void)closeCollapseClickCellsWithIndexes:(NSArray *)indexArray animated:(BOOL)animated {
    // This works off of NSNumbers for each Index
    for (int ii = 0; ii < indexArray.count; ii++) {
        id indexID = indexArray[ii];
        if ([indexID isKindOfClass:[NSNumber class]]) {
            [self closeCollapseClickCellAtIndex:[indexID intValue] animated:animated];
        }
    }
}

#pragma mark - CollapseClickCell for Index
-(CollapseClickCell *)collapseClickCellForIndex:(int)index {
    if ([[self.dataArray objectAtIndex:index] isKindOfClass:[CollapseClickCell class]]) {
        return [self.dataArray objectAtIndex:index];
    }

    return nil;
}

#pragma mark - Scroll To Cell
-(void)scrollToCollapseClickCellAtIndex:(int)index animated:(BOOL)animated {
    CollapseClickCell *cell = [self.dataArray objectAtIndex:index];
    [self setContentOffset:CGPointMake(cell.frame.origin.x, cell.frame.origin.y) animated:animated];
}

#pragma mark - Content View for Cell
-(UIView *)contentViewForCellAtIndex:(int)index {
    CollapseClickCell *cell = [self.subviews objectAtIndex:index];
    return cell.ContentView;
}

@end


text:
DIR=$(cd `dirname $0` && pwd)
source $DIR/include.sh

args="echo hello there"

project=$2
if [ "" == "$2" ] ; then
    project="test"
fi

#escape the string for xml
xmlargs=$($XMLSTARLET esc "$args")
xmlproj=$($XMLSTARLET esc "$project")

#produce job.xml content corresponding to the dispatch request
cat > $DIR/temp.out <<END
<joblist>
   <job>
      <name>cli job</name>
      <group>api-test</group>
      <description></description>
      <loglevel>INFO</loglevel>
      <context>
          <project>$xmlproj</project>
      </context>
      <dispatch>
        <threadcount>1</threadcount>
        <keepgoing>true</keepgoing>
      </dispatch>
      <sequence>
        <command>
        <exec>$xmlargs</exec>
        </command>
      </sequence>
   </job>
</joblist>

END

# now submit req
runurl="${APIURL}/project/$project/jobs/import"

echo "TEST: import RunDeck Jobs in jobs.xml format (multipart request)"

params=""

# specify the file for upload with curl, named "xmlBatch"
ulopts="-F xmlBatch=@$DIR/temp.out"

# get listing
docurl $ulopts  ${runurl}?${params} > $DIR/curl.out
if [ 0 != $? ] ; then
    errorMsg "ERROR: failed query request"
    exit 2
fi

#result will contain list of failed and succeeded jobs, in this
#case there should only be 1 failed or 1 succeeded since we submit only 1

failedcount=$(xmlsel "//failed/@count" $DIR/curl.out)
succount=$(xmlsel "//succeeded/@count" $DIR/curl.out)
skipcount=$(xmlsel "//skipped/@count" $DIR/curl.out)

if [ "1" != "$succount" ] ; then
    errorMsg  "Upload was not successful."
    exit 2
fi

# verify results
jid=$(xmlsel "//succeeded/job/id" $DIR/curl.out)
jname=$(xmlsel "//succeeded/job/name" $DIR/curl.out)
jgroup=$(xmlsel "//succeeded/job/group" $DIR/curl.out)
jproj=$(xmlsel "//succeeded/job/project" $DIR/curl.out)

assert "cli job" "$jname" "Wrong job name: $jname"
assert "api-test" "$jgroup" "Wrong job group: $jgroup"
assert "$project" "$jproj" "Wrong job project: $jproj"

if [ -z "$jid" ] ; then
    errorMsg "Expected job id in result: $jid"
    exit 2
fi

echo "OK"

# test upload via form content instead of multipart file

echo "TEST: import RunDeck Jobs in jobs.xml format (urlencode)"

params=""

# specify the file for upload with curl, named "xmlBatch"
ulopts="--data-urlencode xmlBatch@$DIR/temp.out"

# get listing
docurl $ulopts  ${runurl}?${params} > $DIR/curl.out
if [ 0 != $? ] ; then
    errorMsg "ERROR: failed query request"
    exit 2
fi

#result will contain list of failed and succeeded jobs, in this
#case there should only be 1 failed or 1 succeeded since we submit only 1

failedcount=$(xmlsel "//failed/@count" $DIR/curl.out)
succount=$(xmlsel "//succeeded/@count" $DIR/curl.out)
skipcount=$(xmlsel "//skipped/@count" $DIR/curl.out)

if [ "1" != "$succount" ] ; then
    errorMsg  "Upload was not successful."
    exit 2
fi

# verify results
jid=$(xmlsel "//succeeded/job/id" $DIR/curl.out)
jname=$(xmlsel "//succeeded/job/name" $DIR/curl.out)
jgroup=$(xmlsel "//succeeded/job/group" $DIR/curl.out)
jproj=$(xmlsel "//succeeded/job/project" $DIR/curl.out)

assert "cli job" "$jname" "Wrong job name: $jname"
assert "api-test" "$jgroup" "Wrong job group: $jgroup"
assert "$project" "$jproj" "Wrong job project: $jproj"

if [ -z "$jid" ] ; then
    errorMsg "Expected job id in result: $jid"
    exit 2
fi

echo "OK"

rm $DIR/curl.out
rm $DIR/temp.out


text:
module Preservation

  # Builder
  #
  module Builder

    # Build wget string
    #
    # @param username [String]
    # @param password [String]
    # @param file_url [String]
    # @return [String]
    def self.build_wget(username, password, file_url)
      # construct wget command with parameters
      wget_str = ''
      wget_str << 'wget'
      wget_str << ' '
      wget_str << '--user'
      wget_str << ' '
      wget_str << username
      wget_str << ' '
      wget_str << '--password'
      wget_str << ' '
      wget_str << '"' + password + '"'
      wget_str << ' '
      wget_str << file_url
      wget_str << ' '
      wget_str << '--no-check-certificate'
      wget_str
    end

    # Build directory name
    #
    # @param metadata_record [Hash]
    # @param directory_name_scheme [Symbol]
    # @return [String]
    def self.build_directory_name(metadata_record, directory_name_scheme)
      doi = metadata_record[:doi]
      uuid = metadata_record[:uuid]
      title = metadata_record[:title].strip.gsub(' ', '-').gsub('/', '-')
      time = Time.new
      date = time.strftime("%Y-%m-%d")
      time = time.strftime("%H:%M:%S")
      join_str = '-----'

      case directory_name_scheme
        when :uuid_title
          [uuid, title].join(join_str)
        when :title_uuid
          [title, uuid].join(join_str)
        when :date_uuid_title
          [date, uuid, title].join(join_str)
        when :date_title_uuid
          [date, title, uuid].join(join_str)
        when :date_time_uuid
          [date, time, uuid].join(join_str)
        when :date_time_title
          [date, time, title].join(join_str)
        when :date_time_uuid_title
          [date, time, uuid, title].join(join_str)
        when :date_time_title_uuid
          [date, time, title, uuid].join(join_str)
        when :uuid
          uuid
        when :doi
          if doi.nil? || doi.empty?
            return ''
          end
          doi.gsub('/', '-')
        when :doi_short
          if doi.nil? || doi.empty?
            return ''
          end
          doi_short_to_remove = 'http://dx.doi.org/'
          short = doi.gsub(doi_short_to_remove, '')
          short.gsub!('/', '-')
        else
          uuid
      end
    end

  end

end


text:
<?php

/**
 * Doctrine_Ticket_DC64_TestCase
 *
 * @package     Doctrine
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.doctrine-project.org
 * @since       1.0
 * @version     $Revision$
 */
class Doctrine_Ticket_DC64_TestCase extends Doctrine_UnitTestCase
{
    public function prepareTables()
    {
        $this->tables[] = 'Ticket_DC64_Article';
        parent::prepareTables();
    }

    public function testTicket()
    {
        $article = new Ticket_DC64_Article();
        $article->title = 'testing provider';
        $article->content = 'testing';
        $article->save();
        $this->assertEqual($article->slug, 'jwage_testing_provider');

        $article = new Ticket_DC64_Article();
        $article->title = 'testing provider';
        $article->content = 'testing';
        $article->save();
        $this->assertEqual($article->slug, 'jwage_testing_provider_1');

        $article = new Ticket_DC64_Article();
        $article->title = 'testing provider';
        $article->content = 'testing';
        $article->save();
        $this->assertEqual($article->slug, 'jwage_testing_provider_2');
    }
}

class Ticket_DC64_Article extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('title', 'string', 255);
        $this->hasColumn('content', 'clob');
    }

    public function setUp()
    {
        $this->actAs('Sluggable', array(
            'provider' => array($this, 'provideSlug'),
            'builder' => array($this, 'formatSlug')
        ));
    }

    public function __toString()
    {
        return $this->title;
    }

    public static function formatSlug($slug)
    {
        return str_replace('-', '_', Doctrine_Inflector::urlize($slug));
    }

    public static function provideSlug(Doctrine_Record $record)
    {
        return 'jwage ' . $record->title;
    }
}


text:
<icecast>
    <!-- location and admin are two arbitrary strings that are e.g. visible
         on the server info page of the icecast web interface
         (server_version.xsl). -->
    <location>Earth</location>
    <admin>lara.resc@gmail.com</admin>

    <limits>
        <clients>100</clients>
        <sources>2</sources>
        <threadpool>5</threadpool>
        <queue-size>524288</queue-size>
        <client-timeout>30</client-timeout>
        <header-timeout>15</header-timeout>
        <source-timeout>10</source-timeout>
        <!-- If enabled, this will provide a burst of data when a client
             first connects, thereby significantly reducing the startup
             time for listeners that do substantial buffering. However,
             it also significantly increases latency between the source
             client and listening client.  For low-latency setups, you
             might want to disable this. -->
        <burst-on-connect>1</burst-on-connect>
        <!-- same as burst-on-connect, but this allows for being more
             specific on how much to burst. Most people won't need to
             change from the default 64k. Applies to all mountpoints  -->
        <burst-size>65535</burst-size>
    </limits>

    <authentication>
        <!-- Sources log in with username 'source' -->
        <source-password>sourcepass</source-password>
        <!-- Relays log in username 'relay' -->
        <relay-password>casita</relay-password>

        <!-- Admin logs in with the username given below -->
        <admin-user>admin</admin-user>
        <admin-password>admin</admin-password>
    </authentication>

    <!-- set the mountpoint for a shoutcast source to use, the default if not
         specified is /stream but you can change it here if an alternative is
         wanted or an extension is required
    <shoutcast-mount>/live.nsv</shoutcast-mount>
    -->

    <!-- Uncomment this if you want directory listings -->
    <!--
    <directory>
        <yp-url-timeout>15</yp-url-timeout>
        <yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
    </directory>
     -->

    <!-- This is the hostname other people will use to connect to your server.
    It affects mainly the urls generated by Icecast for playlists and yp
    listings. -->
    <hostname>localhost</hostname>

    <!-- You may have multiple <listener> elements -->
    <listen-socket>
        <port>8000</port>
        <!-- <bind-address>127.0.0.1</bind-address> -->
        <!-- <shoutcast-mount>/stream</shoutcast-mount> -->
    </listen-socket>
    <!--
    <listen-socket>
        <port>8001</port>
    </listen-socket>
    -->

    <!--<master-server>127.0.0.1</master-server>-->
    <!--<master-server-port>8001</master-server-port>-->
    <!--<master-update-interval>120</master-update-interval>-->
    <!--<master-password>hackme</master-password>-->

    <!-- setting this makes all relays on-demand unless overridden, this is
         useful for master relays which do not have <relay> definitions here.
         The default is 0 -->
    <!--<relays-on-demand>1</relays-on-demand>-->

    <!--
    <relay>
        <server>127.0.0.1</server>
        <port>8001</port>
        <mount>/example.ogg</mount>
        <local-mount>/different.ogg</local-mount>
        <on-demand>0</on-demand>

        <relay-shoutcast-metadata>0</relay-shoutcast-metadata>
    </relay>
    -->

    <!-- Only define a <mount> section if you want to use advanced options,
         like alternative usernames or passwords
    <mount>
        <mount-name>/example-complex.ogg</mount-name>

        <username>othersource</username>
        <password>hackmemore</password>

        <max-listeners>1</max-listeners>
        <dump-file>/tmp/dump-example1.ogg</dump-file>
        <burst-size>65536</burst-size>
        <fallback-mount>/example2.ogg</fallback-mount>
        <fallback-override>1</fallback-override>
        <fallback-when-full>1</fallback-when-full>
        <intro>/example_intro.ogg</intro>
        <hidden>1</hidden>
        <no-yp>1</no-yp>
        <authentication type="htpasswd">
                <option name="filename" value="myauth"/>
                <option name="allow_duplicate_users" value="0"/>
        </authentication>
        <on-connect>/home/icecast/bin/stream-start</on-connect>
        <on-disconnect>/home/icecast/bin/stream-stop</on-disconnect>
    </mount>

    <mount>
        <mount-name>/auth_example.ogg</mount-name>
        <authentication type="url">
            <option name="mount_add"       value="http://myauthserver.net/notify_mount.php"/>
            <option name="mount_remove"    value="http://myauthserver.net/notify_mount.php"/>
            <option name="listener_add"    value="http://myauthserver.net/notify_listener.php"/>
            <option name="listener_remove" value="http://myauthserver.net/notify_listener.php"/>
        </authentication>
    </mount>

    -->

    <fileserve>1</fileserve>

    <paths>
		<!-- basedir is only used if chroot is enabled -->
        <basedir>/usr/share/icecast2</basedir>

        <!-- Note that if <chroot> is turned on below, these paths must both
             be relative to the new root, not the original root -->
        <logdir>/var/log/icecast2</logdir>
        <webroot>/usr/share/icecast2/web</webroot>
        <adminroot>/usr/share/icecast2/admin</adminroot>
        <!-- <pidfile>/usr/share/icecast2/icecast.pid</pidfile> -->

        <!-- Aliases: treat requests for 'source' path as being for 'dest' path
             May be made specific to a port or bound address using the "port"
             and "bind-address" attributes.
          -->
        <!--
        <alias source="/foo" destination="/bar"/>
          -->
        <!-- Aliases: can also be used for simple redirections as well,
             this example will redirect all requests for http://server:port/ to
             the status page
          -->
        <alias source="/" destination="/status.xsl"/>
    </paths>

    <logging>
        <accesslog>access.log</accesslog>
        <errorlog>error.log</errorlog>
        <!-- <playlistlog>playlist.log</playlistlog> -->
      	<loglevel>3</loglevel> <!-- 4 Debug, 3 Info, 2 Warn, 1 Error -->
      	<logsize>10000</logsize> <!-- Max size of a logfile -->
        <!-- If logarchive is enabled (1), then when logsize is reached
             the logfile will be moved to [error|access|playlist].log.DATESTAMP,
             otherwise it will be moved to [error|access|playlist].log.old.
             Default is non-archive mode (i.e. overwrite)
        -->
        <!-- <logarchive>1</logarchive> -->
    </logging>

    <security>
        <chroot>0</chroot>
        <!--
        <changeowner>
            <user>nobody</user>
            <group>nogroup</group>
        </changeowner>
        -->
    </security>
</icecast>


text:
"""
Flask-DBConfig
--------------

Configure your Flask application from a local SQLite database, and never have
to ship with a config file again!

Links
`````

* `documentation <http://packages.python.org/Flask-DBConfig>`_

"""
from distutils.core import setup

setup(
    name='Flask-DBConfig',
    version='0.3.12',
    url='https://github.com/tedw4rd/flask-db-configuration/',
    license='MIT',
    author='Ted Aronson',
    author_email='ted.aronson@gmail.com',
    description='Configure Flask applications from a local DB',
    long_description=__doc__,
    packages=['flaskext'],
    namespace_packages=['flaskext'],
    package_dir={'flaskext': 'flaskext'},
    package_data={'flaskext': ['static/**/*', 'templates/*']},
    data_files=[],
    platforms='any',
    install_requires=[
        'Flask'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)


text:
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

module Domgen
  FacetManager.facet(:gwt_rpc => [:gwt, :jackson, :keycloak]) do |facet|
    facet.enhance(Repository) do
      include Domgen::Java::BaseJavaGenerator
      include Domgen::Java::JavaClientServerApplication

      attr_writer :module_name

      def module_name
        @module_name || Reality::Naming.underscore(repository.name)
      end

      attr_writer :base_api_url

      def base_api_url
        @base_api_url || 'api/rpc'
      end

      attr_writer :api_url

      def api_url
        @api_url || "#{self.base_api_url}/#{repository.gwt.module_name}"
      end

      java_artifact :default_callback, :service, :client, :gwt_rpc, '#{repository.name}DefaultAsyncCallback'
      java_artifact :async_callback_adapter, :service, :client, :gwt_rpc, '#{repository.name}AsyncCallbackAdapter'
      java_artifact :rpc_request_builder, :ioc, :client, :gwt_rpc, '#{repository.name}RpcRequestBuilder'
      java_artifact :rpc_services_sting_fragment, :ioc, :client, :gwt_rpc, '#{repository.name}GwtRpcServicesFragment'
      java_artifact :mock_rpc_services_sting_fragment, :test, :client, :gwt_rpc, 'Mock#{repository.name}GwtRpcServicesFragment', :sub_package => 'util'

      java_artifact :code_server_config, :service, :server, :gwt_rpc, '#{repository.name}CodeServerConfig'
      java_artifact :code_server_config_resources, :service, :server, :gwt_rpc, '#{repository.name}CodeServerConfigResources'

      def client_ioc_package
        repository.gwt.client_ioc_package
      end

      attr_writer :server_servlet_package

      def server_servlet_package
        @server_servlet_package || "#{server_package}.servlet"
      end

      attr_writer :services_module_name

      attr_writer :keycloak_client

      def keycloak_client
        @keycloak_client || (repository.application? && !repository.application.user_experience? ? repository.keycloak.default_client.key : :api)
      end

      def pre_verify
        if repository.keycloak.has_local_auth_service?
          client =
            repository.keycloak.client_by_key?(self.keycloak_client) ?
              repository.keycloak.client_by_key(self.keycloak_client) :
              repository.keycloak.client(self.keycloak_client)
          client.bearer_only = true
          client.redirect_uris.clear
          client.web_origins.clear
          client.protected_url_patterns << "/#{base_api_url}/*"
        end
        repository.gwt.sting_test_includes << repository.gwt_rpc.qualified_mock_rpc_services_sting_fragment_name
      end

      protected

      def facet_key
        :gwt
      end
    end

    facet.enhance(DataModule) do
      include Domgen::Java::ClientServerJavaPackage

      attr_writer :server_servlet_package

      def server_servlet_package
        @server_servlet_package || resolve_package(:server_servlet_package)
      end

      attr_writer :api_url

      def api_url
        @api_url || (data_module.name == data_module.repository.name) ? data_module.repository.gwt_rpc.api_url : "#{data_module.repository.gwt_rpc.api_url}/#{Reality::Naming.underscore(data_module.name)}"
      end

      protected

      def facet_key
        :gwt_rpc
      end
    end

    facet.enhance(Service) do
      include Domgen::Java::BaseJavaGenerator

      attr_writer :servlet_path

      def servlet_path
        @servlet_path || service.name
      end

      attr_writer :api_url

      def api_url
        @api_url || "#{service.data_module.gwt_rpc.api_url}/#{self.servlet_path}"
      end

      attr_writer :rpc_prefix

      def rpc_prefix
        @rpc_prefix || 'GwtRpc'
      end

      attr_writer :default_callback

      def default_callback?
        @default_callback.nil? ? true : @default_callback
      end

      attr_writer :service_name

      def service_name
        @service_name || service.name
      end

      def qualified_service_name
        "#{parent.parent.gwt_rpc.client_service_package}.#{service_name}"
      end

      java_artifact :rpc_service, :service, :shared, :gwt_rpc, '#{rpc_prefix}#{service.name}'
      java_artifact :async_rpc_service, :service, :shared, :gwt_rpc, '#{rpc_service_name}Async'
      java_artifact :servlet, :servlet, :server, :gwt_rpc, '#{rpc_service_name}Servlet'
    end

    facet.enhance(Method) do
      def name
        Reality::Naming.camelize(method.name)
      end

      attr_writer :cancelable

      def cancelable?
        @cancelable.nil? ? false : @cancelable
      end

    end

    facet.enhance(Parameter) do
      include Domgen::Java::ImitJavaCharacteristic

      # Does the parameter come from the environment?
      def environmental?
        !!@environment_key
      end

      attr_reader :environment_key

      def environment_key=(environment_key)
        Domgen.error("Unknown environment_key #{environment_key}") unless valid_environment_key?(environment_key)
        @environment_key = environment_key
      end

      def valid_environment_key?(environment_key)
        self.class.environment_key_set.include?(environment_key) ||
          environment_key_is_cookie?(environment_key)
      end

      def environment_key_is_cookie?(environment_key = self.environment_key)
        environment_key =~ /^request:cookie:.*/
      end

      def environment_value
        Domgen.error('environment_value invoked for non-environmental value') unless environmental?
        return "findCookie(getThreadLocalRequest(),\"#{environment_key.to_s[15, 100]}\")" if environment_key_is_cookie?(environment_key)
        value = self.class.environment_key_set[environment_key]
        return value if value

      end

      def self.environment_key_set
        {
          'request:session:id' => 'getThreadLocalRequest().getSession(true).getId()',
          'request:permutation-strong-name' => 'getPermutationStrongName()',
          'request:locale' => 'getThreadLocalRequest().getLocale().toString()',
          'request:remote-host' => 'getThreadLocalRequest().getRemoteHost()',
          'request:remote-address' => 'getThreadLocalRequest().getRemoteAddr()',
          'request:remote-port' => 'getThreadLocalRequest().getRemotePort()',
          'request:remote-user' => 'getThreadLocalRequest().getRemoteUser()',
          'request' => 'getThreadLocalRequest()',
        }
      end

      protected

      def characteristic
        parameter
      end
    end

    facet.enhance(Result) do
      include Domgen::Java::ImitJavaCharacteristic

      protected

      def characteristic
        result
      end
    end

    facet.enhance(Exception) do
      include Domgen::Java::BaseJavaGenerator

      java_artifact :name, :data_type, :shared, :gwt_rpc, 'GwtRpc#{exception.name}Exception'
    end
  end
end


text:
class Echo_i : public POA_Echo,
	       public PortableServer::RefCountServantBase
{
public:
  inline Echo_i() {}
  virtual ~Echo_i() {}
  virtual char* echoString(const char* mesg);
};

char* Echo_i::echoString(const char* mesg)
{
  cout << "C++ upcall '" << mesg << "'" << endl;
  return CORBA::string_dup(mesg);
}

class InterpreterUnlocker {
public:
  InterpreterUnlocker() {
    tstate_ = PyEval_SaveThread();
  }
  ~InterpreterUnlocker() {
    PyEval_RestoreThread(tstate_);
  }
private:
  PyThreadState* tstate_;
};

// This function retrieves the omniORBpyAPI struct from the _omnipy
// Python module.
static omniORBpyAPI*
getAPI()
{
  PyObject* omnipy = PyImport_ImportModule((char*)"_omnipy");
  if (!omnipy) {
    PyErr_SetString(PyExc_ImportError,
		    (char*)"Cannot import _omnipy");
    return 0;
  }
  PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
  omniORBpyAPI* api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
  Py_DECREF(pyapi);
  return api;
}

extern "C" {

  static PyObject* EmbedGetObjRef(PyObject* self, PyObject* args)
  {
    PyObject* pyorb;
    if (!PyArg_ParseTuple(args, (char*)"O", &pyorb)) return 0;

    omniORBpyAPI* api = getAPI();
    if (!api)
      return 0;

    CORBA::Object_var obj;
    CORBA::ORB_var    orb;

    try {
      // Python code gave us the ORB reference; convert it to the C++ reference
      obj = api->pyObjRefToCxxObjRef(pyorb, 1);
      orb = CORBA::ORB::_narrow(obj);
    }
    catch (CORBA::BAD_PARAM& ex) {
      PyErr_SetString(PyExc_TypeError,
		      (char*)"getObjRef() expects ORB as its argument");
      return 0;
    }
    // Activate an Echo object in the Root POA
    obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);

    Echo_i* myecho = new Echo_i();

    PortableServer::ObjectId_var myechoid = poa->activate_object(myecho);

    obj = myecho->_this();
    myecho->_remove_ref();

    PortableServer::POAManager_var pman = poa->the_POAManager();
    pman->activate();

    // Return the Echo reference to Python
    PyObject* ret = api->cxxObjRefToPyObjRef(obj, 1);
    return ret;
  }

  static PyObject* EmbedPutObjRef(PyObject* self, PyObject* args)
  {
    PyObject* pyobj;
    if (!PyArg_ParseTuple(args, (char*)"O", &pyobj)) return 0;

    omniORBpyAPI* api = getAPI();
    if (!api)
      return 0;

    CORBA::Object_var obj;
    Echo_var eobj;
    try {
      obj = api->pyObjRefToCxxObjRef(pyobj, 1);
    }
    catch (CORBA::SystemException& ex) {
      PyErr_SetString(PyExc_TypeError,
		      (char*)"putObjRef() expects CORBA object argument");
      return 0;
    }
    eobj = Echo::_narrow(obj);
    if (CORBA::is_nil(eobj)) {
      PyErr_SetString(PyExc_TypeError,
		      (char*)"putObjRef() argument not an Echo");
      return 0;
    }
    {
      // To do the call into Python, we must release the Python
      // interpreter lock, since the code doing the upcall acquires
      // it. The InterpreterUnlocker class deals with it for us.
      InterpreterUnlocker _u;
      cout << "\nTrying call to Python object..." << endl;
      CORBA::String_var ret = eobj->echoString("Hello from C++");
      cout << "The result was '" << (char*)ret << "'" << endl;
    }

    Py_INCREF(Py_None);
    return Py_None;
  }

  static PyMethodDef embed_methods[] = {
    {(char*)"getObjRef", EmbedGetObjRef, METH_VARARGS},
    {(char*)"putObjRef", EmbedPutObjRef, METH_VARARGS},
    {NULL, NULL}
  };

  void DLL_EXPORT init_embed()
  {
    PyObject* m = Py_InitModule((char*)"_embed", embed_methods);
  }
}