text:
package org.develnext.jphp.core.compiler.jvm.statement.expr;

import org.develnext.jphp.core.compiler.jvm.statement.ExpressionStmtCompiler;
import org.develnext.jphp.core.tokenizer.token.stmt.LabelStmtToken;
import org.objectweb.asm.tree.LabelNode;

public class GotoLabelCompiler extends BaseStatementCompiler<LabelStmtToken> {
    public GotoLabelCompiler(ExpressionStmtCompiler exprCompiler) {
        super(exprCompiler);
    }

    @Override
    public void write(LabelStmtToken token) {
        LabelNode labelNode = method.getOrCreateGotoLabel(token.getName());
        add(labelNode);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef INDEX_ADD_ADD
#define INDEX_ADD_ADD

#include "../index-core/option.h"

void add(Option opt);

#endif


text:
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Slice management and manipulation
//!
//! For more details `std::slice`.

#![stable]
#![doc(primitive = "slice")]

// How this module is organized.
//
// The library infrastructure for slices is fairly messy. There's
// a lot of stuff defined here. Let's keep it clean.
//
// Since slices don't support inherent methods; all operations
// on them are defined on traits, which are then reexported from
// the prelude for convenience. So there are a lot of traits here.
//
// The layout of this file is thus:
//
// * Slice-specific 'extension' traits and their implementations. This
//   is where most of the slice API resides.
// * Implementations of a few common traits with important slice ops.
// * Definitions of a bunch of iterators.
// * Free functions.
// * The `raw` and `bytes` submodules.
// * Boilerplate trait implementations.

pub use self::BinarySearchResult::*;

use mem::transmute;
use clone::Clone;
use cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering, Less, Equal, Greater, Equiv};
use cmp;
use default::Default;
use iter::*;
use num::Int;
use ops;
use option::{None, Option, Some};
use ptr;
use ptr::RawPtr;
use mem;
use mem::size_of;
use kinds::{Sized, marker};
use raw::Repr;
// Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
use raw::Slice as RawSlice;

//
// Extension traits
//

/// Extension methods for slices.
#[unstable = "may merge with other traits"]
pub trait SlicePrelude<T> for Sized? {
    /// Returns a subslice spanning the interval [`start`, `end`).
    ///
    /// Panics when the end of the new slice lies beyond the end of the
    /// original slice (i.e. when `end > self.len()`) or when `start > end`.
    ///
    /// Slicing with `start` equal to `end` yields an empty slice.
    #[unstable = "waiting on final error conventions/slicing syntax"]
    fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T];

    /// Returns a subslice from `start` to the end of the slice.
    ///
    /// Panics when `start` is strictly greater than the length of the original slice.
    ///
    /// Slicing from `self.len()` yields an empty slice.
    #[unstable = "waiting on final error conventions/slicing syntax"]
    fn slice_from<'a>(&'a self, start: uint) -> &'a [T];

    /// Returns a subslice from the start of the slice to `end`.
    ///
    /// Panics when `end` is strictly greater than the length of the original slice.
    ///
    /// Slicing to `0` yields an empty slice.
    #[unstable = "waiting on final error conventions/slicing syntax"]
    fn slice_to<'a>(&'a self, end: uint) -> &'a [T];

    /// Divides one slice into two at an index.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding
    /// the index `mid` itself) and the second will contain all
    /// indices from `[mid, len)` (excluding the index `len` itself).
    ///
    /// Panics if `mid > len`.
    #[unstable = "waiting on final error conventions"]
    fn split_at<'a>(&'a self, mid: uint) -> (&'a [T], &'a [T]);

    /// Returns an iterator over the slice
    #[unstable = "iterator type may change"]
    fn iter<'a>(&'a self) -> Items<'a, T>;

    /// Returns an iterator over subslices separated by elements that match
    /// `pred`.  The matched element is not contained in the subslices.
    #[unstable = "iterator type may change, waiting on unboxed closures"]
    fn split<'a>(&'a self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;

    /// Returns an iterator over subslices separated by elements that match
    /// `pred`, limited to splitting at most `n` times.  The matched element is
    /// not contained in the subslices.
    #[unstable = "iterator type may change"]
    fn splitn<'a>(&'a self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>>;

    /// Returns an iterator over subslices separated by elements that match
    /// `pred` limited to splitting at most `n` times. This starts at the end of
    /// the slice and works backwards.  The matched element is not contained in
    /// the subslices.
    #[unstable = "iterator type may change"]
    fn rsplitn<'a>(&'a self,  n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>>;

    /// Returns an iterator over all contiguous windows of length
    /// `size`. The windows overlap. If the slice is shorter than
    /// `size`, the iterator returns no values.
    ///
    /// # Panics
    ///
    /// Panics if `size` is 0.
    ///
    /// # Example
    ///
    /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
    /// `[3,4]`):
    ///
    /// ```rust
    /// let v = &[1i, 2, 3, 4];
    /// for win in v.windows(2) {
    ///     println!("{}", win);
    /// }
    /// ```
    #[unstable = "iterator type may change"]
    fn windows<'a>(&'a self, size: uint) -> Windows<'a, T>;

    /// Returns an iterator over `size` elements of the slice at a
    /// time. The chunks do not overlap. If `size` does not divide the
    /// length of the slice, then the last chunk will not have length
    /// `size`.
    ///
    /// # Panics
    ///
    /// Panics if `size` is 0.
    ///
    /// # Example
    ///
    /// Print the slice two elements at a time (i.e. `[1,2]`,
    /// `[3,4]`, `[5]`):
    ///
    /// ```rust
    /// let v = &[1i, 2, 3, 4, 5];
    /// for win in v.chunks(2) {
    ///     println!("{}", win);
    /// }
    /// ```
    #[unstable = "iterator type may change"]
    fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, T>;

    /// Returns the element of a slice at the given index, or `None` if the
    /// index is out of bounds.
    #[unstable = "waiting on final collection conventions"]
    fn get<'a>(&'a self, index: uint) -> Option<&'a T>;

    /// Returns the first element of a slice, or `None` if it is empty.
    #[unstable = "name may change"]
    fn head<'a>(&'a self) -> Option<&'a T>;

    /// Returns all but the first element of a slice.
    #[unstable = "name may change"]
    fn tail<'a>(&'a self) -> &'a [T];

    /// Returns all but the last element of a slice.
    #[unstable = "name may change"]
    fn init<'a>(&'a self) -> &'a [T];

    /// Returns the last element of a slice, or `None` if it is empty.
    #[unstable = "name may change"]
    fn last<'a>(&'a self) -> Option<&'a T>;

    /// Returns a pointer to the element at the given index, without doing
    /// bounds checking.
    #[unstable]
    unsafe fn unsafe_get<'a>(&'a self, index: uint) -> &'a T;

    /// Returns an unsafe pointer to the slice's buffer
    ///
    /// The caller must ensure that the slice outlives the pointer this
    /// function returns, or else it will end up pointing to garbage.
    ///
    /// Modifying the slice may cause its buffer to be reallocated, which
    /// would also make any pointers to it invalid.
    #[unstable]
    fn as_ptr(&self) -> *const T;

    /// Binary search a sorted slice with a comparator function.
    ///
    /// The comparator function should implement an order consistent
    /// with the sort order of the underlying slice, returning an
    /// order code that indicates whether its argument is `Less`,
    /// `Equal` or `Greater` the desired target.
    ///
    /// If a matching value is found then returns `Found`, containing
    /// the index for the matched element; if no match is found then
    /// `NotFound` is returned, containing the index where a matching
    /// element could be inserted while maintaining sorted order.
    ///
    /// # Example
    ///
    /// Looks up a series of four elements. The first is found, with a
    /// uniquely determined position; the second and third are not
    /// found; the fourth could match any position in `[1,4]`.
    ///
    /// ```rust
    /// use std::slice::{Found, NotFound};
    /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
    /// let s = s.as_slice();
    ///
    /// let seek = 13;
    /// assert_eq!(s.binary_search(|probe| probe.cmp(&seek)), Found(9));
    /// let seek = 4;
    /// assert_eq!(s.binary_search(|probe| probe.cmp(&seek)), NotFound(7));
    /// let seek = 100;
    /// assert_eq!(s.binary_search(|probe| probe.cmp(&seek)), NotFound(13));
    /// let seek = 1;
    /// let r = s.binary_search(|probe| probe.cmp(&seek));
    /// assert!(match r { Found(1...4) => true, _ => false, });
    /// ```
    #[unstable = "waiting on unboxed closures"]
    fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult;

    /// Return the number of elements in the slice
    ///
    /// # Example
    ///
    /// ```
    /// let a = [1i, 2, 3];
    /// assert_eq!(a.len(), 3);
    /// ```
    #[experimental = "not triaged yet"]
    fn len(&self) -> uint;

    /// Returns true if the slice has a length of 0
    ///
    /// # Example
    ///
    /// ```
    /// let a = [1i, 2, 3];
    /// assert!(!a.is_empty());
    /// ```
    #[inline]
    #[experimental = "not triaged yet"]
    fn is_empty(&self) -> bool { self.len() == 0 }
    /// Returns a mutable reference to the element at the given index,
    /// or `None` if the index is out of bounds
    #[unstable = "waiting on final error conventions"]
    fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T>;

    /// Work with `self` as a mut slice.
    /// Primarily intended for getting a &mut [T] from a [T, ..N].
    fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T];

    /// Returns a mutable subslice spanning the interval [`start`, `end`).
    ///
    /// Panics when the end of the new slice lies beyond the end of the
    /// original slice (i.e. when `end > self.len()`) or when `start > end`.
    ///
    /// Slicing with `start` equal to `end` yields an empty slice.
    #[unstable = "waiting on final error conventions"]
    fn slice_mut<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T];

    /// Returns a mutable subslice from `start` to the end of the slice.
    ///
    /// Panics when `start` is strictly greater than the length of the original slice.
    ///
    /// Slicing from `self.len()` yields an empty slice.
    #[unstable = "waiting on final error conventions"]
    fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [T];

    /// Returns a mutable subslice from the start of the slice to `end`.
    ///
    /// Panics when `end` is strictly greater than the length of the original slice.
    ///
    /// Slicing to `0` yields an empty slice.
    #[unstable = "waiting on final error conventions"]
    fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [T];

    /// Returns an iterator that allows modifying each value
    #[unstable = "waiting on iterator type name conventions"]
    fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T>;

    /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
    #[unstable = "name may change"]
    fn head_mut<'a>(&'a mut self) -> Option<&'a mut T>;

    /// Returns all but the first element of a mutable slice
    #[unstable = "name may change"]
    fn tail_mut<'a>(&'a mut self) -> &'a mut [T];

    /// Returns all but the last element of a mutable slice
    #[unstable = "name may change"]
    fn init_mut<'a>(&'a mut self) -> &'a mut [T];

    /// Returns a mutable pointer to the last item in the slice.
    #[unstable = "name may change"]
    fn last_mut<'a>(&'a mut self) -> Option<&'a mut T>;

    /// Returns an iterator over mutable subslices separated by elements that
    /// match `pred`.  The matched element is not contained in the subslices.
    #[unstable = "waiting on unboxed closures, iterator type name conventions"]
    fn split_mut<'a>(&'a mut self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;

    /// Returns an iterator over subslices separated by elements that match
    /// `pred`, limited to splitting at most `n` times.  The matched element is
    /// not contained in the subslices.
    #[unstable = "waiting on unboxed closures, iterator type name conventions"]
    fn splitn_mut<'a>(&'a mut self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>>;

    /// Returns an iterator over subslices separated by elements that match
    /// `pred` limited to splitting at most `n` times. This starts at the end of
    /// the slice and works backwards.  The matched element is not contained in
    /// the subslices.
    #[unstable = "waiting on unboxed closures, iterator type name conventions"]
    fn rsplitn_mut<'a>(&'a mut self,  n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>>;

    /// Returns an iterator over `chunk_size` elements of the slice at a time.
    /// The chunks are mutable and do not overlap. If `chunk_size` does
    /// not divide the length of the slice, then the last chunk will not
    /// have length `chunk_size`.
    ///
    /// # Panics
    ///
    /// Panics if `chunk_size` is 0.
    #[unstable = "waiting on iterator type name conventions"]
    fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> MutChunks<'a, T>;

    /// Swaps two elements in a slice.
    ///
    /// Panics if `a` or `b` are out of bounds.
    ///
    /// # Arguments
    ///
    /// * a - The index of the first element
    /// * b - The index of the second element
    ///
    /// # Example
    ///
    /// ```rust
    /// let mut v = ["a", "b", "c", "d"];
    /// v.swap(1, 3);
    /// assert!(v == ["a", "d", "c", "b"]);
    /// ```
    #[unstable = "waiting on final error conventions"]
    fn swap(&mut self, a: uint, b: uint);

    /// Divides one `&mut` into two at an index.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding
    /// the index `mid` itself) and the second will contain all
    /// indices from `[mid, len)` (excluding the index `len` itself).
    ///
    /// Panics if `mid > len`.
    ///
    /// # Example
    ///
    /// ```rust
    /// let mut v = [1i, 2, 3, 4, 5, 6];
    ///
    /// // scoped to restrict the lifetime of the borrows
    /// {
    ///    let (left, right) = v.split_at_mut(0);
    ///    assert!(left == &mut []);
    ///    assert!(right == &mut [1i, 2, 3, 4, 5, 6]);
    /// }
    ///
    /// {
    ///     let (left, right) = v.split_at_mut(2);
    ///     assert!(left == &mut [1i, 2]);
    ///     assert!(right == &mut [3i, 4, 5, 6]);
    /// }
    ///
    /// {
    ///     let (left, right) = v.split_at_mut(6);
    ///     assert!(left == &mut [1i, 2, 3, 4, 5, 6]);
    ///     assert!(right == &mut []);
    /// }
    /// ```
    #[unstable = "waiting on final error conventions"]
    fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]);

    /// Reverse the order of elements in a slice, in place.
    ///
    /// # Example
    ///
    /// ```rust
    /// let mut v = [1i, 2, 3];
    /// v.reverse();
    /// assert!(v == [3i, 2, 1]);
    /// ```
    #[experimental = "may be moved to iterators instead"]
    fn reverse(&mut self);

    /// Returns an unsafe mutable pointer to the element in index
    #[experimental = "waiting on unsafe conventions"]
    unsafe fn unsafe_mut<'a>(&'a mut self, index: uint) -> &'a mut T;

    /// Return an unsafe mutable pointer to the slice's buffer.
    ///
    /// The caller must ensure that the slice outlives the pointer this
    /// function returns, or else it will end up pointing to garbage.
    ///
    /// Modifying the slice may cause its buffer to be reallocated, which
    /// would also make any pointers to it invalid.
    #[inline]
    #[unstable]
    fn as_mut_ptr(&mut self) -> *mut T;
}

