text:
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Primitives;
using BusinessObjects.Devices;
using Logging;
using Common;
using Common.Commands;
using Configuration;

namespace PinballClient.ClientComms
{
    [Export(typeof(IClientToLocalCommsController))]
    public class ClientToLocalCommsController: IClientToLocalCommsController
    {
        public IClientCommsController CurrentController { get; set; }

        public IRsConfiguration Configuration { get; set; }

        public MachineState MachineState { get; set; }

        // TODO: May need to links these to return back to the client to update its state

        public void SendConfigureMachineMessage(bool useHardware)
        {
            if (null != Configuration)
            {
                Configuration.MachineConfiguration.UseHardware = useHardware;
                Configuration.WriteMachineToFile();
            }
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent configure machine message to Local Client");
        }

        public void SendConfigureDeviceMessage(Switch device, bool removeDevice = false)
        {
            if (null != Configuration)
            {
                // Update local state
                MachineState.UpdateDevice(device, removeDevice);

                // Write to config
                Configuration.MachineConfiguration.Switches = MachineState.Devices.AllSwitches();
                Configuration.WriteMachineToFile();
            }

            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent configure device message to Local Client: " + device.Name);
        }

        public void SendConfigureDeviceMessage(Coil device, bool removeDevice = false)
        {
            if (null != Configuration)
            {
                // Update local state
                MachineState.UpdateDevice(device, removeDevice);

                // Write to config
                Configuration.MachineConfiguration.Coils = MachineState.Devices.AllCoils();
                Configuration.WriteMachineToFile();
            }
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent configure device message to Local Client: " + device.Name);
        }

        public void SendConfigureDeviceMessage(StepperMotor device, bool removeDevice = false)
        {
            if (null != Configuration)
            {
                // Update local state
                MachineState.UpdateDevice(device, removeDevice);

                // Write to config
                Configuration.MachineConfiguration.StepperMotors = MachineState.Devices.AllStepperMotors();
                Configuration.WriteMachineToFile();
            }
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent configure device message to Local Client: " + device.Name);
        }

        public void SendConfigureDeviceMessage(Servo device, bool removeDevice = false)
        {
            if (null != Configuration)
            {
                // Update local state
                MachineState.UpdateDevice(device, removeDevice);

                // Write to config
                Configuration.MachineConfiguration.Servos = MachineState.Devices.AllServos();
                Configuration.WriteMachineToFile();
            }
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent configure device message to Local Client: " + device.Name);
        }

        public void SendConfigureDeviceMessage(Led device, bool removeDevice = false)
        {
            if (null != Configuration)
            {
                // Update local state
                MachineState.UpdateDevice(device, removeDevice);

                // Write to config
                Configuration.MachineConfiguration.Leds = MachineState.Devices.AllLeds();
                Configuration.WriteMachineToFile();
            }
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent configure device message to Local Client: " + device.Name);
        }

        public void SendCommandDeviceMessage(Switch device, SwitchCommand command)
        {
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent command device message to Local Client: " + device.Name + " Command: " + command);
        }

        public void SendCommandDeviceMessage(Coil device, CoilCommand command)
        {
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent command device message to Local Client: " + device.Name + " Command: " + command);
        }

        public void SendCommandDeviceMessage(StepperMotor device, StepperMotorCommand command)
        {
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent command device message to Local Client: " + device.Name + " Command: " + command);
        }

        public void SendCommandDeviceMessage(Servo device, ServoCommand command)
        {
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent command device message to Local Client: " + device.Name + " Command: " + command);
        }

        public void SendCommandDeviceMessage(Led device, LedCommand command)
        {
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent command device message to Local Client: " + device.Name + " Command: " + command);
        }

        public void RequestSettings()
        {
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent request settings message to Local Client");
        }

        public void RequestFile(string mediaFilename)
        {
            RsLog.LogMessage(LogEventType.Info, OriginatorType.System, "Client", "", "Sent request file message to Local Client");
        }

    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ProductService.cs" company="">
//   Copyright (c) 2013 Aaron Zhang, for OrderDynamics coding test.  All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace WingtipToys.Core.Services
{
    using System.Collections.Generic;

    using NHibernate.Criterion;

    using WingtipToys.Core.Entities;
    using WingtipToys.Core.Infrastructure.Persistence;

    /// <summary>
    ///     Services for Product related persistence functions.
    /// </summary>
    public class ProductService : IProductService
    {
        #region Public Methods and Operators

        /// <summary>
        /// Gets the products.
        /// </summary>
        /// <param name="categoryName">Name of the category.</param>
        /// <param name="searchKeywords">The search keywords.</param>
        /// <returns>
        /// The products.
        /// </returns>
        public virtual IEnumerable<Product> GetProducts(string categoryName, string searchKeywords)
        {
            var query = SessionManager.Instance.CurrentSession.QueryOver<Product>();

            if (!string.IsNullOrWhiteSpace(searchKeywords))
            {
                string trimmedSearchKeywords = searchKeywords.Trim();

                query.Where(Restrictions.Disjunction()
                    .Add(Restrictions.On<Product>(product => product.ProductName).IsInsensitiveLike(trimmedSearchKeywords, MatchMode.Anywhere))
                    .Add(Restrictions.On<Product>(product => product.Description).IsInsensitiveLike(trimmedSearchKeywords, MatchMode.Anywhere)));
            }

            string trimmedCategoryName = categoryName == null ? null : categoryName.Trim();
            return query.JoinQueryOver(product => product.Category)
                .Where(category => category.CategoryName == trimmedCategoryName)
                .List();
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
drop table if exists `cache`;

create table `cache`
(
    `id`  varchar(128) not null,
    `expire` integer,
    `data`   LONGBLOB,
    primary key (`id`)
) engine InnoDB;


text:
CODE_EQ(s::State) = if length(s.code) > 1
  push!(s.boolean, pop!(s.code) === pop!(s.code))
end

CODE_APPEND(s::State) = if length(s.code) > 1
  first = pop!(s.code)
  second = peek(s.code)
  s.code[end] = vcat(isa(first, Vector) ? first : [first],
    isa(second, Vector) ? second : [second])
end

CODE_ATOM(s::State) = if !isempty(s.code)
  push!(s.boolean, !isa(pop!(s.code), Vector))
end

CODE_CAR(s::State) = if !isempty(s.code) && isa(s.code[end], Vector)
  s.code[end] = isempty(s.code[end]) ? [] : s.code[end][1]
end

CODE_CDR(s::State) = if !isempty(s.code)
  top = peek(s.code)
  if !isa(top, Vector) || length(top) < 2
    s.code[end] = []
  else
    s.code[end] = top[2:end]
  end
end

CODE_CONS(s::State) = if length(s.code) > 1
  top = pop!(s.code)
  s.code[end] = vcat([peek(s.code)], isa(top, Vector) ? top : [top])
end

CODE_CONTAINER(s::State) = if length(s.code) > 1
  s.code[end] = container(pop!(s.code), peek(s.code))
end

CODE_CONTAINS(s::State) = if length(s.code) > 1
  first = pop!(s.code)
  second = pop!(s.code)
  push!(s.boolean, !isempty(container(second, first)))
end

CODE_DISCREPANCY(s::State) = if length(s.code) > 1
  a = isa(peek(s.code), Vector) ? pop!(s.code) : [pop!(s.code)]
  b = isa(peek(s.code), Vector) ? pop!(s.code) : [pop!(s.code)]
  dis = zero(Int32)

  for v in setdiff(a, b)
    dis += count(x -> x == v, a)
  end
  for v in setdiff(b, a)
    dis += count(x -> x == v, b)
  end

  push!(s.integer, dis)
end

CODE_DO(s::State) = if !isempty(s.code)
  push!(s.exec, Symbol("CODE.POP"), peek(s.code))
end

CODE_DO_STAR(s::State) = if !isempty(s.code)
  push!(s.exec, pop!(s.code))
end

CODE_DO_STAR_COUNT(s::State) = if !isempty(s.code) && !isempty(s.integer) && s.integer[end] > 0
  push!(s.exec, pop!(s.code), Symbol("EXEC.DO*COUNT"))
end

CODE_DO_STAR_TIMES(s::State) = if !isempty(s.code) && !isempty(s.integer) && s.integer[end] > 0
  push!(s.exec, pop!(s.code), Symbol("EXEC.DO*TIMES"))
end

CODE_DO_STAR_RANGE(s::State) = if !isempty(s.code) && length(s.integer) > 1
  push!(s.exec, pop!(s.code), Symbol("EXEC.DO*RANGE"))
end

CODE_DUP(s::State) = if !isempty(s.code)
  push!(s.code, peek(s.code))
end

CODE_EXTRACT(s::State) = if !isempty(s.code) && !isempty(s.integer)
  index = abs(pop!(s.integer))
  code = peek(s.code)

  # Do nothing (other than pop from the INTEGER stack) if the top of the CODE
  # stack is an atom.
  if !isa(code, Vector)
    return
  end

  # Calculate the index modulo the number of points in the given expression.
  index %= num_points(code)

  # Depth-first search for the given index.
  q = Any[code]
  j = 0
  while !isempty(q)
    expr = pop!(q)

    # Put the extracted sub-expression on top of the CODE stack.
    if j == index
      s.code[end] = expr
      break
    end

    # Add sub-expressions to the front of the processing queue, from
    # left to right.
    if isa(expr, Vector)
      for k in length(expr):-1:1
        push!(q, expr[k])
      end
    end

    j += 1
  end
end

CODE_FLUSH(s::State) = empty!(s.code)

CODE_FROM_BOOLEAN(s::State) = if !isempty(s.boolean)
  push!(s.code, pop!(s.boolean))
end

CODE_FROM_FLOAT(s::State) = if !isempty(s.float)
  push!(s.code, pop!(s.float))
end

CODE_FROM_INTEGER(s::State) = if !isempty(s.integer)
  push!(s.code, pop!(s.integer))
end

CODE_FROM_NAME(s::State) = if !isempty(s.name)
  push!(s.code, pop!(s.name))
end

CODE_IF(s::State) = if !isempty(s.boolean) && length(s.code) > 1
  a = pop!(s.code)
  b = pop!(s.code)
  push!(s.exec, pop!(s.boolean) ? b : a)
end

CODE_INSERT(s::State) = if !isempty(s.integer) && length(s.code) > 1
  cntr = pop!(s.code)
  item = pop!(s.code)

  # Calculate the insertion point.
  i = abs(pop!(s.integer)) % num_points(cntr)

  # Push the modified container back onto the stack.
  push!(s.code, insert_at_point!(cntr, item, i))
end

#
# TODO
#
CODE_INSTRUCTIONS(s::State) = return

CODE_LENGTH(s::State) = if !isempty(s.code)
  top = pop!(s.code)
  push!(s.integer, isa(top, Vector) ? length(top) : 1)
end

CODE_LIST(s::State) = if length(s.code) > 1
  s.code[end] = [pop!(s.code), peek(s.code)]
end

CODE_MEMBER(s::State) = if length(s.code) > 1
  first = isa(peek(s.code), Vector) ? pop!(s.code) : [pop!(s.code)]
  push!(s.boolean, in(pop!(s.code), first))
end

CODE_NOOP(s::State) = return

CODE_NTH(s::State) = if !isempty(s.integer) && !isempty(s.code) && isa(s.code[end], Vector)
  if isempty(peek(s.code))
    s.code[end] = []
  else
    s.code[end] = s.code[end][1 + (abs(pop!(s.integer)) % length(peek(s.code)))]
  end
end

# Zeroth CDR is the first CDR in this implementation.
# Seems to be implied by the Push 3.0 language reference.
CODE_NTH_CDR(s::State) = if !isempty(s.code) && !isempty(s.integer)
  i = pop!(s.integer)
  if !isa(peek(s.code), Vector) || isempty(peek(s.code))
    s.code[end] = []
  else
    i = abs(i) % length(peek(s.code))
    deleteat!(s.code[end], 1:i+1)
  end
end

CODE_NULL(s::State) = if !isempty(s.code)
  top = pop!(s.code)
  push!(s.boolean, isa(top, Vector) && isempty(top))
end

CODE_POP(s::State) = !isempty(s.code) && pop!(s.code)

#
# TODO
#
CODE_POSITION(s::State) = return

CODE_QUOTE(s::State) = s.flag_quote_code = true

CODE_ROT(s::State) = if length(s.code) > 2
  s.code[end], s.code[end-1], s.code[end-2] =
    s.code[end-1], s.code[end-2], s.code[end]
end

CODE_SHOVE(s::State) = if !isempty(s.integer) && !isempty(s.code)
  shove!(s.code, pop!(s.integer))
end

CODE_SIZE(s::State) = if !isempty(s.code)
  push!(s.integer, num_points(pop!(s.code)))
end

CODE_STACK_DEPTH(s::State) = push!(s.integer, length(s.code))

#
# TODO
#
CODE_SUBST(s::State) = return

CODE_SWAP(s::State) = if length(s.code) >= 2
  s.code[end], s.code[end-1] = s.code[end-1], s.code[end]
end

CODE_YANK(s::State) = if !isempty(s.integer) && !isempty(s.code)
  yank!(s.code, pop!(s.integer))
end

CODE_YANK_DUP(s::State) = if !isempty(s.integer) && !isempty(s.code)
  yankdup!(s.code, pop!(s.integer))
end

CODE_RAND(s::State) = push!(s.code, random_code(s))

CODE_DEFINE(s::State) = if !isempty(s.code) && !isempty(s.name)
  s.definitions[pop!(s.name)] = pop!(s.code)
end

CODE_DEFINITION(s::State) = if !isempty(s.name) && haskey(s.definitions, pop!(s.name))
  push!(s.code, deepcopy(s.definitions[pop!(s.name)]))
end

Push.register("CODE.=",                CODE_EQ)
Push.register("CODE.APPEND",           CODE_APPEND)
Push.register("CODE.ATOM",             CODE_ATOM)
Push.register("CODE.CAR",              CODE_CAR)
Push.register("CODE.CDR",              CODE_CDR)
Push.register("CODE.CONS",             CODE_CONS)
Push.register("CODE.CONTAINER",        CODE_CONTAINER)
Push.register("CODE.CONTAINS",         CODE_CONTAINS)
Push.register("CODE.DEFINE",           CODE_DEFINE)
Push.register("CODE.DEFINITION",       CODE_DEFINITION)
Push.register("CODE.DISCREPANCY",      CODE_DISCREPANCY)
Push.register("CODE.DO",               CODE_DO)
Push.register("CODE.DO*",              CODE_DO_STAR)
Push.register("CODE.DO*COUNT",         CODE_DO_STAR_COUNT)
Push.register("CODE.DO*RANGE",         CODE_DO_STAR_RANGE)
Push.register("CODE.DO*TIMES",         CODE_DO_STAR_TIMES)
Push.register("CODE.DUP",              CODE_DUP)
Push.register("CODE.EXTRACT",          CODE_EXTRACT)
Push.register("CODE.FLUSH",            CODE_FLUSH)
Push.register("CODE.FROMBOOLEAN",      CODE_FROM_BOOLEAN)
Push.register("CODE.FROMINTEGER",      CODE_FROM_INTEGER)
Push.register("CODE.FROMNAME",         CODE_FROM_NAME)
Push.register("CODE.IF",               CODE_IF)
Push.register("CODE.INSERT",           CODE_INSERT)
Push.register("CODE.INSTRUCTIONS",     CODE_INSTRUCTIONS)
Push.register("CODE.LENGTH",           CODE_LENGTH)
Push.register("CODE.LIST",             CODE_LIST)
Push.register("CODE.MEMBER",           CODE_MEMBER)
Push.register("CODE.NOOP",             CODE_NOOP)
Push.register("CODE.NTH",              CODE_NTH)
Push.register("CODE.NTHCDR",           CODE_NTH_CDR)
Push.register("CODE.NULL",             CODE_NULL)
Push.register("CODE.POP",              CODE_POP)
Push.register("CODE.POSITION",         CODE_POSITION)
Push.register("CODE.QUOTE",            CODE_QUOTE)
Push.register("CODE.RAND",             CODE_RAND)
Push.register("CODE.ROT",              CODE_ROT)
Push.register("CODE.SHOVE",            CODE_SHOVE)
Push.register("CODE.SIZE",             CODE_SIZE)
Push.register("CODE.STACKDEPTH",       CODE_STACK_DEPTH)
Push.register("CODE.SUBST",            CODE_SUBST)
Push.register("CODE.SWAP",             CODE_SWAP)
Push.register("CODE.YANK",             CODE_YANK)
Push.register("CODE.YANKDUP",          CODE_YANK_DUP)


text:
package io.gatling.http.request.builder.polling

import scala.concurrent.duration.FiniteDuration

import io.gatling.core.session._
import io.gatling.http.action.HttpActionBuilder
import io.gatling.http.action.polling.{ PollingStartBuilder, PollingStopBuilder }
import io.gatling.http.request.builder.HttpRequestBuilder

object Polling {
  private val DefaultPollerName = SessionPrivateAttributes.generatePrivateAttribute("http.polling")

  val Default: Polling = new Polling(DefaultPollerName)
}

final class Polling(pollerName: String) {
  def pollerName(pollerName: String): Polling = new Polling(pollerName)

  def every(period: FiniteDuration): PollingEveryStep = new PollingEveryStep(pollerName, period)

  def stop: HttpActionBuilder = new PollingStopBuilder(pollerName)
}

final class PollingEveryStep(pollerName: String, period: FiniteDuration) {
  def exec(requestBuilder: HttpRequestBuilder): HttpActionBuilder =
    new PollingStartBuilder(pollerName, period, requestBuilder)
}


text:
package org.apache.ignite.internal.processors.cache.warmup;

import java.util.Arrays;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.QueryIndex;

/**
 * Person.
 */
class Person {
    /** Id. */
    final long id;

    /** Name. */
    final String name;

    /** Organization id. */
    final long orgId;

    /**
     * Constructor.
     *
     * @param id Id.
     * @param name Name.
     * @param orgId Organization id.
     */
    Person(long id, String name, long orgId) {
        this.id = id;
        this.name = name;
        this.orgId = orgId;
    }

    /**
     * Create query entity.
     *
     * @return New query entity.
     */
    static QueryEntity queryEntity() {
        return new QueryEntity(String.class, Person.class)
            .addQueryField("id", Long.class.getName(), null)
            .addQueryField("name", String.class.getName(), null)
            .addQueryField("orgId", Long.class.getName(), null)
            .setIndexes(Arrays.asList(
                new QueryIndex("id"),
                new QueryIndex("name"),
                new QueryIndex("orgId")
            ));
    }
}


text:
// <copyright file="DieRollerFactory.cs" company="DarthPedro">
// Copyright (c) 2017 DarthPedro. All rights reserved.
// </copyright>

using OnePlat.DiceNotation.DieRoller;
using System;

namespace DiceRoller.Mvc.Services
{
    /// <summary>
    /// Factory class for getting the appropriate die roller.
    /// </summary>
    public class DieRollerFactory
    {
        /// <summary>
        /// Gets the die roller based on specified type.
        /// </summary>
        /// <param name="type">Type string</param>
        /// <param name="tracker">Die roll tracker to use</param>
        /// <returns>Instance of die roller, or null if none found.</returns>
        public IDieRoller GetDieRoller(string type, IDieRollTracker tracker = null)
        {
            IDieRoller roller = null;

            if (type == typeof(ConstantDieRoller).ToString())
            {
                roller = new ConstantDieRoller();
            }
            else if (type == typeof(RandomDieRoller).ToString())
            {
                roller = new RandomDieRoller(tracker);
            }
            else if (type == typeof(CryptoDieRoller).ToString())
            {
                roller = new CryptoDieRoller(tracker);
            }
            else if (type == typeof(MathNetDieRoller).ToString())
            {
                roller = new MathNetDieRoller(tracker);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(type));
            }

            return roller;
        }
    }
}


text:
using Parrot.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Shapes;
using Wind.Containers;

namespace Parrot.Displays
{
    public class pSpacer : pControl
    {
        public UniformGrid Element;

        public bool IsHoriztonal = false;
        public bool IsFill = true;

        public pSpacer(string InstanceName)
        {
            //Set Element info setup
            Element = new UniformGrid();
            Element.Name = InstanceName;
            Type = "Spacer";

            //Set "Clear" appearance to all elements
            Element.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
        }

        public void SetProperties(System.Windows.Media.Color FillColor, double Width, bool IsHorizontalAlignment, bool IsFilled)
        {

            Element.Children.Clear();

            IsHoriztonal = IsHorizontalAlignment;
            IsFill = IsFilled;

            if (IsHoriztonal)
            {
                Element.Width = double.NaN;
                Element.HorizontalAlignment = HorizontalAlignment.Stretch;
                if (Width == 0)
                {
                    Element.Height = double.NaN;
                    Element.VerticalAlignment= VerticalAlignment.Stretch;
                } else {
                    Element.Height = Width;
                }
            }
            else
            {
                Element.Height = double.NaN;
                Element.VerticalAlignment = VerticalAlignment.Stretch;
                if (Width == 0)
                {
                    Element.Width = double.NaN;
                    Element.HorizontalAlignment = HorizontalAlignment.Stretch;
                }
                else
                {
                    Element.Width = Width;
                }
            }

            if (IsFilled)
            {
                Element.Background = new SolidColorBrush(FillColor);
            }
            else
            {
                Element.Background = new SolidColorBrush(Colors.Transparent);

                Label LabelA = new Label();
                LabelA.BorderBrush = new SolidColorBrush(FillColor);

                Element.Children.Add(LabelA);

                if (IsHoriztonal)
                {
                    Element.Columns = 1;
                    Element.Rows = 2;

                    Grid.SetColumn(LabelA, 0);
                    Grid.SetRow(LabelA, 0);

                    LabelA.BorderThickness = new Thickness(0, 0, 0, 1);
                }
                else
                {
                    Element.Columns = 2;
                    Element.Rows = 1;

                    Grid.SetColumn(LabelA, 0);
                    Grid.SetRow(LabelA, 0);

                    LabelA.BorderThickness = new Thickness(0, 0,1, 0);
                }

            }

        }

        public override void SetFill()
        {
            Element.Background = Graphics.WpfFill;
        }

        public override void SetStroke()
        {
        }

        public override void SetSize()
        {
            if (Graphics.Width < 1) { Element.Width = double.NaN; } else { Element.Width = Graphics.Width; }
            if (Graphics.Height < 1) { Element.Height = double.NaN; } else { Element.Height = Graphics.Height; }
        }

        public override void SetMargin()
        {
            Element.Margin = new Thickness(Graphics.Margin[0], Graphics.Margin[1], Graphics.Margin[2], Graphics.Margin[3]);
        }

        public override void SetPadding()
        {
        }

        public override void SetFont()
        {
        }
    }
}


text:
package org.apache.camel.guice.util;

import java.lang.annotation.Annotation;
import java.util.Map;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Scope;

import org.apache.camel.guice.inject.Injectors;
import org.apache.camel.guice.support.CloseFailedException;
import org.apache.camel.guice.support.HasScopeAnnotation;
import org.apache.camel.guice.support.internal.CloseErrorsImpl;

/**
 * Represents a scope which caches objects around until the scope is closed.
 *
 * The scope can be closed as many times as required - there is no need to
 * recreate the scope instance each time a scope goes out of scope.
 *
 * @version
 */
public class CloseableScope implements Scope, HasScopeAnnotation {

    private Class<? extends Annotation> scopeAnnotation;
    private final Map<Key<?>, Object> map = Maps.newHashMap();

    @Inject
    private Injector injector;

    public CloseableScope(Class<? extends Annotation> scopeAnnotation) {
        this.scopeAnnotation = scopeAnnotation;
    }

    @SuppressWarnings("unchecked")
    public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
        return new CachingProvider<T>() {
            public T get() {
                Object o;
                synchronized (map) {
                    o = map.get(key);
                    if (o == null) {
                        o = creator.get();
                        map.put(key, o);
                    }
                }
                return (T) o;
            }

            public T getCachedValue() {
                synchronized (map) {
                    return (T) map.get(key);
                }
            }
        };
    }

    /**
     * Closes all of the objects within this scope using the given injector and
     * scope annotation and clears the scope
     */
    public void close() throws CloseFailedException {
        close(injector);
    }

    /**
     * Closes all of the objects within the given injector of the specified
     * scope and clears the scope
     */
    public void close(Injector injector) throws CloseFailedException {
        Preconditions.checkNotNull(injector, "injector");
        CloseErrorsImpl errors = new CloseErrorsImpl(this);
        Injectors.close(injector, scopeAnnotation, errors);

        synchronized (map) {
            map.clear();
        }
        errors.throwIfNecessary();
    }

    public Class<? extends Annotation> getScopeAnnotation() {
        return scopeAnnotation;
    }
}


text:
package com.touwolf.mailchimp.data.condiction.types;

public class McSelectMerge extends McParent {
    private McSelectMergeOpEnum op;

    private String field;

    private String value;

    /**
     * Whether the segment value matches exactly, doesn't match, is blank, or isn't blank.
     * Possible Values:
     * <p>
     * is
     * not
     * blank
     * blank_not
     */
    public McSelectMergeOpEnum getOp() {
        return op;
    }

    public void setOp(McSelectMergeOpEnum op) {
        this.op = op;
    }

    /**
     * The select merge segment field.
     */
    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    /**
     * The value to compare.
     */
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


text:
<?php

namespace Ups\Entity;

use DOMDocument;
use Ups\NodeInterface;

/**
 * Class Translate
 * @package Ups\Entity
 */
class Translate implements NodeInterface
{
    /**
     * @deprecated
     */
    public $LanguageCode;

    /**
     * @deprecated
     */
    public $DialectCode;

    /**
     * @deprecated
     */
    public $Code;

    /**
     * @var string
     */
    private $languageCode;

    /**
     * @var string
     */
    private $dialectCode;

    /**
     * @var string
     */
    private $code;

    /**
     * @var string
     */
    private $locale;

    /**
     * @param null $response
     */
    public function __construct($response = null)
    {
        if (null != $response) {
            if (isset($response->LanguageCode)) {
                $this->setLanguageCode($response->LanguageCode);
            }
            if (isset($response->DialectCode)) {
                $this->setDialectCode($response->DialectCode);
            }
            if (isset($response->Code)) {
                $this->setCode($response->Code);
            }
            if (isset($response->Locale)) {
                $this->setLocale($response->Locale);
            }
        }
    }

    /**
     * @param DOMDocument|null $document
     * @return \DOMElement
     */
    public function toNode(DOMDocument $document = null)
    {
        if (null === $document) {
            $document = new DOMDocument();
        }

        $node = $document->createElement('Translate');

        $node->appendChild($document->createElement('LanguageCode', $this->getLanguageCode()));

        if ($this->getCode()) {
            $node->appendChild($document->createElement('Code', $this->getCode()));
        }

        if ($this->getDialectCode()) {
            $node->appendChild($document->createElement('DialectCode', $this->getDialectCode()));
        }

        if ($this->getLocale()) {
            $node->appendChild($document->createElement('Locale', $this->getLocale()));
        }

        return $node;
    }

    /**
     * @return string|null
     */
    public function getLanguageCode()
    {
        return $this->languageCode;
    }

    /**
     * @param mixed $languageCode
     */
    public function setLanguageCode($languageCode)
    {
        $this->LanguageCode = $languageCode;
        $this->languageCode = $languageCode;
    }

    /**
     * @return string|null
     */
    public function getDialectCode()
    {
        return $this->dialectCode;
    }

    /**
     * @param mixed $dialectCode
     */
    public function setDialectCode($dialectCode)
    {
        $this->DialectCode = $dialectCode;
        $this->dialectCode = $dialectCode;
    }

    /**
     * @return null|string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @param mixed $code
     */
    public function setCode($code)
    {
        $this->Code = $code;
        $this->code = $code;
    }

    /**
     * @return null|string
     */
    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * @param mixed $locale
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;
    }
}


text:
#include <aws/swf/model/ListActivityTypesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::SWF::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListActivityTypesRequest::ListActivityTypesRequest() :
    m_domainHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_registrationStatus(RegistrationStatus::NOT_SET),
    m_registrationStatusHasBeenSet(false),
    m_nextPageTokenHasBeenSet(false),
    m_maximumPageSize(0),
    m_maximumPageSizeHasBeenSet(false),
    m_reverseOrder(false),
    m_reverseOrderHasBeenSet(false)
{
}

Aws::String ListActivityTypesRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_domainHasBeenSet)
  {
   payload.WithString("domain", m_domain);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_registrationStatusHasBeenSet)
  {
   payload.WithString("registrationStatus", RegistrationStatusMapper::GetNameForRegistrationStatus(m_registrationStatus));
  }