#[unstable]
impl<T> SlicePrelude<T> for [T] {
    #[inline]
    fn slice(&self, start: uint, end: uint) -> &[T] {
        assert!(start <= end);
        assert!(end <= self.len());
        unsafe {
            transmute(RawSlice {
                data: self.as_ptr().offset(start as int),
                len: (end - start)
            })
        }
    }

    #[inline]
    fn slice_from(&self, start: uint) -> &[T] {
        self.slice(start, self.len())
    }

    #[inline]
    fn slice_to(&self, end: uint) -> &[T] {
        self.slice(0, end)
    }

    #[inline]
    fn split_at(&self, mid: uint) -> (&[T], &[T]) {
        (self[..mid], self[mid..])
    }

    #[inline]
    fn iter<'a>(&'a self) -> Items<'a, T> {
        unsafe {
            let p = self.as_ptr();
            if mem::size_of::<T>() == 0 {
                Items{ptr: p,
                      end: (p as uint + self.len()) as *const T,
                      marker: marker::ContravariantLifetime::<'a>}
            } else {
                Items{ptr: p,
                      end: p.offset(self.len() as int),
                      marker: marker::ContravariantLifetime::<'a>}
            }
        }
    }

    #[inline]
    fn split<'a>(&'a self, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
        Splits {
            v: self,
            pred: pred,
            finished: false
        }
    }

    #[inline]
    fn splitn<'a>(&'a self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>> {
        SplitsN {
            iter: self.split(pred),
            count: n,
            invert: false
        }
    }

    #[inline]
    fn rsplitn<'a>(&'a self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>> {
        SplitsN {
            iter: self.split(pred),
            count: n,
            invert: true
        }
    }

    #[inline]
    fn windows(&self, size: uint) -> Windows<T> {
        assert!(size != 0);
        Windows { v: self, size: size }
    }

    #[inline]
    fn chunks(&self, size: uint) -> Chunks<T> {
        assert!(size != 0);
        Chunks { v: self, size: size }
    }

    #[inline]
    fn get(&self, index: uint) -> Option<&T> {
        if index < self.len() { Some(&self[index]) } else { None }
    }

    #[inline]
    fn head(&self) -> Option<&T> {
        if self.len() == 0 { None } else { Some(&self[0]) }
    }

    #[inline]
    fn tail(&self) -> &[T] { self[1..] }

    #[inline]
    fn init(&self) -> &[T] {
        self[..self.len() - 1]
    }

    #[inline]
    fn last(&self) -> Option<&T> {
        if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
    }

    #[inline]
    unsafe fn unsafe_get(&self, index: uint) -> &T {
        transmute(self.repr().data.offset(index as int))
    }

    #[inline]
    fn as_ptr(&self) -> *const T {
        self.repr().data
    }

    #[unstable]
    fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult {
        let mut base : uint = 0;
        let mut lim : uint = self.len();

        while lim != 0 {
            let ix = base + (lim >> 1);
            match f(&self[ix]) {
                Equal => return Found(ix),
                Less => {
                    base = ix + 1;
                    lim -= 1;
                }
                Greater => ()
            }
            lim >>= 1;
        }
        return NotFound(base);
    }

    #[inline]
    fn len(&self) -> uint { self.repr().len }

    #[inline]
    fn get_mut(&mut self, index: uint) -> Option<&mut T> {
        if index < self.len() { Some(&mut self[index]) } else { None }
    }

    #[inline]
    fn as_mut_slice(&mut self) -> &mut [T] { self }

    fn slice_mut(&mut self, start: uint, end: uint) -> &mut [T] {
        self[mut start..end]
    }

    #[inline]
    fn slice_from_mut(&mut self, start: uint) -> &mut [T] {
        self[mut start..]
    }

    #[inline]
    fn slice_to_mut(&mut self, end: uint) -> &mut [T] {
        self[mut ..end]
    }

    #[inline]
    fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]) {
        unsafe {
            let self2: &mut [T] = mem::transmute_copy(&self);
            (self[mut ..mid], self2[mut mid..])
        }
    }

    #[inline]
    fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
        unsafe {
            let p = self.as_mut_ptr();
            if mem::size_of::<T>() == 0 {
                MutItems{ptr: p,
                         end: (p as uint + self.len()) as *mut T,
                         marker: marker::ContravariantLifetime::<'a>,
                         marker2: marker::NoCopy}
            } else {
                MutItems{ptr: p,
                         end: p.offset(self.len() as int),
                         marker: marker::ContravariantLifetime::<'a>,
                         marker2: marker::NoCopy}
            }
        }
    }

    #[inline]
    fn last_mut(&mut self) -> Option<&mut T> {
        let len = self.len();
        if len == 0 { return None; }
        Some(&mut self[len - 1])
    }

    #[inline]
    fn head_mut(&mut self) -> Option<&mut T> {
        if self.len() == 0 { None } else { Some(&mut self[0]) }
    }

    #[inline]
    fn tail_mut(&mut self) -> &mut [T] {
        let len = self.len();
        self[mut 1..len]
    }

    #[inline]
    fn init_mut(&mut self) -> &mut [T] {
        let len = self.len();
        self[mut 0..len - 1]
    }

    #[inline]
    fn split_mut<'a>(&'a mut self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
        MutSplits { v: self, pred: pred, finished: false }
    }

    #[inline]
    fn splitn_mut<'a>(&'a mut self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>> {
        SplitsN {
            iter: self.split_mut(pred),
            count: n,
            invert: false
        }
    }

    #[inline]
    fn rsplitn_mut<'a>(&'a mut self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>> {
        SplitsN {
            iter: self.split_mut(pred),
            count: n,
            invert: true
        }
   }

    #[inline]
    fn chunks_mut(&mut self, chunk_size: uint) -> MutChunks<T> {
        assert!(chunk_size > 0);
        MutChunks { v: self, chunk_size: chunk_size }
    }

    fn swap(&mut self, a: uint, b: uint) {
        unsafe {
            // Can't take two mutable loans from one vector, so instead just cast
            // them to their raw pointers to do the swap
            let pa: *mut T = &mut self[a];
            let pb: *mut T = &mut self[b];
            ptr::swap(pa, pb);
        }
    }

    fn reverse(&mut self) {
        let mut i: uint = 0;
        let ln = self.len();
        while i < ln / 2 {
            // Unsafe swap to avoid the bounds check in safe swap.
            unsafe {
                let pa: *mut T = self.unsafe_mut(i);
                let pb: *mut T = self.unsafe_mut(ln - i - 1);
                ptr::swap(pa, pb);
            }
            i += 1;
        }
    }

    #[inline]
    unsafe fn unsafe_mut(&mut self, index: uint) -> &mut T {
        transmute((self.repr().data as *mut T).offset(index as int))
    }

    #[inline]
    fn as_mut_ptr(&mut self) -> *mut T {
        self.repr().data as *mut T
    }
}

impl<T> ops::Index<uint, T> for [T] {
    fn index(&self, &index: &uint) -> &T {
        assert!(index < self.len());

        unsafe { mem::transmute(self.repr().data.offset(index as int)) }
    }
}

impl<T> ops::IndexMut<uint, T> for [T] {
    fn index_mut(&mut self, &index: &uint) -> &mut T {
        assert!(index < self.len());

        unsafe { mem::transmute(self.repr().data.offset(index as int)) }
    }
}

impl<T> ops::Slice<uint, [T]> for [T] {
    #[inline]
    fn as_slice_<'a>(&'a self) -> &'a [T] {
        self
    }

    #[inline]
    fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
        self.slice_or_fail(start, &self.len())
    }

    #[inline]
    fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
        self.slice_or_fail(&0, end)
    }
    #[inline]
    fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
        assert!(*start <= *end);
        assert!(*end <= self.len());
        unsafe {
            transmute(RawSlice {
                    data: self.as_ptr().offset(*start as int),
                    len: (*end - *start)
                })
        }
    }
}

impl<T> ops::SliceMut<uint, [T]> for [T] {
    #[inline]
    fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
        self
    }

    #[inline]
    fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
        let len = &self.len();
        self.slice_or_fail_mut(start, len)
    }

    #[inline]
    fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
        self.slice_or_fail_mut(&0, end)
    }
    #[inline]
    fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
        assert!(*start <= *end);
        assert!(*end <= self.len());
        unsafe {
            transmute(RawSlice {
                    data: self.as_ptr().offset(*start as int),
                    len: (*end - *start)
                })
        }
    }
}

/// Extension methods for slices containing `PartialEq` elements.
#[unstable = "may merge with other traits"]
pub trait PartialEqSlicePrelude<T: PartialEq> for Sized? {
    /// Find the first index containing a matching value.
    fn position_elem(&self, t: &T) -> Option<uint>;

    /// Find the last index containing a matching value.
    fn rposition_elem(&self, t: &T) -> Option<uint>;

    /// Return true if the slice contains an element with the given value.
    fn contains(&self, x: &T) -> bool;

    /// Returns true if `needle` is a prefix of the slice.
    fn starts_with(&self, needle: &[T]) -> bool;

    /// Returns true if `needle` is a suffix of the slice.
    fn ends_with(&self, needle: &[T]) -> bool;
}

#[unstable = "trait is unstable"]
impl<T: PartialEq> PartialEqSlicePrelude<T> for [T] {
    #[inline]
    fn position_elem(&self, x: &T) -> Option<uint> {
        self.iter().position(|y| *x == *y)
    }

    #[inline]
    fn rposition_elem(&self, t: &T) -> Option<uint> {
        self.iter().rposition(|x| *x == *t)
    }

    #[inline]
    fn contains(&self, x: &T) -> bool {
        self.iter().any(|elt| *x == *elt)
    }

    #[inline]
    fn starts_with(&self, needle: &[T]) -> bool {
        let n = needle.len();
        self.len() >= n && needle == self[..n]
    }

    #[inline]
    fn ends_with(&self, needle: &[T]) -> bool {
        let (m, n) = (self.len(), needle.len());
        m >= n && needle == self[m-n..]
    }
}

/// Extension methods for slices containing `Ord` elements.
#[unstable = "may merge with other traits"]
pub trait OrdSlicePrelude<T: Ord> for Sized? {
    /// Binary search a sorted slice for a given element.
    ///
    /// If the value is found then `Found` is returned, containing the
    /// index of the matching element; if the value is not found then
    /// `NotFound` is returned, containing the index where a matching
    /// element could be inserted while maintaining sorted order.
    ///
    /// # Example
    ///
    /// Looks up a series of four elements. The first is found, with a
    /// uniquely determined position; the second and third are not
    /// found; the fourth could match any position in `[1,4]`.
    ///
    /// ```rust
    /// use std::slice::{Found, NotFound};
    /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
    /// let s = s.as_slice();
    ///
    /// assert_eq!(s.binary_search_elem(&13),  Found(9));
    /// assert_eq!(s.binary_search_elem(&4),   NotFound(7));
    /// assert_eq!(s.binary_search_elem(&100), NotFound(13));
    /// let r = s.binary_search_elem(&1);
    /// assert!(match r { Found(1...4) => true, _ => false, });
    /// ```
    #[unstable = "name likely to change"]
    fn binary_search_elem(&self, x: &T) -> BinarySearchResult;

    /// Mutates the slice to the next lexicographic permutation.
    ///
    /// Returns `true` if successful and `false` if the slice is at the
    /// last-ordered permutation.
    ///
    /// # Example
    ///
    /// ```rust
    /// let v: &mut [_] = &mut [0i, 1, 2];
    /// v.next_permutation();
    /// let b: &mut [_] = &mut [0i, 2, 1];
    /// assert!(v == b);
    /// v.next_permutation();
    /// let b: &mut [_] = &mut [1i, 0, 2];
    /// assert!(v == b);
    /// ```
    #[experimental]
    fn next_permutation(&mut self) -> bool;

    /// Mutates the slice to the previous lexicographic permutation.
    ///
    /// Returns `true` if successful and `false` if the slice is at the
    /// first-ordered permutation.
    ///
    /// # Example
    ///
    /// ```rust
    /// let v: &mut [_] = &mut [1i, 0, 2];
    /// v.prev_permutation();
    /// let b: &mut [_] = &mut [0i, 2, 1];
    /// assert!(v == b);
    /// v.prev_permutation();
    /// let b: &mut [_] = &mut [0i, 1, 2];
    /// assert!(v == b);
    /// ```
    #[experimental]
    fn prev_permutation(&mut self) -> bool;
}

#[unstable = "trait is unstable"]
impl<T: Ord> OrdSlicePrelude<T> for [T] {
    #[unstable]
    fn binary_search_elem(&self, x: &T) -> BinarySearchResult {
        self.binary_search(|p| p.cmp(x))
    }

    #[experimental]
    fn next_permutation(&mut self) -> bool {
        // These cases only have 1 permutation each, so we can't do anything.
        if self.len() < 2 { return false; }

        // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
        let mut i = self.len() - 1;
        while i > 0 && self[i-1] >= self[i] {
            i -= 1;
        }

        // If that is the entire vector, this is the last-ordered permutation.
        if i == 0 {
            return false;
        }

        // Step 2: Find the rightmost element larger than the pivot (i-1)
        let mut j = self.len() - 1;
        while j >= i && self[j] <= self[i-1]  {
            j -= 1;
        }

        // Step 3: Swap that element with the pivot
        self.swap(j, i-1);

        // Step 4: Reverse the (previously) weakly decreasing part
        self[mut i..].reverse();

        true
    }

    #[experimental]
    fn prev_permutation(&mut self) -> bool {
        // These cases only have 1 permutation each, so we can't do anything.
        if self.len() < 2 { return false; }

        // Step 1: Identify the longest, rightmost weakly increasing part of the vector
        let mut i = self.len() - 1;
        while i > 0 && self[i-1] <= self[i] {
            i -= 1;
        }

        // If that is the entire vector, this is the first-ordered permutation.
        if i == 0 {
            return false;
        }

        // Step 2: Reverse the weakly increasing part
        self[mut i..].reverse();

        // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
        let mut j = self.len() - 1;
        while j >= i && self[j-1] < self[i-1]  {
            j -= 1;
        }

        // Step 4: Swap that element with the pivot
        self.swap(i-1, j);

        true
    }
}