  if(m_nextPageTokenHasBeenSet)
  {
   payload.WithString("nextPageToken", m_nextPageToken);

  }

  if(m_maximumPageSizeHasBeenSet)
  {
   payload.WithInteger("maximumPageSize", m_maximumPageSize);

  }

  if(m_reverseOrderHasBeenSet)
  {
   payload.WithBool("reverseOrder", m_reverseOrder);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection ListActivityTypesRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "SimpleWorkflowService.ListActivityTypes"));
  return headers;

}


text:
import { createStore, applyMiddleware } from 'redux';
import promise from '../../src';
import errorMiddleware from './middleware';
import { createLogger } from 'redux-logger';

const reducer = (state) => state;

// Custom error middleware should go before the promise middleware
const store = createStore(reducer, null, applyMiddleware(
  errorMiddleware,
  promise,
  createLogger({ collapsed: true }),
));

export default store;


text:
Demo.components.Viewport = function(spec) {
    'use strict';
    let that = {
        get left() { return spec.left; },
        get top() { return spec.top; },
        get width() { return 1; },    // Width and height are always going to be 1
        get height() { return 1; },
        get buffer() { return spec.buffer; } // This can't really be any larger than world.buffer, guess I could protect against that.
    };

    Object.defineProperty(that, 'right', {
        get: function() { return that.left + that.width; },
        enumerable: true,
        configurable: false
    });

    Object.defineProperty(that, 'bottom', {
        get: function() { return that.top + that.height; },
        enumerable: true,
        configurable: false
    });

    // ------------------------------------------------------------------
    //
    // This function is used to ensure the viewport moves to keep the specified
    // model visible.  Based upon the game-world location of the model and the
    // current state of the viewport, the viewport is updated to ensure the
    // model is visible.  The viewport is analagous to a camera.
    //
    // ------------------------------------------------------------------
    that.update = function(model) {
        //
        // Compute how close the model is to the visible edge in screen-space
        // and move the viewport accordingly.
        let diffRight = that.right - model.center.x;
        let diffLeft = Math.abs(spec.left - model.center.x);
        let diffBottom = that.bottom - model.center.y;
        let diffTop = Math.abs(spec.top - model.center.y);

        if (diffRight < spec.buffer) {
            spec.left += (spec.buffer - diffRight);
        }

        if (diffLeft < spec.buffer) {
            spec.left -= (spec.buffer - diffLeft);
        }

        if (diffBottom < spec.buffer) {
            spec.top += (spec.buffer - diffBottom);
        }

        if (diffTop < spec.buffer) {
            spec.top -= (spec.buffer - diffTop);
        }
    };

    // ------------------------------------------------------------------
    //
    // Use to specify new properties for the viewport.
    //
    // ------------------------------------------------------------------
    that.set = function(left, top, buffer) {
        spec.left = left;
        spec.top = top;
        spec.buffer = buffer;
    };

    return that;
};


text:
require 'test_helper'

class FeedUtilsTest < Test::Unit::TestCase
  def test_something_for_real
    flunk "hey buddy, you should probably rename this file and start testing for real"
  end
end


text:
from templates import Plugin
from zipfile import ZipFile
import base64
from Crypto.Cipher import Blowfish
import xml.etree.ElementTree as ET

class Thoughtcrime(Plugin):
	NAME = "thoughtcrime"

	def recon(self):
		return 'res/raw/blfs.key' in self.zipfile.namelist() and \
			'res/raw/config.cfg' in self.zipfile.namelist()

	def extract(self):
		raw_resources = filter(lambda x: x.startswith('res/raw'), self.zipfile.namelist())
		iv = "12345678" # this has to be done better
		key = self.zipfile.open('res/raw/blfs.key').read()
		key = ''.join(['%x' % ord(x) for x in key])[0:50]
		cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
		decode = base64.b64decode(self.zipfile.open('res/raw/config.cfg').read())
		config = cipher.decrypt(decode)
		config = config[:config.find('</config>')+9]
		config = ET.fromstring(config)
		c2 = config.findall('.//data')[0].get('url_main').split(';')
		phone = config.findall('.//data')[0].get('phone_number')
		return {'c2': c2, 'phone': phone}


text:
extern disp_dev_t gdisp;
struct disp_device* disp_vdevice_register(struct disp_vdevice_init_data *data);
s32 disp_vdevice_unregister(struct disp_device *vdevice);
s32 disp_vdevice_get_source_ops(struct disp_vdevice_source_ops *ops);

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `collections\hash\table.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>table.rs.html -- source</title>

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

    <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079

// Copyright 2014-2015 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.

use alloc::heap::{EMPTY, allocate, deallocate};

use cmp;
use hash::{BuildHasher, Hash, Hasher};
use intrinsics::needs_drop;
use marker;
use mem::{align_of, size_of};
use mem;
use ops::{Deref, DerefMut};
use ptr::{self, Unique, Shared};

use self::BucketState::*;

const EMPTY_BUCKET: u64 = 0;

/// The raw hashtable, providing safe-ish access to the unzipped and highly
/// optimized arrays of hashes, keys, and values.
///
/// This design uses less memory and is a lot faster than the naive
/// `Vec<Option<u64, K, V>>`, because we don't pay for the overhead of an
/// option on every element, and we get a generally more cache-aware design.
///
/// Essential invariants of this structure:
///
///   - if t.hashes[i] == EMPTY_BUCKET, then `Bucket::at_index(&t, i).raw`
///     points to 'undefined' contents. Don't read from it. This invariant is
///     enforced outside this module with the `EmptyBucket`, `FullBucket`,
///     and `SafeHash` types.
///
///   - An `EmptyBucket` is only constructed at an index with
///     a hash of EMPTY_BUCKET.
///
///   - A `FullBucket` is only constructed at an index with a
///     non-EMPTY_BUCKET hash.
///
///   - A `SafeHash` is only constructed for non-`EMPTY_BUCKET` hash. We get
///     around hashes of zero by changing them to 0x8000_0000_0000_0000,
///     which will likely map to the same bucket, while not being confused
///     with "empty".
///
///   - All three "arrays represented by pointers" are the same length:
///     `capacity`. This is set at creation and never changes. The arrays
///     are unzipped to save space (we don't have to pay for the padding
///     between odd sized elements, such as in a map from u64 to u8), and
///     be more cache aware (scanning through 8 hashes brings in at most
///     2 cache lines, since they're all right beside each other).
///
/// You can kind of think of this module/data structure as a safe wrapper
/// around just the "table" part of the hashtable. It enforces some
/// invariants at the type level and employs some performance trickery,
/// but in general is just a tricked out `Vec<Option<u64, K, V>>`.
#[cfg_attr(stage0, unsafe_no_drop_flag)]
pub struct RawTable<K, V> {
    capacity: usize,
    size: usize,
    hashes: Unique<u64>,

    // Because K/V do not appear directly in any of the types in the struct,
    // inform rustc that in fact instances of K and V are reachable from here.
    marker: marker::PhantomData<(K, V)>,
}

unsafe impl<K: Send, V: Send> Send for RawTable<K, V> {}
unsafe impl<K: Sync, V: Sync> Sync for RawTable<K, V> {}

struct RawBucket<K, V> {
    hash: *mut u64,

    // We use *const to ensure covariance with respect to K and V
    key: *const K,
    val: *const V,
    _marker: marker::PhantomData<(K, V)>,
}

impl<K, V> Copy for RawBucket<K, V> {}
impl<K, V> Clone for RawBucket<K, V> {
    fn clone(&self) -> RawBucket<K, V> {
        *self
    }
}

pub struct Bucket<K, V, M> {
    raw: RawBucket<K, V>,
    idx: usize,
    table: M,
}

impl<K, V, M: Copy> Copy for Bucket<K, V, M> {}
impl<K, V, M: Copy> Clone for Bucket<K, V, M> {
    fn clone(&self) -> Bucket<K, V, M> {
        *self
    }
}

pub struct EmptyBucket<K, V, M> {
    raw: RawBucket<K, V>,
    idx: usize,
    table: M,
}

pub struct FullBucket<K, V, M> {
    raw: RawBucket<K, V>,
    idx: usize,
    table: M,
}

pub type EmptyBucketImm<'table, K, V> = EmptyBucket<K, V, &'table RawTable<K, V>>;
pub type FullBucketImm<'table, K, V> = FullBucket<K, V, &'table RawTable<K, V>>;

pub type EmptyBucketMut<'table, K, V> = EmptyBucket<K, V, &'table mut RawTable<K, V>>;
pub type FullBucketMut<'table, K, V> = FullBucket<K, V, &'table mut RawTable<K, V>>;

pub enum BucketState<K, V, M> {
    Empty(EmptyBucket<K, V, M>),
    Full(FullBucket<K, V, M>),
}

// A GapThenFull encapsulates the state of two consecutive buckets at once.
// The first bucket, called the gap, is known to be empty.
// The second bucket is full.
pub struct GapThenFull<K, V, M> {
    gap: EmptyBucket<K, V, ()>,
    full: FullBucket<K, V, M>,
}

/// A hash that is not zero, since we use a hash of zero to represent empty
/// buckets.
#[derive(PartialEq, Copy, Clone)]
pub struct SafeHash {
    hash: u64,
}

impl SafeHash {
    /// Peek at the hash value, which is guaranteed to be non-zero.
    #[inline(always)]
    pub fn inspect(&self) -> u64 {
        self.hash
    }
}

/// We need to remove hashes of 0. That's reserved for empty buckets.
/// This function wraps up `hash_keyed` to be the only way outside this
/// module to generate a SafeHash.
pub fn make_hash<T: ?Sized, S>(hash_state: &S, t: &T) -> SafeHash
    where T: Hash,
          S: BuildHasher
{
    let mut state = hash_state.build_hasher();
    t.hash(&mut state);
    // We need to avoid 0 in order to prevent collisions with
    // EMPTY_HASH. We can maintain our precious uniform distribution
    // of initial indexes by unconditionally setting the MSB,
    // effectively reducing 64-bits hashes to 63 bits.
    SafeHash { hash: 0x8000_0000_0000_0000 | state.finish() }
}

// `replace` casts a `*u64` to a `*SafeHash`. Since we statically
// ensure that a `FullBucket` points to an index with a non-zero hash,
// and a `SafeHash` is just a `u64` with a different name, this is
// safe.
//
// This test ensures that a `SafeHash` really IS the same size as a
// `u64`. If you need to change the size of `SafeHash` (and
// consequently made this test fail), `replace` needs to be
// modified to no longer assume this.
#[test]
fn can_alias_safehash_as_u64() {
    assert_eq!(size_of::<SafeHash>(), size_of::<u64>())
}

impl<K, V> RawBucket<K, V> {
    unsafe fn offset(self, count: isize) -> RawBucket<K, V> {
        RawBucket {
            hash: self.hash.offset(count),
            key: self.key.offset(count),
            val: self.val.offset(count),
            _marker: marker::PhantomData,
        }
    }
}

// Buckets hold references to the table.
impl<K, V, M> FullBucket<K, V, M> {
    /// Borrow a reference to the table.
    pub fn table(&self) -> &M {
        &self.table
    }
    /// Move out the reference to the table.
    pub fn into_table(self) -> M {
        self.table
    }
    /// Get the raw index.
    pub fn index(&self) -> usize {
        self.idx
    }
}

impl<K, V, M> EmptyBucket<K, V, M> {
    /// Borrow a reference to the table.
    pub fn table(&self) -> &M {
        &self.table
    }
}

impl<K, V, M> Bucket<K, V, M> {
    /// Get the raw index.
    pub fn index(&self) -> usize {
        self.idx
    }
}

impl<K, V, M> Deref for FullBucket<K, V, M>
    where M: Deref<Target = RawTable<K, V>>
{
    type Target = RawTable<K, V>;
    fn deref(&self) -> &RawTable<K, V> {
        &self.table
    }
}

/// `Put` is implemented for types which provide access to a table and cannot be invalidated
///  by filling a bucket. A similar implementation for `Take` is possible.
pub trait Put<K, V> {
    unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V>;
}

impl<'t, K, V> Put<K, V> for &'t mut RawTable<K, V> {
    unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> {
        *self
    }
}

impl<K, V, M> Put<K, V> for Bucket<K, V, M>
    where M: Put<K, V>
{
    unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> {
        self.table.borrow_table_mut()
    }
}

impl<K, V, M> Put<K, V> for FullBucket<K, V, M>
    where M: Put<K, V>
{
    unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> {
        self.table.borrow_table_mut()
    }
}

impl<K, V, M: Deref<Target = RawTable<K, V>>> Bucket<K, V, M> {
    pub fn new(table: M, hash: SafeHash) -> Bucket<K, V, M> {
        Bucket::at_index(table, hash.inspect() as usize)
    }

    pub fn at_index(table: M, ib_index: usize) -> Bucket<K, V, M> {
        // if capacity is 0, then the RawBucket will be populated with bogus pointers.
        // This is an uncommon case though, so avoid it in release builds.
        debug_assert!(table.capacity() > 0,
                      "Table should have capacity at this point");
        let ib_index = ib_index & (table.capacity() - 1);
        Bucket {
            raw: unsafe { table.first_bucket_raw().offset(ib_index as isize) },
            idx: ib_index,
            table: table,
        }
    }

    pub fn first(table: M) -> Bucket<K, V, M> {
        Bucket {
            raw: table.first_bucket_raw(),
            idx: 0,
            table: table,
        }
    }

    /// Reads a bucket at a given index, returning an enum indicating whether
    /// it's initialized or not. You need to match on this enum to get
    /// the appropriate types to call most of the other functions in
    /// this module.
    pub fn peek(self) -> BucketState<K, V, M> {
        match unsafe { *self.raw.hash } {
            EMPTY_BUCKET => {
                Empty(EmptyBucket {
                    raw: self.raw,
                    idx: self.idx,
                    table: self.table,
                })
            }
            _ => {
                Full(FullBucket {
                    raw: self.raw,
                    idx: self.idx,
                    table: self.table,
                })
            }
        }
    }

    /// Modifies the bucket pointer in place to make it point to the next slot.
    pub fn next(&mut self) {
        self.idx += 1;
        let range = self.table.capacity();
        // This code is branchless thanks to a conditional move.
        let dist = if self.idx & (range - 1) == 0 {
            1 - range as isize
        } else {
            1
        };
        unsafe {
            self.raw = self.raw.offset(dist);
        }
    }
}

impl<K, V, M: Deref<Target = RawTable<K, V>>> EmptyBucket<K, V, M> {
    #[inline]
    pub fn next(self) -> Bucket<K, V, M> {
        let mut bucket = self.into_bucket();
        bucket.next();
        bucket
    }

    #[inline]
    pub fn into_bucket(self) -> Bucket<K, V, M> {
        Bucket {
            raw: self.raw,
            idx: self.idx,
            table: self.table,
        }
    }

    pub fn gap_peek(self) -> Option<GapThenFull<K, V, M>> {
        let gap = EmptyBucket {
            raw: self.raw,
            idx: self.idx,
            table: (),
        };

        match self.next().peek() {
            Full(bucket) => {
                Some(GapThenFull {
                    gap: gap,
                    full: bucket,
                })
            }
            Empty(..) => None,
        }
    }
}

impl<K, V, M> EmptyBucket<K, V, M>
    where M: Put<K, V>
{
    /// Puts given key and value pair, along with the key's hash,
    /// into this bucket in the hashtable. Note how `self` is 'moved' into
    /// this function, because this slot will no longer be empty when
    /// we return! A `FullBucket` is returned for later use, pointing to
    /// the newly-filled slot in the hashtable.
    ///
    /// Use `make_hash` to construct a `SafeHash` to pass to this function.
    pub fn put(mut self, hash: SafeHash, key: K, value: V) -> FullBucket<K, V, M> {
        unsafe {
            *self.raw.hash = hash.inspect();
            ptr::write(self.raw.key as *mut K, key);
            ptr::write(self.raw.val as *mut V, value);

            self.table.borrow_table_mut().size += 1;
        }

        FullBucket {
            raw: self.raw,
            idx: self.idx,
            table: self.table,
        }
    }
}

impl<K, V, M: Deref<Target = RawTable<K, V>>> FullBucket<K, V, M> {
    #[inline]
    pub fn next(self) -> Bucket<K, V, M> {
        let mut bucket = self.into_bucket();
        bucket.next();
        bucket
    }

    #[inline]
    pub fn into_bucket(self) -> Bucket<K, V, M> {
        Bucket {
            raw: self.raw,
            idx: self.idx,
            table: self.table,
        }
    }

    /// Duplicates the current position. This can be useful for operations
    /// on two or more buckets.
    pub fn stash(self) -> FullBucket<K, V, Self> {
        FullBucket {
            raw: self.raw,
            idx: self.idx,
            table: self,
        }
    }

    /// Get the distance between this bucket and the 'ideal' location
    /// as determined by the key's hash stored in it.
    ///
    /// In the cited blog posts above, this is called the "distance to
    /// initial bucket", or DIB. Also known as "probe count".
    pub fn displacement(&self) -> usize {
        // Calculates the distance one has to travel when going from
        // `hash mod capacity` onwards to `idx mod capacity`, wrapping around
        // if the destination is not reached before the end of the table.
        (self.idx.wrapping_sub(self.hash().inspect() as usize)) & (self.table.capacity() - 1)
    }

    #[inline]
    pub fn hash(&self) -> SafeHash {
        unsafe { SafeHash { hash: *self.raw.hash } }
    }

    /// Gets references to the key and value at a given index.
    pub fn read(&self) -> (&K, &V) {
        unsafe { (&*self.raw.key, &*self.raw.val) }
    }
}

// We take a mutable reference to the table instead of accepting anything that
// implements `DerefMut` to prevent fn `take` from being called on `stash`ed
// buckets.
impl<'t, K, V> FullBucket<K, V, &'t mut RawTable<K, V>> {
    /// Removes this bucket's key and value from the hashtable.
    ///
    /// This works similarly to `put`, building an `EmptyBucket` out of the
    /// taken bucket.
    pub fn take(mut self) -> (EmptyBucket<K, V, &'t mut RawTable<K, V>>, K, V) {
        self.table.size -= 1;

        unsafe {
            *self.raw.hash = EMPTY_BUCKET;
            (EmptyBucket {
                raw: self.raw,
                idx: self.idx,
                table: self.table,
            },
             ptr::read(self.raw.key),
             ptr::read(self.raw.val))
        }
    }
}

// This use of `Put` is misleading and restrictive, but safe and sufficient for our use cases
// where `M` is a full bucket or table reference type with mutable access to the table.
impl<K, V, M> FullBucket<K, V, M>
    where M: Put<K, V>
{
    pub fn replace(&mut self, h: SafeHash, k: K, v: V) -> (SafeHash, K, V) {
        unsafe {
            let old_hash = ptr::replace(self.raw.hash as *mut SafeHash, h);
            let old_key = ptr::replace(self.raw.key as *mut K, k);
            let old_val = ptr::replace(self.raw.val as *mut V, v);

            (old_hash, old_key, old_val)
        }
    }
}

impl<K, V, M> FullBucket<K, V, M>
    where M: Deref<Target = RawTable<K, V>> + DerefMut
{
    /// Gets mutable references to the key and value at a given index.
    pub fn read_mut(&mut self) -> (&mut K, &mut V) {
        unsafe { (&mut *(self.raw.key as *mut K), &mut *(self.raw.val as *mut V)) }
    }
}

impl<'t, K, V, M> FullBucket<K, V, M>
    where M: Deref<Target = RawTable<K, V>> + 't
{
    /// Exchange a bucket state for immutable references into the table.
    /// Because the underlying reference to the table is also consumed,
    /// no further changes to the structure of the table are possible;
    /// in exchange for this, the returned references have a longer lifetime
    /// than the references returned by `read()`.
    pub fn into_refs(self) -> (&'t K, &'t V) {
        unsafe { (&*self.raw.key, &*self.raw.val) }
    }
}

impl<'t, K, V, M> FullBucket<K, V, M>
    where M: Deref<Target = RawTable<K, V>> + DerefMut + 't
{
    /// This works similarly to `into_refs`, exchanging a bucket state
    /// for mutable references into the table.
    pub fn into_mut_refs(self) -> (&'t mut K, &'t mut V) {
        unsafe { (&mut *(self.raw.key as *mut K), &mut *(self.raw.val as *mut V)) }
    }
}

impl<K, V, M> GapThenFull<K, V, M>
    where M: Deref<Target = RawTable<K, V>>
{
    #[inline]
    pub fn full(&self) -> &FullBucket<K, V, M> {
        &self.full
    }

    pub fn shift(mut self) -> Option<GapThenFull<K, V, M>> {
        unsafe {
            *self.gap.raw.hash = mem::replace(&mut *self.full.raw.hash, EMPTY_BUCKET);
            ptr::copy_nonoverlapping(self.full.raw.key, self.gap.raw.key as *mut K, 1);
            ptr::copy_nonoverlapping(self.full.raw.val, self.gap.raw.val as *mut V, 1);
        }

        let FullBucket { raw: prev_raw, idx: prev_idx, .. } = self.full;

        match self.full.next().peek() {
            Full(bucket) => {
                self.gap.raw = prev_raw;
                self.gap.idx = prev_idx;

                self.full = bucket;

                Some(self)
            }
            Empty(..) => None,
        }
    }
}

/// Rounds up to a multiple of a power of two. Returns the closest multiple
/// of `target_alignment` that is higher or equal to `unrounded`.
///
/// # Panics
///
/// Panics if `target_alignment` is not a power of two.
#[inline]
fn round_up_to_next(unrounded: usize, target_alignment: usize) -> usize {
    assert!(target_alignment.is_power_of_two());
    (unrounded + target_alignment - 1) & !(target_alignment - 1)
}

#[test]
fn test_rounding() {
    assert_eq!(round_up_to_next(0, 4), 0);
    assert_eq!(round_up_to_next(1, 4), 4);
    assert_eq!(round_up_to_next(2, 4), 4);
    assert_eq!(round_up_to_next(3, 4), 4);
    assert_eq!(round_up_to_next(4, 4), 4);
    assert_eq!(round_up_to_next(5, 4), 8);
}

// Returns a tuple of (key_offset, val_offset),
// from the start of a mallocated array.
#[inline]
fn calculate_offsets(hashes_size: usize,
                     keys_size: usize,
                     keys_align: usize,
                     vals_align: usize)
                     -> (usize, usize, bool) {
    let keys_offset = round_up_to_next(hashes_size, keys_align);
    let (end_of_keys, oflo) = keys_offset.overflowing_add(keys_size);

    let vals_offset = round_up_to_next(end_of_keys, vals_align);

    (keys_offset, vals_offset, oflo)
}

// Returns a tuple of (minimum required malloc alignment, hash_offset,
// array_size), from the start of a mallocated array.
fn calculate_allocation(hash_size: usize,
                        hash_align: usize,
                        keys_size: usize,
                        keys_align: usize,
                        vals_size: usize,
                        vals_align: usize)
                        -> (usize, usize, usize, bool) {
    let hash_offset = 0;
    let (_, vals_offset, oflo) = calculate_offsets(hash_size, keys_size, keys_align, vals_align);
    let (end_of_vals, oflo2) = vals_offset.overflowing_add(vals_size);

    let align = cmp::max(hash_align, cmp::max(keys_align, vals_align));

    (align, hash_offset, end_of_vals, oflo || oflo2)
}

#[test]
fn test_offset_calculation() {
    assert_eq!(calculate_allocation(128, 8, 15, 1, 4, 4),
               (8, 0, 148, false));
    assert_eq!(calculate_allocation(3, 1, 2, 1, 1, 1), (1, 0, 6, false));
    assert_eq!(calculate_allocation(6, 2, 12, 4, 24, 8), (8, 0, 48, false));
    assert_eq!(calculate_offsets(128, 15, 1, 4), (128, 144, false));
    assert_eq!(calculate_offsets(3, 2, 1, 1), (3, 5, false));
    assert_eq!(calculate_offsets(6, 12, 4, 8), (8, 24, false));
}

impl<K, V> RawTable<K, V> {
    /// Does not initialize the buckets. The caller should ensure they,
    /// at the very least, set every hash to EMPTY_BUCKET.
    unsafe fn new_uninitialized(capacity: usize) -> RawTable<K, V> {
        if capacity == 0 {
            return RawTable {
                size: 0,
                capacity: 0,
                hashes: Unique::new(EMPTY as *mut u64),
                marker: marker::PhantomData,
            };
        }

        // No need for `checked_mul` before a more restrictive check performed
        // later in this method.
        let hashes_size = capacity * size_of::<u64>();
        let keys_size = capacity * size_of::<K>();
        let vals_size = capacity * size_of::<V>();

        // Allocating hashmaps is a little tricky. We need to allocate three
        // arrays, but since we know their sizes and alignments up front,
        // we just allocate a single array, and then have the subarrays
        // point into it.
        //
        // This is great in theory, but in practice getting the alignment
        // right is a little subtle. Therefore, calculating offsets has been
        // factored out into a different function.
        let (malloc_alignment, hash_offset, size, oflo) = calculate_allocation(hashes_size,
                                                                               align_of::<u64>(),
                                                                               keys_size,
                                                                               align_of::<K>(),
                                                                               vals_size,
                                                                               align_of::<V>());

        assert!(!oflo, "capacity overflow");

        // One check for overflow that covers calculation and rounding of size.
        let size_of_bucket = size_of::<u64>()
                                 .checked_add(size_of::<K>())
                                 .unwrap()
                                 .checked_add(size_of::<V>())
                                 .unwrap();
        assert!(size >=
                capacity.checked_mul(size_of_bucket)
                        .expect("capacity overflow"),
                "capacity overflow");

        let buffer = allocate(size, malloc_alignment);
        if buffer.is_null() {
            ::alloc::oom()
        }

        let hashes = buffer.offset(hash_offset as isize) as *mut u64;

        RawTable {
            capacity: capacity,
            size: 0,
            hashes: Unique::new(hashes),
            marker: marker::PhantomData,
        }
    }

    fn first_bucket_raw(&self) -> RawBucket<K, V> {
        let hashes_size = self.capacity * size_of::<u64>();
        let keys_size = self.capacity * size_of::<K>();

        let buffer = *self.hashes as *const u8;
        let (keys_offset, vals_offset, oflo) = calculate_offsets(hashes_size,
                                                                 keys_size,
                                                                 align_of::<K>(),
                                                                 align_of::<V>());
        debug_assert!(!oflo, "capacity overflow");
        unsafe {
            RawBucket {
                hash: *self.hashes,
                key: buffer.offset(keys_offset as isize) as *const K,
                val: buffer.offset(vals_offset as isize) as *const V,
                _marker: marker::PhantomData,
            }
        }
    }

    /// Creates a new raw table from a given capacity. All buckets are
    /// initially empty.
    pub fn new(capacity: usize) -> RawTable<K, V> {
        unsafe {
            let ret = RawTable::new_uninitialized(capacity);
            ptr::write_bytes(*ret.hashes, 0, capacity);
            ret
        }
    }

    /// The hashtable's capacity, similar to a vector's.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// The number of elements ever `put` in the hashtable, minus the number
    /// of elements ever `take`n.
    pub fn size(&self) -> usize {
        self.size
    }

    fn raw_buckets(&self) -> RawBuckets<K, V> {
        RawBuckets {
            raw: self.first_bucket_raw(),
            hashes_end: unsafe { self.hashes.offset(self.capacity as isize) },
            marker: marker::PhantomData,
        }
    }

    pub fn iter(&self) -> Iter<K, V> {
        Iter {
            iter: self.raw_buckets(),
            elems_left: self.size(),
        }
    }

    pub fn iter_mut(&mut self) -> IterMut<K, V> {
        IterMut {
            iter: self.raw_buckets(),
            elems_left: self.size(),
            _marker: marker::PhantomData,
        }
    }

    pub fn into_iter(self) -> IntoIter<K, V> {
        let RawBuckets { raw, hashes_end, .. } = self.raw_buckets();
        // Replace the marker regardless of lifetime bounds on parameters.
        IntoIter {
            iter: RawBuckets {
                raw: raw,
                hashes_end: hashes_end,
                marker: marker::PhantomData,
            },
            table: self,
        }
    }

    pub fn drain(&mut self) -> Drain<K, V> {
        let RawBuckets { raw, hashes_end, .. } = self.raw_buckets();
        // Replace the marker regardless of lifetime bounds on parameters.
        Drain {
            iter: RawBuckets {
                raw: raw,
                hashes_end: hashes_end,
                marker: marker::PhantomData,
            },
            table: unsafe { Shared::new(self) },
            marker: marker::PhantomData,
        }
    }

    /// Returns an iterator that copies out each entry. Used while the table
    /// is being dropped.
    unsafe fn rev_move_buckets(&mut self) -> RevMoveBuckets<K, V> {
        let raw_bucket = self.first_bucket_raw();
        RevMoveBuckets {
            raw: raw_bucket.offset(self.capacity as isize),
            hashes_end: raw_bucket.hash,
            elems_left: self.size,
            marker: marker::PhantomData,
        }
    }
}

/// A raw iterator. The basis for some other iterators in this module. Although
/// this interface is safe, it's not used outside this module.
struct RawBuckets<'a, K, V> {
    raw: RawBucket<K, V>,
    hashes_end: *mut u64,

    // Strictly speaking, this should be &'a (K,V), but that would
    // require that K:'a, and we often use RawBuckets<'static...> for
    // move iterations, so that messes up a lot of other things. So
    // just use `&'a (K,V)` as this is not a publicly exposed type
    // anyway.
    marker: marker::PhantomData<&'a ()>,
}

// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for RawBuckets<'a, K, V> {
    fn clone(&self) -> RawBuckets<'a, K, V> {
        RawBuckets {
            raw: self.raw,
            hashes_end: self.hashes_end,
            marker: marker::PhantomData,
        }
    }
}

impl<'a, K, V> Iterator for RawBuckets<'a, K, V> {
    type Item = RawBucket<K, V>;

    fn next(&mut self) -> Option<RawBucket<K, V>> {
        while self.raw.hash != self.hashes_end {
            unsafe {
                // We are swapping out the pointer to a bucket and replacing
                // it with the pointer to the next one.
                let prev = ptr::replace(&mut self.raw, self.raw.offset(1));
                if *prev.hash != EMPTY_BUCKET {
                    return Some(prev);
                }
            }
        }

        None
    }
}

/// An iterator that moves out buckets in reverse order. It leaves the table
/// in an inconsistent state and should only be used for dropping
/// the table's remaining entries. It's used in the implementation of Drop.
struct RevMoveBuckets<'a, K, V> {
    raw: RawBucket<K, V>,
    hashes_end: *mut u64,
    elems_left: usize,

    // As above, `&'a (K,V)` would seem better, but we often use
    // 'static for the lifetime, and this is not a publicly exposed
    // type.
    marker: marker::PhantomData<&'a ()>,
}