/// Extension methods for slices on Clone elements
#[unstable = "may merge with other traits"]
pub trait CloneSlicePrelude<T> for Sized? {
    /// Copies as many elements from `src` as it can into `self` (the
    /// shorter of `self.len()` and `src.len()`). Returns the number
    /// of elements copied.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::slice::CloneSlicePrelude;
    ///
    /// let mut dst = [0i, 0, 0];
    /// let src = [1i, 2];
    ///
    /// assert!(dst.clone_from_slice(&src) == 2);
    /// assert!(dst == [1, 2, 0]);
    ///
    /// let src2 = [3i, 4, 5, 6];
    /// assert!(dst.clone_from_slice(&src2) == 3);
    /// assert!(dst == [3i, 4, 5]);
    /// ```
    fn clone_from_slice(&mut self, &[T]) -> uint;
}

#[unstable = "trait is unstable"]
impl<T: Clone> CloneSlicePrelude<T> for [T] {
    #[inline]
    fn clone_from_slice(&mut self, src: &[T]) -> uint {
        let min = cmp::min(self.len(), src.len());
        let dst = self.slice_to_mut(min);
        let src = src.slice_to(min);
        for i in range(0, min) {
            dst[i].clone_from(&src[i]);
        }
        min
    }
}

//
// Common traits
//

/// Data that is viewable as a slice.
#[unstable = "may merge with other traits"]
pub trait AsSlice<T> {
    /// Work with `self` as a slice.
    fn as_slice<'a>(&'a self) -> &'a [T];
}

#[unstable = "trait is unstable"]
impl<'a,T> AsSlice<T> for &'a [T] {
    #[inline(always)]
    fn as_slice<'a>(&'a self) -> &'a [T] { *self }
}

#[unstable = "waiting for DST"]
impl<'a, T> Default for &'a [T] {
    fn default() -> &'a [T] { &[] }
}

//
// Iterators
//

// The shared definition of the `Item` and `MutItems` iterators
macro_rules! iterator {
    (struct $name:ident -> $ptr:ty, $elem:ty) => {
        #[experimental = "needs review"]
        impl<'a, T> Iterator<$elem> for $name<'a, T> {
            #[inline]
            fn next(&mut self) -> Option<$elem> {
                // could be implemented with slices, but this avoids bounds checks
                unsafe {
                    if self.ptr == self.end {
                        None
                    } else {
                        if mem::size_of::<T>() == 0 {
                            // purposefully don't use 'ptr.offset' because for
                            // vectors with 0-size elements this would return the
                            // same pointer.
                            self.ptr = transmute(self.ptr as uint + 1);

                            // Use a non-null pointer value
                            Some(transmute(1u))
                        } else {
                            let old = self.ptr;
                            self.ptr = self.ptr.offset(1);

                            Some(transmute(old))
                        }
                    }
                }
            }

            #[inline]
            fn size_hint(&self) -> (uint, Option<uint>) {
                let diff = (self.end as uint) - (self.ptr as uint);
                let size = mem::size_of::<T>();
                let exact = diff / (if size == 0 {1} else {size});
                (exact, Some(exact))
            }
        }

        #[experimental = "needs review"]
        impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
            #[inline]
            fn next_back(&mut self) -> Option<$elem> {
                // could be implemented with slices, but this avoids bounds checks
                unsafe {
                    if self.end == self.ptr {
                        None
                    } else {
                        if mem::size_of::<T>() == 0 {
                            // See above for why 'ptr.offset' isn't used
                            self.end = transmute(self.end as uint - 1);

                            // Use a non-null pointer value
                            Some(transmute(1u))
                        } else {
                            self.end = self.end.offset(-1);

                            Some(transmute(self.end))
                        }
                    }
                }
            }
        }
    }
}

/// Immutable slice iterator
#[experimental = "needs review"]
pub struct Items<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
    marker: marker::ContravariantLifetime<'a>
}

iterator!{struct Items -> *const T, &'a T}

#[experimental = "needs review"]
impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}

#[experimental = "needs review"]
impl<'a, T> Clone for Items<'a, T> {
    fn clone(&self) -> Items<'a, T> { *self }
}

#[experimental = "needs review"]
impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
    #[inline]
    fn indexable(&self) -> uint {
        let (exact, _) = self.size_hint();
        exact
    }

    #[inline]
    fn idx(&mut self, index: uint) -> Option<&'a T> {
        unsafe {
            if index < self.indexable() {
                if mem::size_of::<T>() == 0 {
                    // Use a non-null pointer value
                    Some(transmute(1u))
                } else {
                    Some(transmute(self.ptr.offset(index as int)))
                }
            } else {
                None
            }
        }
    }
}

/// Mutable slice iterator.
#[experimental = "needs review"]
pub struct MutItems<'a, T: 'a> {
    ptr: *mut T,
    end: *mut T,
    marker: marker::ContravariantLifetime<'a>,
    marker2: marker::NoCopy
}

iterator!{struct MutItems -> *mut T, &'a mut T}

#[experimental = "needs review"]
impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}

/// An abstraction over the splitting iterators, so that splitn, splitn_mut etc
/// can be implemented once.
trait SplitsIter<E>: DoubleEndedIterator<E> {
    /// Mark the underlying iterator as complete, extracting the remaining
    /// portion of the slice.
    fn finish(&mut self) -> Option<E>;
}

/// An iterator over subslices separated by elements that match a predicate
/// function.
#[experimental = "needs review"]
pub struct Splits<'a, T:'a> {
    v: &'a [T],
    pred: |t: &T|: 'a -> bool,
    finished: bool
}

#[experimental = "needs review"]
impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<&'a [T]> {
        if self.finished { return None; }

        match self.v.iter().position(|x| (self.pred)(x)) {
            None => self.finish(),
            Some(idx) => {
                let ret = Some(self.v[..idx]);
                self.v = self.v[idx + 1..];
                ret
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        if self.finished {
            (0, Some(0))
        } else {
            (1, Some(self.v.len() + 1))
        }
    }
}

#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a [T]> {
        if self.finished { return None; }

        match self.v.iter().rposition(|x| (self.pred)(x)) {
            None => self.finish(),
            Some(idx) => {
                let ret = Some(self.v[idx + 1..]);
                self.v = self.v[..idx];
                ret
            }
        }
    }
}

impl<'a, T> SplitsIter<&'a [T]> for Splits<'a, T> {
    #[inline]
    fn finish(&mut self) -> Option<&'a [T]> {
        if self.finished { None } else { self.finished = true; Some(self.v) }
    }
}

/// An iterator over the subslices of the vector which are separated
/// by elements that match `pred`.
#[experimental = "needs review"]
pub struct MutSplits<'a, T:'a> {
    v: &'a mut [T],
    pred: |t: &T|: 'a -> bool,
    finished: bool
}

impl<'a, T> SplitsIter<&'a mut [T]> for MutSplits<'a, T> {
    #[inline]
    fn finish(&mut self) -> Option<&'a mut [T]> {
        if self.finished {
            None
        } else {
            self.finished = true;
            Some(mem::replace(&mut self.v, &mut []))
        }
    }
}

#[experimental = "needs review"]
impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<&'a mut [T]> {
        if self.finished { return None; }

        let idx_opt = { // work around borrowck limitations
            let pred = &mut self.pred;
            self.v.iter().position(|x| (*pred)(x))
        };
        match idx_opt {
            None => self.finish(),
            Some(idx) => {
                let tmp = mem::replace(&mut self.v, &mut []);
                let (head, tail) = tmp.split_at_mut(idx);
                self.v = tail[mut 1..];
                Some(head)
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        if self.finished {
            (0, Some(0))
        } else {
            // if the predicate doesn't match anything, we yield one slice
            // if it matches every element, we yield len+1 empty slices.
            (1, Some(self.v.len() + 1))
        }
    }
}

#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a mut [T]> {
        if self.finished { return None; }

        let idx_opt = { // work around borrowck limitations
            let pred = &mut self.pred;
            self.v.iter().rposition(|x| (*pred)(x))
        };
        match idx_opt {
            None => self.finish(),
            Some(idx) => {
                let tmp = mem::replace(&mut self.v, &mut []);
                let (head, tail) = tmp.split_at_mut(idx);
                self.v = head;
                Some(tail[mut 1..])
            }
        }
    }
}

/// An iterator over subslices separated by elements that match a predicate
/// function, splitting at most a fixed number of times.
#[experimental = "needs review"]
pub struct SplitsN<I> {
    iter: I,
    count: uint,
    invert: bool
}

#[experimental = "needs review"]
impl<E, I: SplitsIter<E>> Iterator<E> for SplitsN<I> {
    #[inline]
    fn next(&mut self) -> Option<E> {
        if self.count == 0 {
            self.iter.finish()
        } else {
            self.count -= 1;
            if self.invert { self.iter.next_back() } else { self.iter.next() }
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (lower, upper_opt) = self.iter.size_hint();
        (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
    }
}

/// An iterator over overlapping subslices of length `size`.
#[deriving(Clone)]
#[experimental = "needs review"]
pub struct Windows<'a, T:'a> {
    v: &'a [T],
    size: uint
}

impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<&'a [T]> {
        if self.size > self.v.len() {
            None
        } else {
            let ret = Some(self.v[..self.size]);
            self.v = self.v[1..];
            ret
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        if self.size > self.v.len() {
            (0, Some(0))
        } else {
            let x = self.v.len() - self.size;
            (x.saturating_add(1), x.checked_add(1u))
        }
    }
}

/// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
/// time).
///
/// When the slice len is not evenly divided by the chunk size, the last slice
/// of the iteration will be the remainder.
#[deriving(Clone)]
#[experimental = "needs review"]
pub struct Chunks<'a, T:'a> {
    v: &'a [T],
    size: uint
}

#[experimental = "needs review"]
impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<&'a [T]> {
        if self.v.len() == 0 {
            None
        } else {
            let chunksz = cmp::min(self.v.len(), self.size);
            let (fst, snd) = self.v.split_at(chunksz);
            self.v = snd;
            Some(fst)
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        if self.v.len() == 0 {
            (0, Some(0))
        } else {
            let n = self.v.len() / self.size;
            let rem = self.v.len() % self.size;
            let n = if rem > 0 { n+1 } else { n };
            (n, Some(n))
        }
    }
}