impl<'a, K, V> Iterator for RevMoveBuckets<'a, K, V> {
    type Item = (K, V);

    fn next(&mut self) -> Option<(K, V)> {
        if self.elems_left == 0 {
            return None;
        }

        loop {
            debug_assert!(self.raw.hash != self.hashes_end);

            unsafe {
                self.raw = self.raw.offset(-1);

                if *self.raw.hash != EMPTY_BUCKET {
                    self.elems_left -= 1;
                    return Some((ptr::read(self.raw.key), ptr::read(self.raw.val)));
                }
            }
        }
    }
}

/// Iterator over shared references to entries in a table.
pub struct Iter<'a, K: 'a, V: 'a> {
    iter: RawBuckets<'a, K, V>,
    elems_left: usize,
}

unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {}
unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {}

// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Iter<'a, K, V> {
    fn clone(&self) -> Iter<'a, K, V> {
        Iter {
            iter: self.iter.clone(),
            elems_left: self.elems_left,
        }
    }
}

/// Iterator over mutable references to entries in a table.
pub struct IterMut<'a, K: 'a, V: 'a> {
    iter: RawBuckets<'a, K, V>,
    elems_left: usize,
    // To ensure invariance with respect to V
    _marker: marker::PhantomData<&'a mut V>,
}