#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a [T]> {
        if self.v.len() == 0 {
            None
        } else {
            let remainder = self.v.len() % self.size;
            let chunksz = if remainder != 0 { remainder } else { self.size };
            let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
            self.v = fst;
            Some(snd)
        }
    }
}

#[experimental = "needs review"]
impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
    #[inline]
    fn indexable(&self) -> uint {
        self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
    }

    #[inline]
    fn idx(&mut self, index: uint) -> Option<&'a [T]> {
        if index < self.indexable() {
            let lo = index * self.size;
            let mut hi = lo + self.size;
            if hi < lo || hi > self.v.len() { hi = self.v.len(); }

            Some(self.v[lo..hi])
        } else {
            None
        }
    }
}

/// An iterator over a slice in (non-overlapping) mutable chunks (`size`
/// elements at a time). When the slice len is not evenly divided by the chunk
/// size, the last slice of the iteration will be the remainder.
#[experimental = "needs review"]
pub struct MutChunks<'a, T:'a> {
    v: &'a mut [T],
    chunk_size: uint
}

#[experimental = "needs review"]
impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<&'a mut [T]> {
        if self.v.len() == 0 {
            None
        } else {
            let sz = cmp::min(self.v.len(), self.chunk_size);
            let tmp = mem::replace(&mut self.v, &mut []);
            let (head, tail) = tmp.split_at_mut(sz);
            self.v = tail;
            Some(head)
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        if self.v.len() == 0 {
            (0, Some(0))
        } else {
            let n = self.v.len() / self.chunk_size;
            let rem = self.v.len() % self.chunk_size;
            let n = if rem > 0 { n + 1 } else { n };
            (n, Some(n))
        }
    }
}

#[experimental = "needs review"]
impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a mut [T]> {
        if self.v.len() == 0 {
            None
        } else {
            let remainder = self.v.len() % self.chunk_size;
            let sz = if remainder != 0 { remainder } else { self.chunk_size };
            let tmp = mem::replace(&mut self.v, &mut []);
            let tmp_len = tmp.len();
            let (head, tail) = tmp.split_at_mut(tmp_len - sz);
            self.v = head;
            Some(tail)
        }
    }
}

/// The result of calling `binary_search`.
///
/// `Found` means the search succeeded, and the contained value is the
/// index of the matching element. `NotFound` means the search
/// succeeded, and the contained value is an index where a matching
/// value could be inserted while maintaining sort order.
#[deriving(PartialEq, Show)]
#[experimental = "needs review"]
pub enum BinarySearchResult {
    /// The index of the found value.
    Found(uint),
    /// The index where the value should have been found.
    NotFound(uint)
}

#[experimental = "needs review"]
impl BinarySearchResult {
    /// Converts a `Found` to `Some`, `NotFound` to `None`.
    /// Similar to `Result::ok`.
    pub fn found(&self) -> Option<uint> {
        match *self {
            Found(i) => Some(i),
            NotFound(_) => None
        }
    }

    /// Convert a `Found` to `None`, `NotFound` to `Some`.
    /// Similar to `Result::err`.
    pub fn not_found(&self) -> Option<uint> {
        match *self {
            Found(_) => None,
            NotFound(i) => Some(i)
        }
    }
}

//
// Free functions
//

/**
 * Converts a pointer to A into a slice of length 1 (without copying).
 */
#[unstable = "waiting for DST"]
pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
    unsafe {
        transmute(RawSlice { data: s, len: 1 })
    }
}

/**
 * Converts a pointer to A into a slice of length 1 (without copying).
 */
#[unstable = "waiting for DST"]
pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
    unsafe {
        let ptr: *const A = transmute(s);
        transmute(RawSlice { data: ptr, len: 1 })
    }
}

//
// Submodules
//

/// Unsafe operations
#[experimental = "needs review"]
pub mod raw {
    use mem::transmute;
    use ptr::RawPtr;
    use raw::Slice;
    use option::{None, Option, Some};

    /**
     * Form a slice from a pointer and length (as a number of units,
     * not bytes).
     */
    #[inline]
    pub unsafe fn buf_as_slice<T,U>(p: *const T, len: uint, f: |v: &[T]| -> U)
                               -> U {
        f(transmute(Slice {
            data: p,
            len: len
        }))
    }

    /**
     * Form a slice from a pointer and length (as a number of units,
     * not bytes).
     */
    #[inline]
    pub unsafe fn mut_buf_as_slice<T,
                                   U>(
                                   p: *mut T,
                                   len: uint,
                                   f: |v: &mut [T]| -> U)
                                   -> U {
        f(transmute(Slice {
            data: p as *const T,
            len: len
        }))
    }

    /**
     * Returns a pointer to first element in slice and adjusts
     * slice so it no longer contains that element. Returns None
     * if the slice is empty. O(1).
     */
     #[inline]
    pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
        if slice.len == 0 { return None; }
        let head: *const T = slice.data;
        slice.data = slice.data.offset(1);
        slice.len -= 1;
        Some(head)
    }

    /**
     * Returns a pointer to last element in slice and adjusts
     * slice so it no longer contains that element. Returns None
     * if the slice is empty. O(1).
     */
     #[inline]
    pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
        if slice.len == 0 { return None; }
        let tail: *const T = slice.data.offset((slice.len - 1) as int);
        slice.len -= 1;
        Some(tail)
    }
}

/// Operations on `[u8]`.
#[experimental = "needs review"]
pub mod bytes {
    use kinds::Sized;
    use ptr;
    use slice::SlicePrelude;

    /// A trait for operations on mutable `[u8]`s.
    pub trait MutableByteVector for Sized? {
        /// Sets all bytes of the receiver to the given value.
        fn set_memory(&mut self, value: u8);
    }

    impl MutableByteVector for [u8] {
        #[inline]
        #[allow(experimental)]
        fn set_memory(&mut self, value: u8) {
            unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
        }
    }

    /// Copies data from `src` to `dst`
    ///
    /// `src` and `dst` must not overlap. Panics if the length of `dst`
    /// is less than the length of `src`.
    #[inline]
    pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
        let len_src = src.len();
        assert!(dst.len() >= len_src);
        unsafe {
            ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
                                            src.as_ptr(),
                                            len_src);
        }
    }
}

//
// Boilerplate traits
//

#[unstable = "waiting for DST"]
impl<T: PartialEq> PartialEq for [T] {
    fn eq(&self, other: &[T]) -> bool {
        self.len() == other.len() &&
            order::eq(self.iter(), other.iter())
    }
    fn ne(&self, other: &[T]) -> bool {
        self.len() != other.len() ||
            order::ne(self.iter(), other.iter())
    }
}

#[unstable = "waiting for DST"]
impl<T: Eq> Eq for [T] {}

#[unstable = "waiting for DST"]
impl<T: PartialEq, V: AsSlice<T>> Equiv<V> for [T] {
    #[inline]
    fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}

#[unstable = "waiting for DST"]
impl<'a,T:PartialEq, V: AsSlice<T>> Equiv<V> for &'a mut [T] {
    #[inline]
    fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}

#[unstable = "waiting for DST"]
impl<T: Ord> Ord for [T] {
    fn cmp(&self, other: &[T]) -> Ordering {
        order::cmp(self.iter(), other.iter())
    }
}

#[unstable = "waiting for DST"]
impl<T: PartialOrd> PartialOrd for [T] {
    #[inline]
    fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
        order::partial_cmp(self.iter(), other.iter())
    }
    #[inline]
    fn lt(&self, other: &[T]) -> bool {
        order::lt(self.iter(), other.iter())
    }
    #[inline]
    fn le(&self, other: &[T]) -> bool {
        order::le(self.iter(), other.iter())
    }
    #[inline]
    fn ge(&self, other: &[T]) -> bool {
        order::ge(self.iter(), other.iter())
    }
    #[inline]
    fn gt(&self, other: &[T]) -> bool {
        order::gt(self.iter(), other.iter())
    }
}

/// Extension methods for immutable slices containing integers.
#[experimental]
pub trait ImmutableIntSlice<U, S> for Sized? {
    /// Converts the slice to an immutable slice of unsigned integers with the same width.
    fn as_unsigned<'a>(&'a self) -> &'a [U];
    /// Converts the slice to an immutable slice of signed integers with the same width.
    fn as_signed<'a>(&'a self) -> &'a [S];
}

/// Extension methods for mutable slices containing integers.
#[experimental]
pub trait MutableIntSlice<U, S> for Sized?: ImmutableIntSlice<U, S> {
    /// Converts the slice to a mutable slice of unsigned integers with the same width.
    fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
    /// Converts the slice to a mutable slice of signed integers with the same width.
    fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
}

macro_rules! impl_immut_int_slice {
    ($u:ty, $s:ty, $t:ty) => {
        #[experimental]
        impl ImmutableIntSlice<$u, $s> for [$t] {
            #[inline]
            fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
            #[inline]
            fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
        }
    }
}
macro_rules! impl_mut_int_slice {
    ($u:ty, $s:ty, $t:ty) => {
        #[experimental]
        impl MutableIntSlice<$u, $s> for [$t] {
            #[inline]
            fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
            #[inline]
            fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
        }
    }
}

macro_rules! impl_int_slice {
    ($u:ty, $s:ty) => {
        impl_immut_int_slice!($u, $s, $u)
        impl_immut_int_slice!($u, $s, $s)
        impl_mut_int_slice!($u, $s, $u)
        impl_mut_int_slice!($u, $s, $s)
    }
}

impl_int_slice!(u8,   i8)
impl_int_slice!(u16,  i16)
impl_int_slice!(u32,  i32)
impl_int_slice!(u64,  i64)
impl_int_slice!(uint, int)


text:
ESP32 Core Dump
===============

Overview
--------