unsafe impl<'a, K: Sync, V: Sync> Sync for IterMut<'a, K, V> {}
// Both K: Sync and K: Send are correct for IterMut's Send impl,
// but Send is the more useful bound
unsafe impl<'a, K: Send, V: Send> Send for IterMut<'a, K, V> {}

/// Iterator over the entries in a table, consuming the table.
pub struct IntoIter<K, V> {
    table: RawTable<K, V>,
    iter: RawBuckets<'static, K, V>,
}

unsafe impl<K: Sync, V: Sync> Sync for IntoIter<K, V> {}
unsafe impl<K: Send, V: Send> Send for IntoIter<K, V> {}

/// Iterator over the entries in a table, clearing the table.
pub struct Drain<'a, K: 'a, V: 'a> {
    table: Shared<RawTable<K, V>>,
    iter: RawBuckets<'static, K, V>,
    marker: marker::PhantomData<&'a RawTable<K, V>>,
}

unsafe impl<'a, K: Sync, V: Sync> Sync for Drain<'a, K, V> {}
unsafe impl<'a, K: Send, V: Send> Send for Drain<'a, K, V> {}

impl<'a, K, V> Iterator for Iter<'a, K, V> {
    type Item = (&'a K, &'a V);

    fn next(&mut self) -> Option<(&'a K, &'a V)> {
        self.iter.next().map(|bucket| {
            self.elems_left -= 1;
            unsafe { (&*bucket.key, &*bucket.val) }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.elems_left, Some(self.elems_left))
    }
}
impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
    fn len(&self) -> usize {
        self.elems_left
    }
}

impl<'a, K, V> Iterator for IterMut<'a, K, V> {
    type Item = (&'a K, &'a mut V);

    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
        self.iter.next().map(|bucket| {
            self.elems_left -= 1;
            unsafe { (&*bucket.key, &mut *(bucket.val as *mut V)) }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.elems_left, Some(self.elems_left))
    }
}
impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
    fn len(&self) -> usize {
        self.elems_left
    }
}

impl<K, V> Iterator for IntoIter<K, V> {
    type Item = (SafeHash, K, V);

    fn next(&mut self) -> Option<(SafeHash, K, V)> {
        self.iter.next().map(|bucket| {
            self.table.size -= 1;
            unsafe {
                (SafeHash { hash: *bucket.hash }, ptr::read(bucket.key), ptr::read(bucket.val))
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = self.table.size();
        (size, Some(size))
    }
}
impl<K, V> ExactSizeIterator for IntoIter<K, V> {
    fn len(&self) -> usize {
        self.table.size()
    }
}

impl<'a, K, V> Iterator for Drain<'a, K, V> {
    type Item = (SafeHash, K, V);

    #[inline]
    fn next(&mut self) -> Option<(SafeHash, K, V)> {
        self.iter.next().map(|bucket| {
            unsafe {
                (**self.table).size -= 1;
                (SafeHash { hash: ptr::replace(bucket.hash, EMPTY_BUCKET) },
                 ptr::read(bucket.key),
                 ptr::read(bucket.val))
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = unsafe { (**self.table).size() };
        (size, Some(size))
    }
}
impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
    fn len(&self) -> usize {
        unsafe {
            (**self.table).size()
        }
    }
}

impl<'a, K: 'a, V: 'a> Drop for Drain<'a, K, V> {
    fn drop(&mut self) {
        for _ in self {}
    }
}

impl<K: Clone, V: Clone> Clone for RawTable<K, V> {
    fn clone(&self) -> RawTable<K, V> {
        unsafe {
            let mut new_ht = RawTable::new_uninitialized(self.capacity());

            {
                let cap = self.capacity();
                let mut new_buckets = Bucket::first(&mut new_ht);
                let mut buckets = Bucket::first(self);
                while buckets.index() != cap {
                    match buckets.peek() {
                        Full(full) => {
                            let (h, k, v) = {
                                let (k, v) = full.read();
                                (full.hash(), k.clone(), v.clone())
                            };
                            *new_buckets.raw.hash = h.inspect();
                            ptr::write(new_buckets.raw.key as *mut K, k);
                            ptr::write(new_buckets.raw.val as *mut V, v);
                        }
                        Empty(..) => {
                            *new_buckets.raw.hash = EMPTY_BUCKET;
                        }
                    }
                    new_buckets.next();
                    buckets.next();
                }
            };

            new_ht.size = self.size();

            new_ht
        }
    }
}

impl<K, V> Drop for RawTable<K, V> {
    #[unsafe_destructor_blind_to_params]
    fn drop(&mut self) {
        if self.capacity == 0 {
            return;
        }

        // This is done in reverse because we've likely partially taken
        // some elements out with `.into_iter()` from the front.
        // Check if the size is 0, so we don't do a useless scan when
        // dropping empty tables such as on resize.
        // Also avoid double drop of elements that have been already moved out.
        unsafe {
            if needs_drop::<(K, V)>() {
                // avoid linear runtime for types that don't need drop
                for _ in self.rev_move_buckets() {}
            }
        }

        let hashes_size = self.capacity * size_of::<u64>();
        let keys_size = self.capacity * size_of::<K>();
        let vals_size = self.capacity * size_of::<V>();
        let (align, _, size, oflo) = calculate_allocation(hashes_size,
                                                          align_of::<u64>(),
                                                          keys_size,
                                                          align_of::<K>(),
                                                          vals_size,
                                                          align_of::<V>());

        debug_assert!(!oflo, "should be impossible");

        unsafe {
            deallocate(*self.hashes as *mut u8, size, align);
            // Remember how everything was allocated out of one buffer
            // during initialization? We only need one call to free here.
        }
    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)