ESP-IDF provides support to generate core dumps on unrecoverable software errors. This useful technique allows post-mortem analysis of software state at the moment of failure.
Upon the crash system enters panic state, prints some information and halts or reboots depending configuration. User can choose to generate core dump in order to analyse
the reason of failure on PC later on. Core dump contains snapshots of all tasks in the system at the moment of failure. Snapshots include tasks control blocks (TCB) and stacks.
So it is possible to find out what task, at what instruction (line of code) and what callstack of that task lead to the crash.
ESP-IDF provides special script `espcoredump.py` to help users to retrieve and analyse core dumps. This tool provides two commands for core dumps analysis:

* info_corefile - prints crashed task's registers, callstack, list of available tasks in the system, memory regions and contents of memory stored in core dump (TCBs and stacks)
* dbg_corefile - creates core dump ELF file and runs GDB debug session with this file. User can examine memory, variables and tasks states manually. Note that since not all memory is saved in core dump only values of variables allocated on stack will be meaningfull

Configuration
-------------

There are a number of core dump related configuration options which user can choose in configuration menu of the application (`make menuconfig`).

1. Core dump data destination (`Components -> ESP32-specific config -> Core dump -> Data destination`):

* Disable core dump generation
* Save core dump to flash
* Print core dump to UART

2. Maximum number of tasks snapshots in core dump (`Components -> ESP32-specific config -> Core dump -> Maximum number of tasks`).

3. Delay before core dump is printed to UART (`Components -> ESP32-specific config -> Core dump -> Delay before print to UART`). Value is in ms.

Save core dump to flash
-----------------------

When this option is selected core dumps are saved to special partition on flash. When using default partition table files which are provided with ESP-IDF it automatically
allocates necessary space on flash, But if user wants to use its own layout file together with core dump feature it should define separate partition for core dump
as it is shown below::

  # Name,   Type, SubType, Offset,  Size
  # Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild
  nvs,      data, nvs,     0x9000,  0x6000
  phy_init, data, phy,     0xf000,  0x1000
  factory,  app,  factory, 0x10000, 1M
  coredump, data, coredump,,        64K

There are no special requrements for partition name. It can be choosen according to the user application needs, but partition type should be 'data' and
sub-type should be 'coredump'. Also when choosing partition size note that core dump data structure introduces constant overhead of 20 bytes and per-task overhead of 12 bytes.
This overhead does not include size of TCB and stack for every task. So partirion size should be at least 20 + max tasks number x (12 + TCB size + max task stack size) bytes.

The example of generic command to analyze core dump from flash is: `espcoredump.py -p </path/to/serial/port> info_corefile </path/to/program/elf/file>`
or `espcoredump.py -p </path/to/serial/port> dbg_corefile </path/to/program/elf/file>`

Print core dump to UART
-----------------------

When this option is selected base64-encoded core dumps are printed on UART upon system panic. In this case user should save core dump text body to some file manually and
then run the following command: `espcoredump.py info_corefile -t b64 -c </path/to/saved/base64/text> </path/to/program/elf/file>`
or `espcoredump.py dbg_corefile -t b64 -c </path/to/saved/base64/text> </path/to/program/elf/file>`

Base64-encoded body of core dump will be between the following header and footer::

 ================= CORE DUMP START =================
 <body of base64-encoded core dump, save it to file on disk>
 ================= CORE DUMP END ===================

The `CORE DUMP START` and `CORE DUMP END` lines must not be included in core dump text file.

ROM Functions in Backtraces
---------------------------

It is possible situation that at the moment of crash some tasks or/and crashed task itself have one or more ROM functions in their callstacks.
Since ROM is not part of the program ELF it will be impossible for GDB to parse such callstacks, because it tries to analyse functions' prologues to acomplish that.
In that case callstack printing will be broken with error message at the first ROM function.
To overcome this issue you can use ROM ELF provided by Espressif (https://dl.espressif.com/dl/esp32_rom.elf) and pass it to 'espcoredump.py'.

Running 'espcoredump.py'
------------------------------------

Generic command syntax:

`espcoredump.py [options] command [args]`

:Script Options:
    * --chip,-c {auto,esp32}. Target chip type. Supported values are `auto` and `esp32`.
    * --port,-p PORT. Serial port device.
    * --baud,-b BAUD. Serial port baud rate used when flashing/reading.
:Commands:
    * info_corefile. Retrieve core dump and print useful info.
    * dbg_corefile. Retrieve core dump and start GDB session with it.
:Command Arguments:
    * --debug,-d DEBUG.             Log level (0..3).
    * --gdb,-g GDB.                 Path to gdb to use for data retrieval.
    * --core,-c CORE.               Path to core dump file to use (if skipped core dump will be read from flash).
    * --core-format,-t CORE_FORMAT. Specifies that file passed with "-c" is an ELF ("elf"), dumped raw binary ("raw") or base64-encoded ("b64") format.
    * --off,-o OFF.                 Offset of coredump partition in flash (type `make partition_table` to see it).
    * --save-core,-s SAVE_CORE.     Save core to file. Othwerwise temporary core file will be deleted. Ignored with "-c".
    * --rom-elf,-r ROM_ELF.         Path to ROM ELF file to use (if skipped "esp32_rom.elf" is used).
    * --print-mem,-m                Print memory dump. Used only with "info_corefile".


text:
from modules import connection
from modules import formatter

def get_errors_per_day():
    conn = connection.get_connection()
    conn.execute('''
    WITH t AS
      (SELECT DATE(log.time) AS failureDate,
      ROUND((SUM(CASE WHEN
        SUBSTRING(log.status, 0, 4)::INTEGER >= 400
        THEN 1
        ELSE 0
        END
      ) * 100.0)::DECIMAL /
      (COUNT(log.status)), 1) AS totalErrors
      FROM log GROUP BY DATE (log.time)
      )
    Select CONCAT(t.totalErrors, '%') AS failure,
    to_char(t.failureDate, 'Month DD, YYYY') AS date
    FROM t
    GROUP BY t.totalErrors, t.failureDate
    HAVING t.totalErrors > 1
    ''')

    return conn

def print_errors_per_day():
    print("Errors per day:")
    formatter.repeat_separator()
    for item in get_errors_per_day():
        print(
            "The day that has more than 1% of errors per day are '" +
            str(item[1]) +
            "' with a total percent of errors of '" +str(item[0]) + "'")
    formatter.repeat_separator()


text:
lgtm,codescanning
* More template engines are recognized as sinks for the `js/code-injection` query.
  Affected packages are
    [mustache](https://npmjs.com/package/mustache),
    [handlebars](https://npmjs.com/package/handlebars),
    [dot](https://npmjs.com/package/dot),
    [hogan.js](https://npmjs.com/package/hogan.js)
    [eta](https://npmjs.com/package/eta),
    [squirrelly](https://npmjs.com/package/squirrelly),
    [whiskers](https://npmjs.com/package/whiskers)


text:
@interface NEAudioModel : NSObject

@property (nonatomic ,copy) NSString *cid;
@property (nonatomic ,copy) NSString *cname;

@property (nonatomic , strong) NSArray *tList;

@end


text:
 |

ROS packages for a 2D pedestrian simulator based on social force
model of [Helbing et. al](http://arxiv.org/pdf/cond-mat/9805244.pdf). The implementation is based on an extended version of Christian Gloor's [libpedsim](http://pedsim.silmaril.org/) library which has been extended to include additional behaviors and activities. This packages is useful for robot navigation experiments with crowded scenes which are hard to acquire in practice.

### Features
- Individual walking using social force model for very large crowds in real time
- Group walking using the extended social force model
- Social activities simulation
- Sensors simulation (point clouds in robot frame for people and walls)
- XML based scene design
- Extensive visualization using Rviz
- Option to connect with gazebo for physics reasoning

### Requirements
- ROS with the visualization stack (currently tested on `hydro`, `indigo`, `kinetic` ). For melodic, see the branch `melodic-dev`
- C++11 compiler

### Installation

The default version is now `melodic`. For kinetic please check out the branch `kinetic` which still depends on Qt4.

```
cd [workspace]/src
git clone https://github.com/srl-freiburg/pedsim_ros.git
cd pedsim_ros
git submodule update --init --recursive
cd ../..
catkin build -c  # or catkin_make
```

### Sample usage
```
roslaunch pedsim_simulator simple_pedestrians.launch
```
### Licence
The core `libpedsim` is licensed under LGPL. The ROS integration and extensions are licensed under BSD.

### Developers
* Billy Okal
* Timm Linder

### Contributors
* Dizan Vasquez
* Sven Wehner
* Omar Islas
* Luigi Palmieri

The package is a **work in progress** mainly used in research prototyping. Pull requests and/or issues are highly encouraged.

### Acknowledgements
These packages have been developed in part during the EU FP7 project [SPENCER](spencer.eu)


text:
<?php

namespace Imper86\AllegroApi\Soap\Wsdl;

class doGetMyBidItemsResponse
{

    /**
     * @var int $bidItemsCounter
     */
    protected $bidItemsCounter = null;

    /**
     * @var ArrayOfBiditemstruct $bidItemsList
     */
    protected $bidItemsList = null;

    /**
     * @param int $bidItemsCounter
     * @param ArrayOfBiditemstruct $bidItemsList
     */
    public function __construct($bidItemsCounter = null, $bidItemsList = null)
    {
      $this->bidItemsCounter = $bidItemsCounter;
      $this->bidItemsList = $bidItemsList;
    }

    /**
     * @return int
     */
    public function getBidItemsCounter()
    {
      return $this->bidItemsCounter;
    }

    /**
     * @param int $bidItemsCounter
     * @return \Imper86\AllegroApi\Soap\Wsdl\doGetMyBidItemsResponse
     */
    public function setBidItemsCounter($bidItemsCounter)
    {
      $this->bidItemsCounter = $bidItemsCounter;
      return $this;
    }

    /**
     * @return ArrayOfBiditemstruct
     */
    public function getBidItemsList()
    {
      return $this->bidItemsList;
    }

    /**
     * @param ArrayOfBiditemstruct $bidItemsList
     * @return \Imper86\AllegroApi\Soap\Wsdl\doGetMyBidItemsResponse
     */
    public function setBidItemsList($bidItemsList)
    {
      $this->bidItemsList = $bidItemsList;
      return $this;
    }

}


text:
describe('Inventory', function() {
  var inventory = require('../src/js/inventory');

  it('is empty at beginning', function() {
    var first = inventory.getAnimal(0);
    expect(first).toBeUndefined();
  });

  it('contains an animal after adding it', function() {
    inventory.addAnimal('choupette', 'chien', 'labrador', 2);
    var first = inventory.getAnimal(0);
    expect(first.name).toBe('choupette');
  });
});


text:
import argparse
import shutil
import os
import colorlog

def apply_template(cl, dst, author, name, description):
    desc = description
    if description is None:
        desc = name

    for pn in os.listdir(dst):
        path = os.path.join(dst, pn)

        if os.path.isdir(path):
            apply_template(cl, path, author, name, description)
            continue

        try:
            with open(path) as f:
                data = f.read()
        except Exception as e:
            print(cl.warning('Error reading {0}: {1}'.format(path, e)))
            continue

        data = data.replace('%PRJ_NAME%', name)
        data = data.replace('%PRJ_AUTHOR%', author)
        data = data.replace('%PRJ_DESCRIPTION%', desc)

        try:
            with open(path, 'w') as f:
                f.write(data)
        except Exception as e:
            print(cl.fail('Error writing {0}: {1}'.format(path, e)))
            continue

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='Template applier')
    parser.add_argument('template', help='The template to apply')
    parser.add_argument('-a', '--author', help='Author', required=True)
    parser.add_argument(
        '-p', '--project-name', help='Project name', required=True)
    parser.add_argument('-d', '--description', default=None,
                        help='Description')
    args = parser.parse_args()

    cl = colorlog.ColorLog()

    p = os.path.join(os.environ['STUFF'], 'templates', args.template)

    if not os.path.exists(p):
        print(cl.fail('Template {0} doesn\'t exists'.format(args.template)))
        return
    dest = os.path.join(os.getcwd(), args.project_name)
    try:
        shutil.copytree(p, dest)
    except Exception as e:
        print(cl.fail('Error creating template: {0}'.format(e)))
        return

    apply_template(cl, dest, args.author, args.project_name, args.description)

    print(cl.succeed('Project {0} created!'.format(args.project_name)))

if __name__ == '__main__':
    main()


text:
module Positionable
  VERSION = "1.1.2"
end


text:
FROM ubuntu:20.04

ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update -yqq && apt-get install -yqq software-properties-common > /dev/null
RUN LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php > /dev/null
RUN apt-get update -yqq > /dev/null && \
    apt-get install -yqq wget git unzip libxml2-dev cmake make systemtap-sdt-dev \
                    zlibc zlib1g zlib1g-dev libpcre3 libpcre3-dev libargon2-0-dev libsodium-dev \
                    php7.4 php7.4-common php7.4-dev libphp7.4-embed php7.4-mysql nginx > /dev/null

ADD ./ ./

ENV NGINX_VERSION=1.18.0

RUN git clone -b v0.0.23 --single-branch --depth 1 https://github.com/rryqszq4/ngx_php7.git > /dev/null

RUN wget -q http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz && \
    tar -zxf nginx-${NGINX_VERSION}.tar.gz && \
    cd nginx-${NGINX_VERSION} && \
    export PHP_LIB=/usr/lib && \
    ./configure --user=www --group=www \
            --prefix=/nginx \
            --with-ld-opt="-Wl,-rpath,$PHP_LIB" \
            --add-module=/ngx_php7/third_party/ngx_devel_kit \
            --add-module=/ngx_php7 > /dev/null && \
    make > /dev/null && make install > /dev/null

CMD /nginx/sbin/nginx -c /deploy/nginx_async.conf


text:
package io.leangen.graphql;

import com.fasterxml.jackson.annotation.JsonCreator;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.Scalars;
import graphql.relay.Relay;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLInputObjectType;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLOutputType;
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLType;
import io.leangen.geantyref.GenericTypeReflector;
import io.leangen.geantyref.TypeFactory;
import io.leangen.geantyref.TypeToken;
import io.leangen.graphql.annotations.GraphQLArgument;
import io.leangen.graphql.annotations.GraphQLId;
import io.leangen.graphql.annotations.GraphQLNonNull;
import io.leangen.graphql.execution.GlobalEnvironment;
import io.leangen.graphql.generator.mapping.common.MapToListTypeAdapter;
import io.leangen.graphql.metadata.strategy.query.PublicResolverBuilder;
import io.leangen.graphql.metadata.strategy.type.DefaultTypeTransformer;
import io.leangen.graphql.metadata.strategy.value.ValueMapperFactory;
import io.leangen.graphql.metadata.strategy.value.gson.GsonValueMapperFactory;
import io.leangen.graphql.metadata.strategy.value.jackson.JacksonValueMapperFactory;
import io.leangen.graphql.services.GenericItemRepo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static io.leangen.graphql.support.GraphQLTypeAssertions.assertArgumentsPresent;
import static io.leangen.graphql.support.GraphQLTypeAssertions.assertInputMapOf;
import static io.leangen.graphql.support.GraphQLTypeAssertions.assertListOf;
import static io.leangen.graphql.support.GraphQLTypeAssertions.assertListOfNonNull;
import static io.leangen.graphql.support.GraphQLTypeAssertions.assertListOfRelayIds;
import static io.leangen.graphql.support.GraphQLTypeAssertions.assertMapOf;
import static io.leangen.graphql.support.GraphQLTypeAssertions.assertNonNull;
import static io.leangen.graphql.support.QueryResultAssertions.assertNoErrors;
import static io.leangen.graphql.support.QueryResultAssertions.assertValueAtPathEquals;
import static io.leangen.graphql.util.GraphQLUtils.isRelayId;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@SuppressWarnings("unchecked")
@RunWith(Parameterized.class)
public class GenericsTest {

    @Parameterized.Parameters(name = "{index}: {0}")
    public static Object[] data() {
        return new Object[] { new JacksonValueMapperFactory(), new GsonValueMapperFactory() };
    }

    // IMPORTANT! All type declarations have to stay outside of tests (can not be inlined)
    // as the annotation parser treats them differently and discards the annotations otherwise.
    // This is a JDK8 bug: http://stackoverflow.com/questions/39952812
    private static final AnnotatedType nonNullString = new TypeToken<GenericItemRepo<@GraphQLNonNull String>>() {
    }.getAnnotatedType();
    private static final AnnotatedType dateId = new TypeToken<GenericItemRepo<@GraphQLId(relayId = true) Date>>() {
    }.getAnnotatedType();
    private static final AnnotatedType listOfWildcardNumbers = new TypeToken<GenericItemRepo<@GraphQLNonNull List<? extends Number>>>() {
    }.getAnnotatedType();
    private static final AnnotatedType arrayOfListsOfNumbers = new TypeToken<GenericItemRepo<@GraphQLNonNull List<Number> @GraphQLNonNull []>>() {
    }.getAnnotatedType();

    private static final GlobalEnvironment ENVIRONMENT = new TestGlobalEnvironment();

    @Parameterized.Parameter
    public ValueMapperFactory valueMapperFactory;

    private static final String ERRORS = "Error(s) during query resolution";

    @Test
    public void testNonNullGenerics() {
        GenericItemRepo<@GraphQLNonNull String> nonNullStringService = new GenericItemRepo<>();
        nonNullStringService.addItem("pooch", "Strudel, the poodle");
        nonNullStringService.addItem("booze", "Fire-water");

        GraphQLSchema schemaWithNonNullGenerics = new TestSchemaGenerator()
                .withOperationsFromSingleton(nonNullStringService, nonNullString)
                .withValueMapperFactory(valueMapperFactory)
                .generate();

        GraphQLOutputType itemType = schemaWithNonNullGenerics.getQueryType().getFieldDefinition("item").getType();
        assertNonNull(itemType, Scalars.GraphQLString);

        GraphQLOutputType itemCollectionType = schemaWithNonNullGenerics.getQueryType().getFieldDefinition("allItems").getType();
        assertListOfNonNull(itemCollectionType, Scalars.GraphQLString);

        GraphQLFieldDefinition addOneItem = schemaWithNonNullGenerics.getMutationType().getFieldDefinition("addItem");
        assertEquals(addOneItem.getArguments().size(), 2);
        assertArgumentsPresent(addOneItem, "item", "name");
        assertNonNull(addOneItem.getArgument("item").getType(), Scalars.GraphQLString);

        GraphQLFieldDefinition addManyItems = schemaWithNonNullGenerics.getMutationType().getFieldDefinition("addItems");
        assertEquals(addManyItems.getArguments().size(), 1);
        assertArgumentsPresent(addManyItems, "items");
        assertListOfNonNull(addManyItems.getArgument("items").getType(), Scalars.GraphQLString);

        GraphQL graphQL = GraphQL.newGraphQL(schemaWithNonNullGenerics).build();
        ExecutionResult result = graphQL.execute("{ allItems }");
        assertTrue(ERRORS, result.getErrors().isEmpty());
        assertEquals(new ArrayList<>(nonNullStringService.getAllItems()), ((Map<String, Object>) result.getData()).get("allItems"));
    }

    @Test
    public void testRelayIdGenerics() {
        GenericItemRepo<@GraphQLId(relayId = true) Date> dateIdService = new GenericItemRepo<>();
        final Date firstEvent = new Date(1000);
        final Date secondEvent = new Date(2000);
        dateIdService.addItem("firstEvent", firstEvent);
        dateIdService.addItem("secondEvent", secondEvent);

        GraphQLSchema schemaWithDateIds = new TestSchemaGenerator()
                .withOperationsFromSingleton(dateIdService, dateId)
                .withValueMapperFactory(valueMapperFactory)
                .generate();

        GraphQLOutputType itemType = schemaWithDateIds.getQueryType().getFieldDefinition("item").getType();
        assertTrue(isRelayId(itemType));

        GraphQLOutputType itemCollectionType = schemaWithDateIds.getQueryType().getFieldDefinition("allItems").getType();
        assertListOfRelayIds(itemCollectionType);

        GraphQLFieldDefinition addOneItem = schemaWithDateIds.getMutationType().getFieldDefinition("addItem");
        assertTrue(isRelayId(addOneItem.getArgument("id")));

        GraphQLFieldDefinition addManyItems = schemaWithDateIds.getMutationType().getFieldDefinition("addItems");
        assertListOfRelayIds(addManyItems.getArgument("items").getType());

        GraphQL graphQL = GraphQL.newGraphQL(schemaWithDateIds).build();
        String jsonDate = valueMapperFactory.getValueMapper(Collections.emptyMap(), ENVIRONMENT).toString(firstEvent, GenericTypeReflector.annotate(Date.class));
        String relayId = new Relay().toGlobalId("Query", jsonDate);
        ExecutionResult result = graphQL.execute("{ contains(id: \"" + relayId+ "\") }");
        assertTrue(ERRORS, result.getErrors().isEmpty());
        assertEquals(relayId, ((Map<String, Object>) result.getData()).get("contains"));
        //Search again but using raw (non Relay encoded) ID this time. For now, this is supported.
        result = graphQL.execute("{ contains(id: \"" + jsonDate.replace("\"", "\\\"") + "\") }");
        assertTrue(ERRORS, result.getErrors().isEmpty());
        assertEquals(relayId, ((Map<String, Object>) result.getData()).get("contains"));
    }

    @Test
    public void testWildcardGenerics() {
        GenericItemRepo<@GraphQLNonNull List<? extends Number>> wildcardNumberService = new GenericItemRepo<>();
        wildcardNumberService.addItem("player1", Arrays.asList(12, 13.4, new BigDecimal("4000")));
        wildcardNumberService.addItem("player2", Arrays.asList(new BigDecimal("12.56"), 14.78));

        GraphQLSchema schemaWithGenerics = new TestSchemaGenerator()
                .withOperationsFromSingleton(wildcardNumberService, listOfWildcardNumbers)
                .withValueMapperFactory(valueMapperFactory)
                .generate();

        GraphQLOutputType itemType = schemaWithGenerics.getQueryType().getFieldDefinition("item").getType();
        assertNonNull(itemType, GraphQLList.class);
        assertListOf(((graphql.schema.GraphQLNonNull) itemType).getWrappedType(), Scalars.GraphQLBigDecimal);

        GraphQLOutputType itemCollectionType = schemaWithGenerics.getQueryType().getFieldDefinition("allItems").getType();
        assertListOfNonNull(itemCollectionType, GraphQLList.class);
        assertListOf(((graphql.schema.GraphQLNonNull) ((GraphQLList) itemCollectionType).getWrappedType()).getWrappedType(), Scalars.GraphQLBigDecimal);

        GraphQLFieldDefinition addOneItem = schemaWithGenerics.getMutationType().getFieldDefinition("addItem");
        GraphQLType itemArgType = addOneItem.getArgument("item").getType();
        assertNonNull(itemArgType, GraphQLList.class);
        assertListOf(((graphql.schema.GraphQLNonNull) itemArgType).getWrappedType(), Scalars.GraphQLBigDecimal);

        GraphQL graphQL = GraphQL.newGraphQL(schemaWithGenerics).build();
        ExecutionResult result = graphQL.execute("{ allItems }");
        assertTrue(ERRORS, result.getErrors().isEmpty());
        Object[] expected = wildcardNumberService.getAllItems().toArray();
        Object[] actual = wildcardNumberService.getAllItems().toArray();
        assertArrayEquals(expected, actual);
    }

    @Test
    public void testArrayGenerics() {
        GenericItemRepo<@GraphQLNonNull List<Number> @GraphQLNonNull []> arrayNumberService = new GenericItemRepo<>();
        List<Number>[] array1 = (List<Number>[]) new List[1];
        array1[0] = Arrays.asList(12, 13.4, new BigDecimal("4000"));
        List<Number>[] array2 = (List<Number>[]) new List[1];
        array2[0] = Arrays.asList(new BigDecimal("12.56"), 14.78);
        arrayNumberService.addItem("scores1", array1);
        arrayNumberService.addItem("scores2", array2);

        GraphQLSchema schemaWithGenerics = new TestSchemaGenerator()
                .withOperationsFromSingleton(arrayNumberService, arrayOfListsOfNumbers)
                .withValueMapperFactory(valueMapperFactory)
                .generate();

        GraphQLOutputType itemType = schemaWithGenerics.getQueryType().getFieldDefinition("item").getType();
        assertNonNull(itemType, GraphQLList.class);
        GraphQLType inner = ((graphql.schema.GraphQLNonNull) itemType).getWrappedType();
        assertListOf(inner, graphql.schema.GraphQLNonNull.class);
        inner = ((graphql.schema.GraphQLNonNull) ((GraphQLList) inner).getWrappedType()).getWrappedType();
        assertListOf(inner, Scalars.GraphQLBigDecimal);

        GraphQLFieldDefinition addOneItem = schemaWithGenerics.getMutationType().getFieldDefinition("addItem");
        GraphQLType itemArgType = addOneItem.getArgument("item").getType();
        assertNonNull(itemArgType, GraphQLList.class);
        inner = ((graphql.schema.GraphQLNonNull) itemType).getWrappedType();
        assertListOf(inner, graphql.schema.GraphQLNonNull.class);
        inner = ((graphql.schema.GraphQLNonNull) ((GraphQLList) inner).getWrappedType()).getWrappedType();
        assertListOf(inner, Scalars.GraphQLBigDecimal);

        GraphQL graphQL = GraphQL.newGraphQL(schemaWithGenerics).build();
        ExecutionResult result = graphQL.execute("{ allItems }");
        assertTrue(ERRORS, result.getErrors().isEmpty());
        Object[] expected = arrayNumberService.getAllItems().toArray();
        Object[] actual = arrayNumberService.getAllItems().toArray();
        assertArrayEquals(expected, actual);
    }

    @Test
    public void testVariableBoundGenerics() {
        Type type = TypeFactory.parameterizedClass(EchoService.class, Number.class);
        GraphQLSchema schema = new TestSchemaGenerator()
                .withResolverBuilders(new PublicResolverBuilder("io.leangen"))
                .withOperationsFromSingleton(new EchoService(), type)
                .generate();

        GraphQLFieldDefinition query = schema.getQueryType().getFieldDefinition("echo");
        assertEquals(Scalars.GraphQLBigDecimal, query.getType());
        assertEquals(Scalars.GraphQLBigDecimal, query.getArgument("in").getType());

        GraphQL graphQL = GraphQL.newGraphQL(schema).build();
        ExecutionResult result = graphQL.execute("{ echo (in: 3) }");
        assertTrue(ERRORS, result.getErrors().isEmpty());
        assertValueAtPathEquals(new BigDecimal(3), result, "echo");
    }

    @Test
    public void testMissingGenerics() {
        Type type = TypeFactory.parameterizedClass(EchoService.class, MissingGenerics.class);
        GraphQLSchema schema = new TestSchemaGenerator()
                .withValueMapperFactory(valueMapperFactory)
                .withOperationsFromSingleton(new EchoService(), type, new PublicResolverBuilder())
                .withTypeTransformer(new DefaultTypeTransformer(true, true))
                .withTypeAdapters(new MapToListTypeAdapter())
                .generate();

        GraphQLFieldDefinition query = schema.getQueryType().getFieldDefinition("echo");
        GraphQLObjectType output = (GraphQLObjectType) query.getType();
        assertMapOf(output.getFieldDefinition("raw").getType(), GraphQLScalarType.class, GraphQLScalarType.class);
        assertMapOf(output.getFieldDefinition("unbounded").getType(), GraphQLScalarType.class, GraphQLScalarType.class);

        GraphQLInputObjectType input = (GraphQLInputObjectType) query.getArgument("in").getType();
        assertInputMapOf(input.getFieldDefinition("raw").getType(), GraphQLScalarType.class, GraphQLScalarType.class);
        assertInputMapOf(input.getFieldDefinition("unbounded").getType(), GraphQLScalarType.class, GraphQLScalarType.class);

        GraphQL runtime = GraphQL.newGraphQL(schema).build();
        ExecutionResult result = runtime.execute("{" +
                "echo (in: {" +
                "   raw: [{key: 2, value: 3}]" +
                "   unbounded: [{key: 2, value: 3}]" +
                "}) {" +
                "   raw {key, value}" +
                "   unbounded {key, value}" +
                "}}");
        assertNoErrors(result);
        assertValueAtPathEquals(2, result, "echo.raw.0.key");
        assertValueAtPathEquals(3, result, "echo.raw.0.value");
        assertValueAtPathEquals(2, result, "echo.unbounded.0.key");
        assertValueAtPathEquals(3, result, "echo.unbounded.0.value");
    }

    public interface GenericEcho<T> {
        <S extends T> S echo(S input);
    }

    public static class EchoService<G> implements GenericEcho<G> {
        @Override
        public <S extends G> S echo(@GraphQLArgument(name = "in") S input) {
            return input;
        }
    }

    public static class MissingGenerics {
        private final Map raw;
        private final Map<?, ?> unbounded;

        @JsonCreator
        public MissingGenerics(Map raw, Map<?, ?> unbounded) {
            this.raw = raw;
            this.unbounded = unbounded;
        }

        public Map<Integer, Integer> getRaw() {
            return raw;
        }

        public Map<?, ?> getUnbounded() {
            return unbounded;
        }
    }
}