text:
A curated list of awesome Go frameworks, libraries and software. Inspired by [awesome-python](https://github.com/vinta/awesome-python).

### Contributing

Please take a quick gander at the [contribution guidelines](https://github.com/avelino/awesome-go/blob/master/CONTRIBUTING.md) first. Thanks to all [contributors](https://github.com/avelino/awesome-go/graphs/contributors); you rock!

### Contents

- [Awesome Go](#awesome-go)
    - [Audio & Music](#audiomusic)
    - [Authentication & OAuth](#authentication--oauth)
    - [CSS Preprocessors](#css-preprocessors)
    - [CUI](#cui)
    - [Database](#database)
    - [Database Drivers](#database-drivers)
    - [Date & Time](#date--time)
    - [Distributed Systems](#distributed-systems)
    - [Email](#email)
    - [Embeddable Scripting Languages](#embeddable-scripting-languages)
    - [Forms](#forms)
    - [Game Development](#game-development)
    - [Generation & Generics](#generation--generics)
    - [GUI](#gui)
    - [Images](#images)
    - [Logging](#logging)
    - [Machine Learning](#machine-learning)
    - [Messaging](#messaging)
    - [Miscellaneous](#miscellaneous)
    - [Natural Language Processing](#natural-language-processing)
    - [Networking](#networking)
    - [OpenGL](#opengl)
    - [ORM](#orm)
    - [Package Management](#package-management)
    - [Science and Data Analysis](#science-and-data-analysis)
    - [Serialization](#serialization)
    - [Template Engines](#template-engines)
    - [Testing](#testing)
    - [Text Processing](#text-processing)
    - [Third-party APIs](#third-party-apis)
    - [Utilities](#utilities)
    - [Video](#video)
    - [Web Frameworks](#web-frameworks)
        - [Middlewares](#middlewares)
    - [Windows](#windows)

- [Tools](#tools)
    - [Code Analysis](#code-analysis)
    - [Editor Plugins](#editor-plugins)
    - [Software Packages](#software-packages)
        - [DevOps Tools](#devops-tools)
        - [Other Software](#other-software)

- [Resources](#resources)
    - [Benchmarks](#benchmarks)
    - [Conferences](#conferences)
    - [E-Books](#e-books)
    - [Twitter](#twitter)
    - [Websites](#websites)
        - [Tutorials](#tutorials)

## Audio/Music

*Libraries for manipulating audio.*

* [flac](https://github.com/eaburns/flac) - A native Go FLAC decoder.
* [go-sox](https://github.com/krig/go-sox) - libsox bindings for go.
* [PortAudio](https://code.google.com/p/portaudio-go/) - Go bindings for the PortAudio audio I/O library.
* [portmidi](https://github.com/rakyll/portmidi) - Go bindings for PortMidi.
* [vorbis](https://github.com/mccoyst/vorbis) - A "native" Go Vorbis decoder (uses CGO, but has no dependencies).
* [waveform](https://github.com/mdlayher/waveform) - Go package capable of generating waveform images from audio streams.

## Authentication & OAuth

*Libraries for implementing authentications schemes.*

* [Go-AWS-Auth](https://github.com/smartystreets/go-aws-auth) - AWS (Amazon Web Services) request signing library.
* [go.auth](https://github.com/bradrydzewski/go.auth) - Authentication API for Go web applications.
* [gorbac](https://github.com/mikespook/gorbac) - provides a lightweight role-based access control (RBAC) implementation in Golang.
* [httpauth](https://github.com/goji/httpauth) - HTTP Authentication middleware.
* [jwt-go](https://github.com/dgrijalva/jwt-go) - Golang implementation of JSON Web Tokens (JWT).
* [oauth2](https://github.com/golang/oauth2) - Successor of goauth2. Generic OAuth 2.0 package that comes with JWT, Google APIs, Compute Engine and App Engine support.
* [osin](https://github.com/RangelReale/osin) - Golang OAuth2 server library.

## CSS Preprocessors

*Libraries for preprocessing CSS files*

* [gcss](https://github.com/yosssi/gcss) - Pure Go CSS Preprocessor.

## CUI

*Libraries for building CUI Applications*

* [chalk](https://github.com/ttacon/chalk) - Intuitive package for prettifying terminal/console output.
* [color](https://github.com/fatih/color) - Versatile package for colored terminal output.
* [go-colortext](https://github.com/daviddengcn/go-colortext) - Go library for color output in terminals.
* [termbox-go](https://github.com/nsf/termbox-go) - Termbox is a library for creating cross-platform text-based interfaces.

## Database

*Generic data structures and algorithms for databases in Go.*

* [bitset](https://github.com/willf/bitset) - Go package implementing bitsets.
* [bloom](https://github.com/dataence/bloom) - Bloom filters implemented in Go.
* [encoding](https://github.com/dataence/encoding) - Integer Compression Libraries for Go.
* [mafsa](https://github.com/smartystreets/mafsa) - MA-FSA implementation with Minimal Perfect Hashing
* [skiplist](https://github.com/gansidui/skiplist) - Skiplist implementation in Go
* [trie](https://github.com/derekparker/trie) - Trie implementation in Go

*Databases implemented in Go.*

* [bolt](https://github.com/boltdb/bolt) - A low-level key/value database for Go.
* [cache2go](https://github.com/muesli/cache2go) - An in-memory key:value cache which supports automatic invalidation based on timeouts.
* [diskv](https://github.com/peterbourgon/diskv) - A home-grown disk-backed key-value store.
* [forestdb](https://github.com/couchbaselabs/goforestdb) - Go bindings for ForestDB.
* [go-cache](https://github.com/pmylund/go-cache) - An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
* [goleveldb](https://github.com/syndtr/goleveldb) - An implementation of the [LevelDB](https://code.google.com/p/leveldb/) key/value database in the Go.
* [groupcache](https://github.com/golang/groupcache) - Groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases.
* [influxdb](https://github.com/influxdb/influxdb) - Scalable datastore for metrics, events, and real-time analytics
* [ledisdb](https://github.com/siddontang/ledisdb) - Ledisdb is a high performance NoSQL like Redis based on LevelDB.
* [tiedot](https://github.com/HouzuoGuo/tiedot) - Your NoSQL database powered by Golang.

*Database tools.*

* [go-mysql](https://github.com/siddontang/go-mysql) - A go toolset to handle MySQL protocol and replication.
* [pgweb](https://github.com/sosedoff/pgweb) - A web-based PostgreSQL database browser
* [vitess](https://github.com/youtube/vitess) - vitess provides servers and tools which facilitate scaling of MySQL databases for large scale web services.

## Database Drivers

*Libraries for connecting and operating databases. (see [Testing](#testing) for mock drivers)*

* Relational Databases
    * [go-adodb](https://github.com/mattn/go-adodb) - Microsoft ActiveX Object DataBase driver for go that using database/sql.
    * [go-mssqldb](https://github.com/denisenkom/go-mssqldb) - Microsoft MSSQL driver prototype in go language.
    * [go-oci8](https://github.com/mattn/go-oci8) - Oracle driver for go that using database/sql.
    * [go-pgsql](https://github.com/lxn/go-pgsql) - A PostgreSQL client package for the Go Programming Language.
    * [go-sql-driver/mysql](https://github.com/go-sql-driver/mysql) - MySQL driver for Go.
    * [go-sqlite3](https://github.com/mattn/go-sqlite3) - SQLite3 driver for go that using database/sql.
    * [pq](https://github.com/lib/pq) - Pure Go Postgres driver for database/sql.

* NoSQL Databases
    * [aerospike-client-go](https://github.com/aerospike/aerospike-client-go) - Aerospike client in Go language.
    * [cayley](https://github.com/google/cayley) - A graph database with support for multiple backends.
    * [go-couchbase](https://github.com/couchbaselabs/go-couchbase) - Couchbase client in Go
    * [gorethink](https://github.com/dancannon/gorethink) - Go language driver for RethinkDB
    * [gomemcache](https://github.com/bradfitz/gomemcache/) - memcache client library for the Go programming language.
    * [mgo](http://godoc.org/labix.org/v2/mgo) - MongoDB driver for the Go language that implements a rich and well tested selection of features under a very simple API following standard Go idioms.
    * [neo4j](https://github.com/cihangir/neo4j) - Neo4j Rest API Bindings for Golang
    * [Neo4j-GO](https://github.com/davemeehan/Neo4j-GO) - Neo4j REST Client in golang.
    * [redigo](https://github.com/garyburd/redigo) - Redigo is a Go client for the Redis database.
    * [redis](https://github.com/hoisie/redis) - A simple, powerful Redis client for Go.

* Search and Analytic Databases
    * [bleve](https://github.com/blevesearch/bleve) - A modern text indexing library for go.
    * [elastic](https://github.com/olivere/elastic) - Elasticsearch client for Google Go.
    * [elastigo](https://github.com/mattbaird/elastigo) - A Elasticsearch client library.
    * [goes](https://github.com/belogik/goes) - A library to interact with Elasticsearch.

## Date & Time

*Libraries for working with dates and times.*

* [now](https://github.com/jinzhu/now) - Now is a time toolkit for golang.

## Distributed Systems

*Packages that help with building Distributed Systems.*

* [goraft](https://github.com/goraft/raft) - A Go implementation of the Raft distributed consensus protocol.
* [raft](https://github.com/hashicorp/raft) - Golang implementation of the Raft consensus protocol, by HashiCorp.

## Email

*Libraries that implement email creation and sending*

* [email](https://github.com/jordan-wright/email) - A robust and flexible email library for Go.
* [Go-MailHog](https://github.com/ian-kent/Go-MailHog) - Catches mail and serves it through a dream. Inspired by MailCatcher, easier to install.
* [Gomail](https://github.com/go-gomail/gomail/) - Gomail is a very simple and powerful package to send emails.

## Embeddable Scripting Languages

*Embedding other languages inside your go code*

* [agora](https://github.com/PuerkitoBio/agora) - Dynamically typed, embeddable programming language in Go
* [anko](https://github.com/mattn/anko) - Scriptable interpreter written in Go
* [gisp](https://github.com/jcla1/gisp) - Simple LISP in Go
* [golua](https://github.com/aarzilli/golua) - Go bindings for Lua C API
* [go-python](https://github.com/sbinet/go-python) - naive go bindings to the CPython C-API
* [otto](https://github.com/robertkrimen/otto) - A JavaScript interpreter written in Go
* [v8-go](https://github.com/idada/v8.go/) - V8 JavaScript engine bindings for Go

## Forms

*Libraries for working with forms.*

* [bind](https://github.com/robfig/bind)  - Bind form data to any Go values
* [binding](https://github.com/mholt/binding) - Binds form and JSON data from net/http Request to struct.
* [formam](https://github.com/monoculum/formam) - decode form's values into a struct.
* [nosurf](https://github.com/justinas/nosurf) - A CSRF protection middleware for Go.

## Game Development

*Awesome game development libraries.*

* [GarageEngine](https://github.com/vova616/GarageEngine) - 2d game engine written in Go working on OpenGL.
* [glop](https://github.com/runningwild/glop) - Glop (Game Library Of Power) is a fairly simple cross-platform game library.
* [go3d](https://github.com/ungerik/go3d) - A performance oriented 2D/3D math package for Go
* [go-astar](https://github.com/beefsack/go-astar) - Go implementation of the A* path finding algorithm

## Generation & Generics

*Tools to enhance the language with features like generics via code generation*

* [gen](https://github.com/clipperhouse/gen) - Code generation tool for 'generics'-like functionality.
* [go-linq](https://github.com/ahmetalpbalkan/go-linq) - .NET LINQ-like query methods for Go.
* [pkgreflect](https://github.com/ungerik/pkgreflect) - A Go preprocessor for package scoped reflection.

## GUI

*Libraries for building GUI Applications*

* [go-gtk](http://mattn.github.io/go-gtk/) - Go bindings for GTK
* [gotk3](https://github.com/conformal/gotk3) - Go bindings for GTK3.
* [go-qml](https://github.com/go-qml/qml) - QML support for the Go language
* [ui](https://github.com/andlabs/ui) - Platform-native GUI library for Go.
* [walk](https://github.com/lxn/walk) - Windows application library kit for Go.

## Images

*Libraries for manipulating images.*

* [geo_pattern](https://github.com/pravj/geo_pattern) - Create beautiful generative image patterns from a string.
* [gift](https://github.com/disintegration/gift) - Package of image processing filters.
* [go-cairo](https://github.com/ungerik/go-cairo) - Go binding for the cairo graphics library.
* [go-gd](https://github.com/bolknote/go-gd) - Go binding for GD library
* [go-nude](https://github.com/koyachi/go-nude) - Nudity detection with Go.
* [go-opencv](https://github.com/lazywei/go-opencv) - Go bindings for OpenCV.
* [go-webcolors](https://github.com/jyotiska/go-webcolors) - Port of webcolors library from Python to Go.
* [img](https://github.com/hawx/img) - A selection of image manipulation tools.
* [imagick](https://github.com/gographics/imagick) - Go binding to ImageMagick's MagickWand C API.
* [imaging](https://github.com/disintegration/imaging) - Simple Go image processing package.
* [resize](https://github.com/nfnt/resize) - Image resizing for the Go with common interpolation methods.
* [rez](https://github.com/bamiaux/rez) - Image resizing in pure Go and SIMD.
* [smartcrop](https://github.com/muesli/smartcrop) - Finds good crops for arbitrary images and crop sizes
* [svgo](https://github.com/ajstarks/svgo) - Go Language Library for SVG generation.

## Logging

*Libraries for generating and working with log files.*

* [glog](https://github.com/golang/glog) - Leveled execution logs for Go.
* [gologex](https://github.com/chzyer/gologex) - An golang log lib, supports tracking and level, wrap by standard log lib
* [go-log](https://github.com/siddontang/go-log) - Log lib supports level and multi handlers.
* [go-logger](https://github.com/apsdehal/go-logger) - Simple logger of Go Programs, with level handlers.
* [logrus](https://github.com/sirupsen/logrus) - Structured, pluggable logging for Go.
* [lumberjack](https://github.com/natefinch/lumberjack) - Simple rolling logger, implements io.WriteCloser.
* [seelog](https://github.com/cihub/seelog) -   logging functionality with flexible dispatching, filtering, and formatting.
* [stdlog](https://github.com/alexcesaro/log) - Stdlog is an object-oriented library providing leveled logging. It is very useful for cron jobs.

## Machine Learning

*Libraries for Machine Learning.*

* [bayesian](https://github.com/jbrukh/bayesian) - Naive Bayesian Classification for Golang.
* [CloudForest](https://github.com/ryanbressler/CloudForest) - Fast, flexible, multi-threaded ensembles of decision trees for machine learning in pure Go.
* [gobrain](https://github.com/goml/gobrain) - Neural Networks written in go
* [go-fann](https://github.com/white-pony/go-fann) - Go bindings for Fast Artificial Neural Networks(FANN) library.
* [go-galib](https://github.com/thoj/go-galib) - Genetic Algorithms library written in Go / golang
* [golinear](https://github.com/danieldk/golinear) - liblinear bindings for Go
* [GoLearn](https://github.com/sjwhitworth/golearn) - General Machine Learning library for Go.
* [go-pr](https://github.com/daviddengcn/go-pr) - Pattern recognition package in Go lang.
* [goRecommend](https://github.com/timkaye11/goRecommend) - Recommendation Algorithms library written in Go.
* [libsvm](https://github.com/datastream/libsvm) - libsvm golang version derived work based on LIBSVM 3.14.
* [mlgo](https://code.google.com/p/mlgo/) - This project aims to provide minimalistic machine learning algorithms in Go.
* [neural-go](https://github.com/schuyler/neural-go) - A multilayer perceptron network implemented in Go, with training via backpropagation.
* [probab](https://code.google.com/p/probab/) - Probability distribution functions. Bayesian inference. Written in pure Go.
* [regommend](https://github.com/muesli/regommend) - Recommendation & collaborative filtering engine
* [shield](https://github.com/eaigner/shield) - Bayesian text classifier with flexible tokenizers and storage backends for Go

## Messaging

*Libraries that implement messaging systems*

* [dbus](https://github.com/godbus/dbus) - Native Go bindings for D-Bus.
* [EventBus](https://github.com/asaskevich/EventBus) - The lightweight event bus with async compatibility.
* [go-nsq](https://github.com/bitly/go-nsq) - the official Go package for NSQ
* [gopush-cluster](https://github.com/Terry-Mao/gopush-cluster) - gopush-cluster is a go push server cluster.
* [NATS](https://github.com/apcera/nats) - A lightweight and highly performant publish-subscribe and distributed queueing messaging system.
* [sarama](https://github.com/Shopify/sarama) - A Go library for Apache Kafka.
* [Uniqush-Push](https://github.com/uniqush/uniqush-push) - A redis backed unified push service for server-side notifications to mobile devices.
* [zmq4](https://github.com/pebbe/zmq4) - A Go interface to ZeroMQ version 4. Also available for [version 3](https://github.com/pebbe/zmq3) and [version 2](https://github.com/pebbe/zmq2).

## Miscellaneous

*These libraries were placed here because none of the other categories seemed to fit*

* [browscap_go](https://github.com/fromYukki/browscap_go) - GoLang Library for [Browser Capabilities Project](http://browscap.org/).

## Natural Language Processing

*Libraries for working with human languages.*

* [go-eco](https://code.google.com/p/go-eco/) - Similarity, dissimilarity and distance matrices; diversity, equitability and inequality measures; species richness estimators; coenocline models.
* [golibstemmer](https://github.com/rjohnsondev/golibstemmer) - Go bindings for the snowball libstemmer library including porter 2
* [go-nlp](https://github.com/nuance/go-nlp) - Utilities for working with discrete probability distributions and other tools useful for doing NLP work.
* [go-porterstemmer](https://github.com/reiver/go-porterstemmer) - A native Go clean room implementation of the Porter Stemming algorithm.
* [go-stem](https://github.com/agonopol/go-stem) - Implementation of the porter stemming algorithm.
* [gounidecode](https://github.com/fiam/gounidecode) - Unicode transliterator (also known as unidecode) for Go
* [icu](https://github.com/goodsign/icu) - Cgo binding for icu4c C library detection and conversion functions. Guaranteed compatibility with version 50.1.
* [libtextcat](https://github.com/goodsign/libtextcat) - Cgo binding for libtextcat C library. Guaranteed compatibility with version 2.2.
* [MMSEGO](https://github.com/awsong/MMSEGO) - This is a GO implementation of [MMSEG](http://technology.chtsai.org/mmseg/) which a Chinese word splitting algorithm.
* [paicehusk](https://github.com/Rookii/paicehusk) - Golang implementation of the Paice/Husk Stemming Algorithm
* [porter](https://github.com/a2800276/porter) - This is a fairly straighforward port of Martin Porter's C implementation of the Porter stemming algorithm.
* [snowball](https://github.com/goodsign/snowball) - Snowball stemmer port (cgo wrapper) for Go. Provides word stem extraction functionality [Snowball native](http://snowball.tartarus.org/).
* [stemmer](https://github.com/dchest/stemmer) - Stemmer packages for Go programming language. Includes English and German stemmers.
* [textcat](https://github.com/pebbe/textcat) - A Go package for n-gram based text categorization, with support for utf-8 and raw text

## Networking

*Libraries for working with various layers of the network*

* [dns](https://github.com/miekg/dns) - Go library for working with DNS
* [gopacket](https://code.google.com/p/gopacket) - A Go library for packet processing with libpacp bindings
* [gopcap](https://github.com/akrennmair/gopcap) - A Go wrapper for libpcap
* [gosnmp](https://github.com/soniah/gosnmp) - Native Go library for performing SNMP actions
* [gotcp](https://github.com/gansidui/gotcp) - A Go package for quickly writing tcp applications
* [portproxy](https://github.com/aybabtme/portproxy) - Simple TCP proxy which adds CORS support to API's which don't support it.
* [tcp_server](https://github.com/firstrow/tcp_server) - A Go library for building tcp servers faster

## OpenGL

*Libraries for using OpenGL in Go.*

* [gl](https://github.com/go-gl/gl) - Go bindings for OpenGL. Requires an external dependency GLEW.
* [glfw3](https://github.com/go-gl/glfw3) - Go bindings for GLFW 3.
* [glow](https://github.com/go-gl/glow) - Go binding generator and bindings for OpenGL.
* [mathgl](https://github.com/go-gl/mathgl) - Pure Go math package specialized for 3D math, with inspiration from GLM.

## ORM

*Libraries that implement Object-Relational Mapping or datamapping techniques.*

* [BeeDB](https://github.com/astaxie/beedb) - go ORM,support database/sql interface,pq/mysql/sqlite.
* [GORM](https://github.com/jinzhu/gorm) - The fantastic ORM library for Golang, aims to be developer friendly.
* [gorp](https://github.com/coopernurse/gorp) - Go Relational Persistence, ORM-ish library for Go.
* [hood](https://github.com/eaigner/hood) - Database agnostic ORM for Go.
* [QBS](https://github.com/coocood/qbs) - Stands for Query By Struct. A Go ORM.
* [upper.io/db](https://github.com/upper/db) - Single interface for interacting with different data sources through the use of adapters that wrap mature database drivers.
* [Xorm](https://github.com/go-xorm/xorm) - Simple and powerful ORM for Go.

## Package Management

*Libraries for package and dependency management.*

* [godep](https://github.com/tools/godep) - dependency tool for go, godep helps build packages reproducibly by fixing their dependencies.
* [gom](https://github.com/mattn/gom) - Go Manager - bundle for go.
* [goop](https://github.com/nitrous-io/goop) - A simple dependency manager for Go (golang), inspired by Bundler.
* [gopm](https://github.com/gpmgo/gopm) - Go Package Manager
* [gpm](https://github.com/pote/gpm) - Barebones dependency manager for Go.
* [VenGO](https://github.com/DamnWidget/VenGO) - create and manage exportable isolated go virtual environments

## Science and Data Analysis

*Libraries for scientific computing and data analyzing.*

* [blas](https://github.com/ziutek/blas) - Implementation of BLAS (Basic Linear Algebra Subprograms)
* [geom](https://github.com/skelterjohn/geom) - 2D geometry for golang
* [gocomplex](https://code.google.com/p/gocomplex/) - A complex number library for the Go programming language.
* [go-fn](https://code.google.com/p/go-fn/) - Mathematical functions written in Go language, that are not covered by math pkg
* [gofrac](https://github.com/anschelsc/gofrac) - A (goinstallable) fractions library for go with support for basic arithmetic.
* [go-gt](https://code.google.com/p/go-gt/) - Graph theory algorithms written in "Go" language
* [go.matrix](https://github.com/skelterjohn/go.matrix) - linear algebra for go
* [gostat](https://code.google.com/p/gostat/) - A statistics library for the go language
* [goraph](https://github.com/gyuho/goraph) - A pure Go graph theory library(data structure, algorith visualization)
* [mudlark-go](https://code.google.com/p/mudlark-go-pkgs/) - A collection of packages providing (hopefully) useful code for use in software using Google's Go programming language.
* [plotinum](https://code.google.com/p/plotinum/) - Plotinum provides an API for building and drawing plots in Go.
* [streamtools](https://github.com/nytlabs/streamtools) - general purpose, graphical tool for dealing with streams of data.
* [vectormath](https://github.com/spate/vectormath) - Vectormath for Go, an adaptation of the scalar C functions from Sony's Vector Math library, as found in the Bullet-2.79 source code.

## Serialization

*Libraries and tools for binary serialization*

* [cbor](https://github.com/2tvenom/cbor) - Golang library for working with cbor binary format
* [gogoprotobuf](https://code.google.com/p/gogoprotobuf) - Protocol Buffers for Go with Gadgets
* [goprotobuf](https://code.google.com/p/goprotobuf) - Go support, in the form of a library and protocol compiler plugin, for Google's protocol buffers.
* [php_session_decoder](https://github.com/yvasiyarov/php_session_decoder) - GoLang library for working with PHP session format and PHP Serialize/Unserialize functions

## Template Engines

*Libraries and tools for templating and lexing.*

* [ace](https://github.com/yosssi/ace) - Ace is an HTML template engine for Go, inspired by Slim and Jade. Ace is a refinement of Gold.
* [amber](https://github.com/eknkc/amber) - Amber is an elegant templating engine for Go Programming Language It is inspired from HAML and Jade.
* [kasia.go](https://github.com/ziutek/kasia.go) - Templating system for HTML and other text documents - go implementation.
* [mustache](https://github.com/hoisie/mustache) - A Go implementation of the Mustache template language.
* [pongo2](https://github.com/flosch/pongo2) - A Django-like template-engine for Go.
* [Razor](https://github.com/sipin/gorazor) - Razor view engine for Golang.
* [Soy](https://github.com/robfig/soy) - Closure templates (aka Soy templates) for Go, following the [official spec](https://developers.google.com/closure/templates/)

## Testing

*Libraries for testing codebases and generating test data.*

* Testing Frameworks
    * [assert](https://github.com/bmizerany/assert) - Asserts to Go testing
    * [ginkgo](http://onsi.github.io/ginkgo/) - BDD Testing Framework for Go
    * [goblin](https://github.com/franela/goblin) - Mocha like testing framework fo Go
    * [gocheck](http://labix.org/gocheck) - A more advanced testing framework alternative to gotest.
    * [GoConvey](https://github.com/smartystreets/goconvey/) - BDD-style framework with web UI and live reload
    * [GoSpec](https://github.com/orfjackal/gospec) - BDD-style testing framework for the Go programming language.
    * [gospecify](https://github.com/stesla/gospecify) - This provides a BDD syntax for testing your Go code. It should be familiar to anybody who has used libraries such as rspec.
    * [Hamcrest](https://github.com/rdrdr/hamcrest) - fluent framework for declarative Matcher objects that, when applied to input values, produce self-describing results.
    * [restit](https://github.com/yookoala/restit) - A Go micro framework to help writing RESTful API integration test.
    * [Testify](https://github.com/stretchr/testify) - A sacred extension to the standard go testing package.

* Mock
    * [counterfeiter](https://github.com/maxbrunsfeld/counterfeiter) - Tool for generating self-contained mock objects
    * [gomock](https://code.google.com/p/gomock/) - Mocking framework for the Go programming language.
    * [mockhttp.go](https://github.com/tv42/mockhttp.go) - Mock object for Go http.ResponseWriter
    * [go-sqlmock](https://github.com/DATA-DOG/go-sqlmock) - Mock SQL driver for testing database interactions

## Text Processing

*Libraries for parsing and manipulating texts.*

* Specific Formats
    * [blackfriday](https://github.com/russross/blackfriday) - Markdown processor in Go
        * [github_flavored_markdown](http://godoc.org/github.com/shurcooL/go/github_flavored_markdown) - GitHub Flavored Markdown renderer in Go.
    * [bluemonday](https://github.com/microcosm-cc/bluemonday) - HTML Sanitizer
    * [enca](https://github.com/endeveit/enca) - Minimal cgo bindings for [libenca](http://cihar.com/software/enca/).
    * [gographviz](https://code.google.com/p/gographviz) - Parses the Graphviz DOT language.
    * [go-humanize](https://github.com/dustin/go-humanize) - Formatters for time, numbers, and memory size to human readable format.
    * [go-pkg-rss](https://github.com/jteeuwen/go-pkg-rss) - This package reads RSS and Atom feeds and provides a caching mechanism that adheres to the feed specs.
    * [go-pkg-xmlx](https://github.com/jteeuwen/go-pkg-xmlx) - Extension to the standard Go XML package. Maintains a node tree that allows forward/backwards browsing and exposes some simple single/multi-node search functions.
    * [GoQuery](https://github.com/PuerkitoBio/goquery) - GoQuery brings a syntax and a set of features similar to jQuery to the Go language.
    * [go-runewidth](https://github.com/mattn/go-runewidth) - Functions to get fixed width of the character or string.
    * [guesslanguage](https://github.com/endeveit/guesslanguage) - Functions to determine the natural language of a unicode text.
    * [slug](https://github.com/gosimple/slug) - URL-friendly slugify with multiple languages support.
    * [toml](https://github.com/BurntSushi/toml) - TOML configuration format (encoder/decoder with reflection).
* Utility
    * [gotabulate](https://github.com/bndr/gotabulate) - Easily pretty-print your tabular data with Go.
    * [govalidator](https://github.com/asaskevich/govalidator) - package of string validators and sanitizers for Go lang.

## Third-party APIs

*Libraries for accessing third party APIs.*

* [facebook](https://github.com/huandu/facebook) - Go Library that supports the Facebook Graph API
* [github](https://github.com/google/go-github) - Go library for accessing the GitHub API.
* [GoMusicBrainz](https://github.com/michiwend/gomusicbrainz) - a Go MusicBrainz WS2 client library
* [gostorm](https://github.com/jsgilmore/gostorm) - GoStorm is a Go library that implements the communications protocol required to write Storm spouts and Bolts in Go that communicate with the Storm shells.
* [hipchat](https://github.com/andybons/hipchat) - This project implements a golang client library for the Hipchat API.
* [hipchat (xmpp)](https://github.com/daneharrigan/hipchat) - A golang package to communicate with HipChat over XMPP.
* [mixpanel](https://github.com/dukex/mixpanel) - Mixpanel is a library for tracking events and sending Mixpanel profile updates to Mixpanel from your go applications.
* [rrdaclient](https://github.com/Omie/rrdaclient) - Go Library to access statdns.com API, which is in turn RRDA API. DNS Queries over HTTP.
* [shopify](https://github.com/rapito/go-shopify) - Go Library to make CRUD request to the Shopify API.
* [smite](https://github.com/sergiotapia/smitego) - Go package to wraps access to the Smite game API.
* [snapchat](https://github.com/jamieomatthews/gosnap) - Go wrapper for the snapchat API
* [spotify](https://github.com/rapito/go-spotify) - Go Library to access Spotify WEB API.

## Utilities

*General utilities and tools to make your life easier.*

* [cli](https://github.com/codegangsta/cli) - A small package for building command line apps in Go.
* [cli-init](https://github.com/tcnksm/cli-init) - The easy way to start building Golang command-line application.
* [coop](https://github.com/rakyll/coop) - Cheat sheet for some of the common concurrent flows in Go.
* [delve](https://github.com/derekparker/delve) - Go debugger.
* [godropbox](https://github.com/dropbox/godropbox) - Common libraries for writing Go services/applications from Dropbox.
* [gopencils](https://github.com/bndr/gopencils) - Small and simple package to easily consume REST APIs.
* [goplaceholder](https://github.com/michiwend/goplaceholder) - a small golang lib to generate placeholder images
* [goreq](https://github.com/franela/goreq) - Minimal and simple request library for Go language.
* [gorequest](https://github.com/parnurzeal/gorequest) - Simplified HTTP client with rich features for Go.
* [gotenv](https://github.com/subosito/gotenv) - Load environment variables from `.env` or any `io.Reader` in Go
* [go-debug](https://github.com/visionmedia/go-debug) - Conditional debug logging for Golang libraries & applications
* [go-dry](https://github.com/ungerik/go-dry) - DRY (don't repeat yourself) package for Go.
* [go-underscore](https://github.com/tobyhede/go-underscore) - A useful collection of helpfully functional Go collection utilities.
* [lrserver](https://github.com/jaschaephraim/lrserver) - LiveReload server for Go
* [mp](https://github.com/sanbornm/mp) - A simple cli email parser. It currently takes stdin and outputs JSON.
* [ngrok](https://github.com/inconshreveable/ngrok) - Introspected tunnels to localhost.
* [okrun](https://github.com/xta/okrun) - go run error steamroller
* [peco](https://github.com/peco/peco) - Simplistic interactive filtering tool
* [profile](https://github.com/davecheney/profile) - Simple profiling support package for Go
* [spinner](https://github.com/briandowns/spinner) - Go package to easily provide a terminal spinner with options.
* [sqlx](https://github.com/jmoiron/sqlx) - provides a set of extensions on top of the excellent built-in database/sql package
* [xlsx](https://github.com/tealeg/xlsx) - Library to simplify reading the XML format used by recent version of Microsoft Excel in Go programs.

## Video

*Libraries for manipulating video.*

* [aac/h264](https://github.com/go-av/codec) - Golang aac/h264 encoder and decoder.
* [gmf](https://github.com/3d0c/gmf) - Go bindings for FFmpeg av\* libraries.
* [gst](https://github.com/ziutek/gst) - Go bindings for GStreamer.

## Web Frameworks

*Full stack web frameworks.*

* [Beego](https://github.com/astaxie/beego) - beego is an open-source, high-performance web framework for the Go programming language.
* [Gin](https://github.com/gin-gonic/gin) - Gin is a web framework written in Go! It features a martini-like API with much better performance, up to 40 times faster. If you need performance and good productivity.
* [Goat](https://github.com/bahlo/goat) - A minimalistic REST API server in Go
* [gocraft/web](https://github.com/gocraft/web) - A mux and middleware package in Go.
* [Goji](https://github.com/zenazn/goji) - Goji is a minimalistic web framework for Golang that's high in antioxidants.
* [Gondola](https://github.com/rainycape/gondola) - The web framework for writing faster sites, faster
* [Gorilla](https://github.com/gorilla/) - Gorilla is a web toolkit for the Go programming language.
* [go-relax](https://github.com/codehack/go-relax) - A framework of pluggable components to build RESTful API's
* [go-rest](https://github.com/ungerik/go-rest) - A small and evil REST framework for Go
* [httprouter](https://github.com/julienschmidt/httprouter) - A high performance router. Use this and the standard http handlers to form a very high performance web framework.
* [Macaron](https://github.com/Unknwon/macaron) - Macaron is a high productive and modular design web framework in Go.
* [mango](https://github.com/paulbellamy/mango) - Mango is a modular web-application framework for Go, inspired by Rack, and PEP333.
* [Martini](https://github.com/go-martini/martini) - Martini is a powerful package for quickly writing modular web applications/services in Golang.
* [pat](https://github.com/bmizerany/pat) - Sinatra style pattern muxer for Go's net/http library, by the author of Sinatra.
* [Revel](https://github.com/revel/revel) - A high-productivity web framework for the Go language.
* [sawsij](http://sawsij.com/) - lightweight, open-source web framework for building high-performance, data-driven web applications.
* [tigertonic](https://github.com/rcrowley/go-tigertonic) - A Go framework for building JSON web services inspired by Dropwizard
* [traffic](https://github.com/pilu/traffic) - Sinatra inspired regexp/pattern mux and web framework for Go.
* [web.go](https://github.com/hoisie/web) - A simple framework to write webapps in Go.
* [zeus](https://github.com/daryl/zeus) - A very simple and fast HTTP router for Go.

### Middlewares

*Libraries for creating HTTP middlewares.*

* [alice](https://github.com/justinas/alice) - Painless middleware chaining for Go.
* [go-wrap](https://github.com/go-on/wrap) - Small middlewares package for net/http.
* [interpose](https://github.com/carbocation/interpose) - Minimalist net/http middleware for golang
* [muxchain](https://github.com/stephens2424/muxchain) - Lightweight middleware for net/http.
* [negroni](https://github.com/codegangsta/negroni) - Idiomatic HTTP middleware for Golang.
* [render](https://github.com/unrolled/render) - Go package for easily rendering JSON, XML, and HTML template responses.

# Tools

Go software and plugins.

## Code Analysis

* [doc](http://godoc.org/code.google.com/p/rspace.cmd/doc) - Go documentation tool that produces an alternative doc format.
* [errcheck](https://github.com/kisielk/errcheck) - Errcheck is a program for checking for unchecked errors in Go programs.
* [gcvis](https://github.com/davecheney/gcvis) - Visualise Go program GC trace data in real time.
* [goast-viewer](https://github.com/yuroyoro/goast-viewer) - Web based Golang AST visualizer.
* [GoCover.io](http://gocover.io/) - GoCover.io offers the code coverage of any golang package as a service.
* [goimports](http://godoc.org/code.google.com/p/go.tools/cmd/goimports) - Tool to fix (add, remove) your Go imports automatically.
* [GoLint](https://github.com/golang/lint) - Golint is a linter for Go source code.
* [Golint online](http://go-lint.appspot.com/) - Lints online Go source files on GitHub, Bitbucket and Google Project Hosting using the golint package.
* [validate](https://github.com/mccoyst/validate) - Automatically validates struct fields with tags.

## Editor Plugins

* [go-lang-idea-plugin](https://github.com/go-lang-plugin-org/go-lang-idea-plugin) Go plugin for IntelliJ IDEA.
* [gocode](https://github.com/nsf/gocode) - An autocompletion daemon for the Go programming language
* [GoSublime](https://github.com/DisposaBoy/GoSublime) - A Golang plugin collection for the text editor SublimeText 2 providing code completion and other IDE-like features.
* [velour](https://github.com/velour/velour) - An IRC client for the acme editor.
* [vim-compiler-go](https://github.com/rjohnsondev/vim-compiler-go) - A Vim plugin to highlight syntax errors on save.
* [vim-go](https://github.com/fatih/vim-go) - Go development plugin for Vim.
* [Watch](https://github.com/eaburns/Watch) - Runs a command in an acme win on file changes.

## Software Packages

Software written in Go.

### DevOps Tools

* [aptly](https://github.com/smira/aptly) - aptly is a Debian repository management tool
* [Boom](https://github.com/rakyll/boom) - Boom is a tiny program that sends some load to a web application.
* [dogo](https://github.com/liudng/dogo) - Monitoring changes in the source file and automatically compile and run (restart).
* [gaudi](http://gaudi.io/) - Gaudi automates the setup of isolated and decoupled dev environments.
* [gobrew](https://github.com/cryptojuice/gobrew) - gobrew lets you easily switch between multiple versions of go.
* [GoBuild](http://gobuild.io/) - Online compile Go projects to Windows, Linux and MacOSX.
* [godbg](https://github.com/sirnewton01/godbg) - Web-based gdb front-end application.
* [Gogs](http://gogs.io/) - A Self Hosted Git Service in the Go Programming Language.
* [gonative](https://github.com/inconshreveable/gonative) - Tool which creates a build of Go that can cross compile to all platforms while still using the Cgo-enabled versions of the stdlib packages.
* [go-selfupdate](https://github.com/sanbornm/go-selfupdate) - Enable your Go applications to self update.
* [gox](https://github.com/mitchellh/gox) - A dead simple, no frills Go cross compile tool.
* [goxc](https://github.com/laher/goxc) - build tool for Go, with a focus on cross-compiling and packaging.
* [GVM](https://github.com/moovweb/gvm) - GVM provides an interface to manage Go versions.
* [hk](https://github.com/heroku/hk) - Heroku command-line interface in Go.
* [Mora](https://github.com/emicklei/mora) - REST server for accessing MongoDB documents and meta data.
* [ostent](https://github.com/ostrost/ostent) - collects and displays system metrics and optionally relays to Graphite and/or InfluxDB
* [Packer](https://github.com/mitchellh/packer) - Packer is a tool for creating identical machine images for multiple platforms from a single source configuration.
* [Rodent](https://github.com/alouche/rodent) - Rodent helps you manage Go versions, projects and track dependencies.

### Other Software

* [Circuit](https://github.com/gocircuit/circuit) - Circuit is a programmable platform-as-a-service (PaaS) and/or Infrastructure-as-a-Service (IaaS), for management, discovery, synchronization and orchestration of services and hosts comprising cloud applications.
* [confd](https://github.com/kelseyhightower/confd) - Manage local application configuration files using templates and data from etcd or consul.
* [Docker](http://www.docker.com/) - An open platform for distributed applications for developers and sysadmins.
* [etcd](https://github.com/coreos/etcd) - A highly-available key value store for shared configuration and service discovery.
* [fleet](https://github.com/coreos/fleet) - A Distributed init System.
* [gocc](https://code.google.com/p/gocc) - Gocc is a compiler kit for Go written in Go.
* [Gor] (https://github.com/buger/gor) - Http traffic replication tool, for replaying traffic from production to stage/dev environments in real-time.
* [heka] (https://github.com/mozilla-services/heka) - universal tool for data processing from Mozilla. Large collection of built-in plugins. Extendable via Go and Lua plugin API.
* [hugo](http://gohugo.io/) - A Fast and Modern Static Website Engine
* [Juju](https://juju.ubuntu.com/) - Cloud-agnostic service deployment and orchestration - supports EC2, Azure, Openstack, MAAS and more.
* [nsq](http://nsq.io/) - A realtime distributed messaging platform
* [orange-cat](https://github.com/noraesae/orange-cat) - A Markdown previewer written in Go.
* [peg](https://github.com/pointlander/peg) - Peg, Parsing Expression Grammar, is an implementation of a Packrat parser generator.
* [Postman](https://github.com/zachlatta/postman) - Command-line utility for batch-sending email.
* [syncthing](http://www.syncthing.net/) - An open, decentralized file synchronization tool and protocol.
* [Tenyks](https://github.com/kyleterry/tenyks) - Service oriented IRC bot using Redis and JSON for messaging.
* [tsuru](http://www.tsuru.io/) - An extensible and open source Platform as a Service software.

# Resources

Where to discover new Go libraries.

## Benchmarks

* [autobench](https://github.com/davecheney/autobench) - Framework to compare the performance between different Go versions.
* [gocostmodel](https://github.com/PuerkitoBio/gocostmodel) - Benchmarks of common basic operations for the Go language.
* [go-http-routing-benchmark](https://github.com/julienschmidt/go-http-routing-benchmark) - Go HTTP request router benchmark and comparison.
* [go_serialization_benchmarks](https://github.com/alecthomas/go_serialization_benchmarks) - Benchmarks of Go serialization methods.
* [go-type-assertion-benchmark](https://github.com/hgfischer/go-type-assertion-benchmark) - Naive performance test of two ways to do type assertion in Go.
* [kvbench](https://github.com/jimrobinson/kvbench) - Key/Value database benchmark.
* [speedtest-resize](https://github.com/fawick/speedtest-resize) - Compare various Image resize algorithms for the Go language.

## Conferences

* [dotGo](http://www.dotgo.io)
* [GopherCon](http://www.gophercon.com/)
* [GopherCon India](http://www.gophercon.in/)

## E-Books

* [A Go Developer's Notebook](https://leanpub.com/GoNotebook/read)
* [An Introduction to Programming in Go](http://www.golang-book.com/)
* [Build Web Application with Golang](https://docs.google.com/file/d/0B2GBHFyTK2N8TzM4dEtIWjBJdEk/edit?pli=1)
* [Building Web Apps With Go](http://codegangsta.gitbooks.io/building-web-apps-with-go/)
* [Go Bootcamp](http://golangbootcamp.com)
* [Learning Go](http://www.miek.nl/downloads/Go/Learning-Go-latest.pdf)
* [Network Programming With Go](http://jan.newmarch.name/go/)

## Twitter

* [@golang](https://twitter.com/golang)
* [@golang_news](https://twitter.com/golang_news)
* [@golangweekly](https://twitter.com/golangweekly)

## Websites

* [awesome-awesomeness](https://github.com/bayandin/awesome-awesomeness) - List of other amazingly awesome lists.
* [Flipboard - Go Magazine](https://flipboard.com/section/the-golang-magazine-bVP7nS) - A collection of Go articles and tutorials.
* [godoc.org](http://godoc.org/) - Documentation for open source Go packages.
* [golang-nuts](https://groups.google.com/forum/#!forum/golang-nuts) - Go mailing list
* [gowalker.org](https://gowalker.org) - Go Project API documentation.
* [Go Projects](https://code.google.com/p/go-wiki/wiki/Projects) - List of projects on the Go community wiki
* [r/Golang](http://www.reddit.com/r/golang) - News about Go.
* [Trending Go repositories on GitHub today](https://github.com/trending?l=go) - Good place to find new Go libraries.
* [go generate](https://docs.google.com/document/d/1V03LUfjSADDooDMhe-_K59EgpTEm3V8uvQRuNMAEnjg/edit) - A proposed code generation syntax from Rob Pike.

## Windows

* [go-ole](https://github.com/mattn/go-ole) - Win32 OLE implementation for golang

### Tutorials

* [A Tour of Go](http://tour.golang.org/) - Interactive tour of Go
* [Go By Example](https://gobyexample.com/) - A hands-on introduction to Go using annotated example programs
* [Working with Go](https://github.com/mkaz/working-with-go) - An intro to go for experienced programmers


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*****************************************************************************\
*                                                                             *
* FixupPointer.h -  Fixup pointer holder types                                *
*                                                                             *
\*****************************************************************************/

#ifndef _FIXUPPOINTER_H
#define _FIXUPPOINTER_H

#include "daccess.h"

#ifdef FEATURE_PREJIT

//----------------------------------------------------------------------------
// RelativePointer is pointer encoded as relative offset. It is used to reduce size of
// relocation section in NGen images. Conversion from/to RelativePointer needs
// address of the pointer ("this") converted to TADDR passed in from outside.
// Converting "this" to TADDR is not possible in the DAC transparently because
// DAC is based on exact pointers, not ranges.
// There are several flavors of conversions from/to RelativePointer:
//  - GetValue/SetValue: The most common version. Assumes that the pointer is not NULL.
//  - GetValueMaybeNull/SetValueMaybeNull: Pointer can be NULL.
//  - GetValueAtPtr: Static version of GetValue. It is
//    meant to simplify access to arrays of RelativePointers.
//  - GetValueMaybeNullAtPtr
template<typename PTR_TYPE>
class RelativePointer
{
public:

    static constexpr bool isRelative = true;
    typedef PTR_TYPE type;

#ifndef DACCESS_COMPILE
    RelativePointer()
    {
        m_delta = (TADDR)NULL;

        _ASSERTE (IsNull());
    }
#else // DACCESS_COMPILE
    RelativePointer() =delete;
#endif // DACCESS_COMPILE

    // Implicit copy/move is not allowed
    // Bitwise copy is implemented by BitwiseCopyTo method
    RelativePointer<PTR_TYPE>(const RelativePointer<PTR_TYPE> &) =delete;
    RelativePointer<PTR_TYPE>(RelativePointer<PTR_TYPE> &&) =delete;
    RelativePointer<PTR_TYPE>& operator = (const RelativePointer<PTR_TYPE> &) =delete;
    RelativePointer<PTR_TYPE>& operator = (RelativePointer<PTR_TYPE> &&) =delete;

    // Returns whether the encoded pointer is NULL.
    BOOL IsNull() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        // Pointer pointing to itself is treated as NULL
        return m_delta == (TADDR)NULL;
    }

    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    PTR_TYPE GetValue(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        PRECONDITION(!IsNull());
        return dac_cast<PTR_TYPE>(base + m_delta);
    }

#ifndef DACCESS_COMPILE
    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    // Does not need explicit base and thus can be used in non-DAC builds only.
    FORCEINLINE PTR_TYPE GetValue() const
    {
        LIMITED_METHOD_CONTRACT;
        return GetValue((TADDR)this);
    }
#endif

    // Static version of GetValue. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(RelativePointer<PTR_TYPE>)>(base)->GetValue(base);
    }

    // Returns value of the encoded pointer. The pointer can be NULL.
    PTR_TYPE GetValueMaybeNull(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;

        // Cache local copy of delta to avoid races when the value is changing under us.
        TADDR delta = m_delta;

        if (delta == 0)
            return NULL;

        return dac_cast<PTR_TYPE>(base + delta);
    }

#ifndef DACCESS_COMPILE
    // Returns value of the encoded pointer. The pointer can be NULL.
    // Does not need explicit base and thus can be used in non-DAC builds only.
    FORCEINLINE PTR_TYPE GetValueMaybeNull() const
    {
        LIMITED_METHOD_CONTRACT;
        return GetValueMaybeNull((TADDR)this);
    }
#endif

    // Static version of GetValueMaybeNull. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueMaybeNullAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(RelativePointer<PTR_TYPE>)>(base)->GetValueMaybeNull(base);
    }

#ifndef DACCESS_COMPILE
    // Set encoded value of the pointer. Assumes that the value is not NULL.
    FORCEINLINE void SetValue(PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        PRECONDITION(addr != NULL);
        m_delta = (TADDR)addr - (TADDR)this;
    }

    // Set encoded value of the pointer. The value can be NULL.
    void SetValueMaybeNull(TADDR base, PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        if (addr == NULL)
            m_delta = NULL;
        else
            m_delta = (TADDR)addr - (TADDR)base;
    }

    // Set encoded value of the pointer. The value can be NULL.
    FORCEINLINE void SetValueMaybeNull(PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        SetValueMaybeNull((TADDR)this, addr);
    }
#endif

#ifndef DACCESS_COMPILE
    void BitwiseCopyTo(RelativePointer<PTR_TYPE> &dest) const
    {
        dest.m_delta = m_delta;
    }
#endif // DACCESS_COMPILE

private:
#ifndef DACCESS_COMPILE
    Volatile<TADDR> m_delta;
#else
    TADDR m_delta;
#endif
};

//----------------------------------------------------------------------------
// FixupPointer is pointer with optional indirection. It is used to reduce number
// of private pages in NGen images - cross-module pointers that written to at runtime
// are packed together and accessed via indirection.
//
// The direct flavor (lowest bit of m_addr is cleared) is user for intra-module pointers
// in NGen images, and in datastructuters allocated at runtime.
//
// The indirect mode (lowest bit of m_addr is set) is used for cross-module pointers
// in NGen images.
//

// Friendly name for lowest bit that marks the indirection
#define FIXUP_POINTER_INDIRECTION 1

template<typename PTR_TYPE>
class FixupPointer
{
public:

    static constexpr bool isRelative = false;
    typedef PTR_TYPE type;

    // Returns whether the encoded pointer is NULL.
    BOOL IsNull() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return m_addr == 0;
    }

    // Returns whether the indirection cell contain fixup that has not been converted to real pointer yet.
    FORCEINLINE BOOL IsTagged() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        TADDR addr = m_addr;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
             return (*PTR_TADDR(addr - FIXUP_POINTER_INDIRECTION) & 1) != 0;
        return FALSE;
    }

    // Returns value of the encoded pointer.
    FORCEINLINE PTR_TYPE GetValue() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        TADDR addr = m_addr;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
            addr = *PTR_TADDR(addr - FIXUP_POINTER_INDIRECTION);
        return dac_cast<PTR_TYPE>(addr);
    }

    // Returns the pointer to the indirection cell.
    PTR_TYPE * GetValuePtr() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        TADDR addr = m_addr;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
            return dac_cast<DPTR(PTR_TYPE)>(addr - FIXUP_POINTER_INDIRECTION);
        return (PTR_TYPE *)&m_addr;
    }

    // Returns value of the encoded pointer.
    // Allows the value to be tagged.
    FORCEINLINE TADDR GetValueMaybeTagged() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        TADDR addr = m_addr;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
            addr = *PTR_TADDR(addr - FIXUP_POINTER_INDIRECTION);
        return addr;
    }

    void SetValue(PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        m_addr = dac_cast<TADDR>(addr);
    }

private:
    TADDR m_addr;
};

//----------------------------------------------------------------------------
// RelativeFixupPointer is combination of RelativePointer and FixupPointer
template<typename PTR_TYPE>
class RelativeFixupPointer
{
public:

    static constexpr bool isRelative = true;
    typedef PTR_TYPE type;

#ifndef DACCESS_COMPILE
    RelativeFixupPointer()
    {
        SetValueMaybeNull(NULL);
    }
#else // DACCESS_COMPILE
    RelativeFixupPointer() =delete;
#endif // DACCESS_COMPILE

    // Implicit copy/move is not allowed
    RelativeFixupPointer<PTR_TYPE>(const RelativeFixupPointer<PTR_TYPE> &) =delete;
    RelativeFixupPointer<PTR_TYPE>(RelativeFixupPointer<PTR_TYPE> &&) =delete;
    RelativeFixupPointer<PTR_TYPE>& operator = (const RelativeFixupPointer<PTR_TYPE> &) =delete;
    RelativeFixupPointer<PTR_TYPE>& operator = (RelativeFixupPointer<PTR_TYPE> &&) =delete;

    // Returns whether the encoded pointer is NULL.
    BOOL IsNull() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        // Pointer pointing to itself is treated as NULL
        return m_delta == (TADDR)NULL;
    }

    // Returns whether the indirection cell contain fixup that has not been converted to real pointer yet.
    FORCEINLINE BOOL IsTagged(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        TADDR addr = base + m_delta;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
             return (*PTR_TADDR(addr - FIXUP_POINTER_INDIRECTION) & 1) != 0;
        return FALSE;
    }

#ifndef DACCESS_COMPILE
    FORCEINLINE BOOL IsTagged() const
    {
        LIMITED_METHOD_CONTRACT;
        TADDR base = (TADDR) this;
        return IsTagged(base);
    }
#endif // !DACCESS_COMPILE

    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    FORCEINLINE PTR_TYPE GetValue(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        PRECONDITION(!IsNull());
        PRECONDITION(!IsTagged(base));
        TADDR addr = base + m_delta;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
            addr = *PTR_TADDR(addr - FIXUP_POINTER_INDIRECTION);
        return dac_cast<PTR_TYPE>(addr);
    }

#ifndef DACCESS_COMPILE
    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    // Does not need explicit base and thus can be used in non-DAC builds only.
    FORCEINLINE PTR_TYPE GetValue() const
    {
        LIMITED_METHOD_CONTRACT;
        return GetValue((TADDR)this);
    }
#endif

    // Static version of GetValue. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(RelativeFixupPointer<PTR_TYPE>)>(base)->GetValue(base);
    }

    // Returns value of the encoded pointer. The pointer can be NULL.
    PTR_TYPE GetValueMaybeNull(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        PRECONDITION(!IsTagged(base));

        // Cache local copy of delta to avoid races when the value is changing under us.
        TADDR delta = m_delta;

        if (delta == 0)
            return NULL;

        TADDR addr = base + delta;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
            addr = *PTR_TADDR(addr - FIXUP_POINTER_INDIRECTION);
        return dac_cast<PTR_TYPE>(addr);
    }

#ifndef DACCESS_COMPILE
    // Returns value of the encoded pointer. The pointer can be NULL.
    // Does not need explicit base and thus can be used in non-DAC builds only.
    FORCEINLINE PTR_TYPE GetValueMaybeNull() const
    {
        LIMITED_METHOD_CONTRACT;
        return GetValueMaybeNull((TADDR)this);
    }
#endif

    // Static version of GetValueMaybeNull. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueMaybeNullAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(RelativeFixupPointer<PTR_TYPE>)>(base)->GetValueMaybeNull(base);
    }

#ifndef DACCESS_COMPILE
    // Set encoded value of the pointer. Assumes that the value is not NULL.
    FORCEINLINE void SetValue(PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        PRECONDITION(addr != NULL);
        m_delta = dac_cast<TADDR>(addr) - (TADDR)this;
    }

    // Set encoded value of the pointer. The value can be NULL.
    void SetValueMaybeNull(TADDR base, PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        if (addr == NULL)
            m_delta = NULL;
        else
            m_delta = dac_cast<TADDR>(addr) - (TADDR)base;
    }

    // Set encoded value of the pointer. The value can be NULL.
    FORCEINLINE void SetValueMaybeNull(PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        SetValueMaybeNull((TADDR)this, addr);
    }
#endif

    // Returns the pointer to the indirection cell.
    PTR_TYPE * GetValuePtr(TADDR base) const
    {
        LIMITED_METHOD_CONTRACT;
        TADDR addr = base + m_delta;
        _ASSERTE((addr & FIXUP_POINTER_INDIRECTION) != 0);
        return dac_cast<DPTR(PTR_TYPE)>(addr - FIXUP_POINTER_INDIRECTION);
    }

#ifndef DACCESS_COMPILE
    PTR_TYPE * GetValuePtr() const
    {
        LIMITED_METHOD_CONTRACT;
        TADDR base = (TADDR) this;
        return GetValuePtr(base);
    }
#endif // !DACCESS_COMPILE

    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    // Allows the value to be tagged.
    FORCEINLINE TADDR GetValueMaybeTagged(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        PRECONDITION(!IsNull());
        TADDR addr = base + m_delta;
        if ((addr & FIXUP_POINTER_INDIRECTION) != 0)
            addr = *PTR_TADDR(addr - FIXUP_POINTER_INDIRECTION);
        return addr;
    }

private:
#ifndef DACCESS_COMPILE
    Volatile<TADDR> m_delta;
#else
    TADDR m_delta;
#endif
};

// Fixup used for RelativePointer
#define IMAGE_REL_BASED_RelativePointer IMAGE_REL_BASED_RELPTR

#endif // FEATURE_PREJIT

//----------------------------------------------------------------------------
// PlainPointer is simple pointer wrapper to support compilation without indirections
// This is useful for building size-constrained runtime without NGen support.
template<typename PTR_TYPE>
class PlainPointer
{
public:

    static constexpr bool isRelative = false;
    typedef PTR_TYPE type;

    // Returns whether the encoded pointer is NULL.
    BOOL IsNull() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return m_ptr == NULL;
    }

    // Returns whether the indirection cell contain fixup that has not been converted to real pointer yet.
    BOOL IsTagged() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return m_ptr & 1;
    }

    // Returns value of the encoded pointer.
    PTR_TYPE GetValue() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<PTR_TYPE>(m_ptr);
    }

    // Returns the pointer to the indirection cell.
    PTR_TYPE * GetValuePtr() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return (PTR_TYPE *)&m_ptr;
    }

    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    PTR_TYPE GetValue(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        PRECONDITION(!IsNull());
        return dac_cast<PTR_TYPE>(m_ptr);
    }

    // Static version of GetValue. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(PlainPointer<PTR_TYPE>)>(base)->GetValue(base);
    }

    // Returns value of the encoded pointer. The pointer can be NULL.
    PTR_TYPE GetValueMaybeNull(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<PTR_TYPE>(m_ptr);
    }

    // Static version of GetValueMaybeNull. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueMaybeNullAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(PlainPointer<PTR_TYPE>)>(base)->GetValueMaybeNull(base);
    }

    void SetValue(PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        m_ptr = dac_cast<TADDR>(addr);
    }

    // Set encoded value of the pointer. Assumes that the value is not NULL.
    void SetValue(TADDR base, PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        PRECONDITION(addr != NULL);
        m_ptr = dac_cast<TADDR>(addr);
    }

    // Static version of SetValue. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static void SetValueAtPtr(TADDR base, PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        dac_cast<DPTR(PlainPointer<PTR_TYPE>)>(base)->SetValue(base, addr);
    }

    // Set encoded value of the pointer. The value can be NULL.
    void SetValueMaybeNull(TADDR base, PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        m_ptr = dac_cast<TADDR>(addr);
    }

#ifndef DACCESS_COMPILE
    // Set encoded value of the pointer. The value can be NULL.
    // Does not need explicit base and thus can be used in non-DAC builds only.
    FORCEINLINE void SetValueMaybeNull(PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        return SetValueMaybeNull((TADDR)this, addr);
    }
#endif

    // Static version of SetValueMaybeNull. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static void SetValueMaybeNullAtPtr(TADDR base, PTR_TYPE addr)
    {
        LIMITED_METHOD_CONTRACT;
        dac_cast<DPTR(PlainPointer<PTR_TYPE>)>(base)->SetValueMaybeNull(base, addr);
    }

private:
    TADDR m_ptr;
};

#ifndef FEATURE_PREJIT

#define FixupPointer PlainPointer
#define RelativePointer PlainPointer
#define RelativeFixupPointer PlainPointer

#endif // !FEATURE_PREJIT

//----------------------------------------------------------------------------
// RelativePointer32 is pointer encoded as relative 32-bit offset. It is used
// to reduce both the size of the pointer itself as well as size of relocation
// section for pointers that live exlusively in NGen images.
template<typename PTR_TYPE>
class RelativePointer32
{
public:

    static constexpr bool isRelative = true;
    typedef PTR_TYPE type;

    // Returns whether the encoded pointer is NULL.
    BOOL IsNull() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        // Pointer pointing to itself is treated as NULL
        return m_delta == 0;
    }

    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    PTR_TYPE GetValue(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        PRECONDITION(!IsNull());
        return dac_cast<PTR_TYPE>(base + m_delta);
    }

#ifndef DACCESS_COMPILE
    // Returns value of the encoded pointer. Assumes that the pointer is not NULL.
    // Does not need explicit base and thus can be used in non-DAC builds only.
    FORCEINLINE PTR_TYPE GetValue() const
    {
        LIMITED_METHOD_CONTRACT;
        return GetValue((TADDR)this);
    }
#endif

    // Static version of GetValue. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(RelativePointer<PTR_TYPE>)>(base)->GetValue(base);
    }

    // Returns value of the encoded pointer. The pointer can be NULL.
    PTR_TYPE GetValueMaybeNull(TADDR base) const
    {
        LIMITED_METHOD_DAC_CONTRACT;

        // Cache local copy of delta to avoid races when the value is changing under us.
        TADDR delta = m_delta;

        if (delta == 0)
            return NULL;

        return dac_cast<PTR_TYPE>(base + delta);
    }

#ifndef DACCESS_COMPILE
    // Returns value of the encoded pointer. The pointer can be NULL.
    // Does not need explicit base and thus can be used in non-DAC builds only.
    FORCEINLINE PTR_TYPE GetValueMaybeNull() const
    {
        LIMITED_METHOD_CONTRACT;
        return GetValueMaybeNull((TADDR)this);
    }
#endif

    // Static version of GetValueMaybeNull. It is meant to simplify access to arrays of pointers.
    FORCEINLINE static PTR_TYPE GetValueMaybeNullAtPtr(TADDR base)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<DPTR(RelativePointer<PTR_TYPE>)>(base)->GetValueMaybeNull(base);
    }

private:
    INT32 m_delta;
};

template<bool isMaybeNull, typename T, typename PT>
typename PT::type
ReadPointer(const T *base, const PT T::* pPointerFieldMember)
{
    LIMITED_METHOD_DAC_CONTRACT;

    uintptr_t offset = (uintptr_t) &(base->*pPointerFieldMember) - (uintptr_t) base;

    if (isMaybeNull)
    {
        return PT::GetValueMaybeNullAtPtr(dac_cast<TADDR>(base) + offset);
    }
    else
    {
        return PT::GetValueAtPtr(dac_cast<TADDR>(base) + offset);
    }
}

template<typename T, typename PT>
typename PT::type
ReadPointerMaybeNull(const T *base, const PT T::* pPointerFieldMember)
{
    LIMITED_METHOD_DAC_CONTRACT;

    return ReadPointer<true>(base, pPointerFieldMember);
}

template<typename T, typename PT>
typename PT::type
ReadPointer(const T *base, const PT T::* pPointerFieldMember)
{
    LIMITED_METHOD_DAC_CONTRACT;

    return ReadPointer<false>(base, pPointerFieldMember);
}

template<bool isMaybeNull, typename T, typename C, typename PT>
typename PT::type
ReadPointer(const T *base, const C T::* pFirstPointerFieldMember, const PT C::* pSecondPointerFieldMember)
{
    LIMITED_METHOD_DAC_CONTRACT;

    const PT *ptr = &(base->*pFirstPointerFieldMember.*pSecondPointerFieldMember);
    uintptr_t offset = (uintptr_t) ptr - (uintptr_t) base;

    if (isMaybeNull)
    {
        return PT::GetValueMaybeNullAtPtr(dac_cast<TADDR>(base) + offset);
    }
    else
    {
        return PT::GetValueAtPtr(dac_cast<TADDR>(base) + offset);
    }
}

template<typename T, typename C, typename PT>
typename PT::type
ReadPointerMaybeNull(const T *base, const C T::* pFirstPointerFieldMember, const PT C::* pSecondPointerFieldMember)
{
    LIMITED_METHOD_DAC_CONTRACT;

    return ReadPointer<true>(base, pFirstPointerFieldMember, pSecondPointerFieldMember);
}

template<typename T, typename C, typename PT>
typename PT::type
ReadPointer(const T *base, const C T::* pFirstPointerFieldMember, const PT C::* pSecondPointerFieldMember)
{
    LIMITED_METHOD_DAC_CONTRACT;

    return ReadPointer<false>(base, pFirstPointerFieldMember, pSecondPointerFieldMember);
}

#endif //_FIXUPPOINTER_H

redpajama_set_name: RedPajamaGithub


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Zend\ServiceManager — Zend Framework 2 2.3.0dev documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="Zend Framework 2 2.3.0dev documentation" href="../index.html" />
    <link rel="next" title="Zend\ServiceManager Quick Start" href="zend.service-manager.quick-start.html" />
    <link rel="prev" title="Zend\Server\Reflection" href="zend.server.reflection.html" />

Navigation

          index

          next |

          previous |

Zend Framework 2 2.3.0dev documentation »

Zend\ServiceManager¶

The Service Locator design pattern is implemented by the <tt class="docutils literal">Zend\ServiceManager</tt> component.
The Service Locator is a  service/object locator, tasked with retrieving other objects.
Following is the <tt class="docutils literal">Zend\ServiceManager\ServiceLocatorInterface</tt> API:

1
2
3
4
5
6
7

namespace Zend\ServiceManager;

interface ServiceLocatorInterface
{
    public function get($name);
    public function has($name);
}

<tt class="docutils literal">has($name)</tt>, tests whether the <tt class="docutils literal">ServiceManager</tt> has a named service;

<tt class="docutils literal">get($name)</tt>, retrieves a service by the given name.

A <tt class="docutils literal">Zend\ServiceManager\ServiceManager</tt> is an implementation of the <tt class="docutils literal">ServiceLocatorInterface</tt>.
In addition to the above described methods, the <tt class="docutils literal">ServiceManager</tt> provides additional API:

Service registration. <tt class="docutils literal">ServiceManager::setService</tt> allows you to register an object as a service:

1
2
3
4
5

$serviceManager->setService('my-foo', new stdClass());
$serviceManager->setService('my-settings', array('password' => 'super-secret'));

var_dump($serviceManager->get('my-foo')); // an instance of stdClass
var_dump($serviceManager->get('my-settings')); // array('password' => 'super-secret')

Lazy-loaded service objects. <tt class="docutils literal">ServiceManager::setInvokableClass</tt> allows you to tell the
<tt class="docutils literal">ServiceManager</tt> what class to instantiate when a particular service is requested:

1
2
3

$serviceManager->setInvokableClass('foo-service-name', 'Fully\Qualified\Classname');

var_dump($serviceManager->get('foo-service-name')); // an instance of Fully\Qualified\Classname

Service factories. Instead of an actual object instance or a class name, you can tell the
<tt class="docutils literal">ServiceManager</tt> to invoke a provided factory in order to get the object instance. Factories
may be either a PHP callback, an object implementing <tt class="docutils literal">Zend\ServiceManager\FactoryInterface</tt>,
or the name of a class implementing that interface:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class MyFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new \stdClass();
    }
}

// registering a factory instance
$serviceManager->setFactory('foo-service-name', new MyFactory());

// registering a factory by factory class name
$serviceManager->setFactory('bar-service-name', 'MyFactory');

// registering a callback as a factory
$serviceManager->setFactory('baz-service-name', function () { return new \stdClass(); });

var_dump($serviceManager->get('foo-service-name')); // stdClass(1)
var_dump($serviceManager->get('bar-service-name')); // stdClass(2)
var_dump($serviceManager->get('baz-service-name')); // stdClass(3)

Service aliasing. With <tt class="docutils literal">ServiceManager::setAlias</tt> you can create aliases of any registered
service, factory or invokable, or even other aliases:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

$foo      = new \stdClass();
$foo->bar = 'baz!';

$serviceManager->setService('my-foo', $foo);
$serviceManager->setAlias('my-bar', 'my-foo');
$serviceManager->setAlias('my-baz', 'my-bar');

var_dump($serviceManager->get('my-foo')->bar); // baz!
var_dump($serviceManager->get('my-bar')->bar); // baz!
var_dump($serviceManager->get('my-baz')->bar); // baz!

Abstract factories. An abstract factory can be considered as a “fallback” factory. If the
service manager was not able to find a service for the requested name, it will check the registered
abstract factories:

 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

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\AbstractFactoryInterface;

class MyAbstractFactory implements AbstractFactoryInterface
{
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        // this abstract factory only knows about 'foo' and 'bar'
        return $requestedName === 'foo' || $requestedName === 'bar';
    }

    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        $service = new \stdClass();

        $service->name = $requestedName;

        return $service;
    }
}

$serviceManager->addAbstractFactory('MyAbstractFactory');

var_dump($serviceManager->get('foo')->name); // foo
var_dump($serviceManager->get('bar')->name); // bar
var_dump($serviceManager->get('baz')->name); // exception! Zend\ServiceManager\Exception\ServiceNotFoundException

Initializers. You may want certain injection points to be always called. As an example,
any object you load via the service manager that implements
<tt class="docutils literal">Zend\EventManager\EventManagerAwareInterface</tt> should likely receive an <tt class="docutils literal">EventManager</tt>
instance. Initializers are PHP callbacks or classes implementing
<tt class="docutils literal">Zend\ServiceManager\InitializerInterface</tt>. They receive the new instance, and can then manipulate it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\InitializerInterface;

class MyInitializer implements InitializerInterface
{
    public function initialize($instance, ServiceLocatorInterface $serviceLocator)
    {
        if ($instance instanceof \stdClass) {
            $instance->initialized = 'initialized!';
        }
    }
}

$serviceManager->setInvokableClass('my-service', 'stdClass');

var_dump($serviceManager->get('my-service')->initialized); // initialized!

In addition to the above, the <tt class="docutils literal">ServiceManager</tt> also provides optional ties to <tt class="docutils literal">Zend\Di</tt>, allowing <tt class="docutils literal">Di</tt> to act
as an initializer or an abstract factory for the service manager.

Previous topic

Zend\Server\Reflection

Next topic

Zend\ServiceManager Quick Start

This Page

        Show Source

Edit Source

            Note: You need to stay logged into your GitHub account to contribute to the documentation.

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

Zend Framework 2 2.3.0dev documentation »

        © Copyright 2013, Zend Technologies Ltd..
      Created using Sphinx 1.2b3.

Edit this document

        The source code of this file is hosted on GitHub. Everyone can
        update and fix errors in this document with few clicks -
        no downloads needed.

            Login with your GitHub account.

            Go to

                Zend\ServiceManager
             on GitHub.

            Edit file contents using GitHub's text editor in your web browser

            Fill in the Commit message text box at the end of the page telling why
            you did the changes. Press Propose file change button next to it when done.

            On Send a pull request page you don't need to fill in text anymore. Just
            press Send pull request button.

            Your changes are now queued for review under project's Pull requests tab on GitHub.


text:
<?php

namespace Freifunk\StatisticBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * NodeStatRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class NodeStatRepository extends EntityRepository
{
    /**
     * Returns the last node status of the specified node
     *
     * @param Node $node
     *
     * @return NodeStat
     */
    public function getLastStatOf(Node $node)
    {
        $qb = $this->createQueryBuilder('s');
        $qb->andWhere($qb->expr()->eq('s.node', $qb->expr()->literal($node->getId())));
        $qb->orderBy('s.time', 'DESC');
        $qb->setMaxResults(1);

        return $qb->getQuery()->getOneOrNullResult();
    }
}


text:
fixture `gh-1388`
    .page `http://localhost:3000/fixtures/regression/gh-1388/pages/index.html`;

test('Press keys in a textarea', async t => {
    await t
        .click('#textarea', { caretPos: 0 })
        .pressKey('space enter backspace home delete');

    const selectionLog = await t.eval(() => window.selectionLog);

    await t.expect(selectionLog).eql([1, 2, 1, 0]);
});


text:
module Ramsey
  class Index
    extend Forwardable
    include Enumerable

    attr_reader :name

    def initialize(name = nil, configuration = nil, &block)
      @name = name
      @indexer = indexer.new
      @config = configuration || Configuration.new(&block) if block_given?
    end

    def self.load(the_path)
      index = new(nil) do
        path the_path
      end
      index.load!
    end

    # this will probably be abstracted, and subclasses will implement
    # appropriately
    def update(data)
      delete(hash_for(data), data[:uuid])
      create(hash_for(data), data[:uuid])
    end

    def update!(*args)
      update(*args)
      save!
    end

    delegate [:each] => :indexer

    # should delegate over to the indexer
    def delete(value, uuid)
      self[value].delete(uuid)
    end

    def [](value)
      indexer[value] || Set.new
    end

    def delete!(*args)
      delete(*args)
      save!
    end

    def save!
      file.open(path, 'w+') do |f|
        f.puts name
        f.puts type
        f.puts properties.join(",")

        indexer.each do |k,v|
          f.puts "#{k}:#{v}"
        end
      end

      self
    end

    def load!
      content = file.read(path).split("\n")

      @name = content.shift.chomp
      config.type content.shift.chomp.to_sym
      config.properties content.shift.chomp.split(',').map(&:to_sym)

      content.each do |line|
        key, value = *line.chomp.split(':')

        indexer[key] ||= Set.new
        indexer[key] << value
      end

      self
    end

    delegate [:path, :type, :properties] => :config

    def ==(other)
      name == other.name
      properties == other.properties
      type == other.type

      each do |k, v|
        other[k] == v
      end
    end

    attr_writer :file_interface, :indexer, :hasher

    protected

    def create(key, value)
      indexer[key] = value
    end

    def hash_for(data)
      hasher.hash( property_vector_for(data) )
    end

    def property_vector_for(data)
      properties.map { |p| hasher.hash data[p] }.join('')
    end

    private

    def file
      @file_interface ||= File
    end

    def indexer
      @indexer ||= Hash
    end

    def hasher
      @hasher ||= Hasher.new
    end

    attr_reader :config
  end
end


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef SHAPE_ANIMATION_ASSET_H
#define SHAPE_ANIMATION_ASSET_H

#ifndef _ASSET_BASE_H_
#include "assets/assetBase.h"
#endif

#ifndef _ASSET_DEFINITION_H_
#include "assets/assetDefinition.h"
#endif

#ifndef _STRINGUNIT_H_
#include "string/stringUnit.h"
#endif

#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
#ifndef _TSSHAPE_H_
#include "ts/tsShape.h"
#endif
#ifndef __RESOURCE_H__
#include "core/resource.h"
#endif

//-----------------------------------------------------------------------------
class ShapeAnimationAsset : public AssetBase
{
   typedef AssetBase Parent;

protected:
   StringTableEntry   mFileName;
   StringTableEntry   mFilePath;

   bool            mIsEmbedded;
   bool            mIsCyclical;

   bool            mIsBlend;

   StringTableEntry mBlendAnimAssetName;

   S32 mBlendFrame;

   //
   StringTableEntry mAnimationName;
   S32 mStartFrame;
   S32 mEndFrame;
   bool mPadRotation;
   bool mPadTransforms;

   Resource<TSShape> mSourceShape;

public:
   ShapeAnimationAsset();
   virtual ~ShapeAnimationAsset();

   /// Engine.
   static void initPersistFields();
   virtual void copyTo(SimObject* object);

   void                    setAnimationFile(const char* pAnimationFile);
   inline StringTableEntry getAnimationFile(void) const { return mFileName; };

   inline StringTableEntry getAnimationPath(void) const { return mFilePath; };

   /// Declare Console Object.
   DECLARE_CONOBJECT(ShapeAnimationAsset);

protected:
   virtual void            initializeAsset(void);
   virtual void            onAssetRefresh(void);

   static bool setAnimationFile(void *obj, const char *index, const char *data) { static_cast<ShapeAnimationAsset*>(obj)->setAnimationFile(data); return false; }
   static const char* getAnimationFile(void* obj, const char* data) { return static_cast<ShapeAnimationAsset*>(obj)->getAnimationFile(); }

public:
   StringTableEntry getAnimationFilename() { return mFileName; }
   StringTableEntry getAnimationName() { return mAnimationName; }
   StringTableEntry getBlendAnimationName() { return mBlendAnimAssetName; }

   S32 getStartFrame() { return mStartFrame; }
   S32 getEndFrame() { return mEndFrame; }

   bool getPadRotation() { return mPadRotation; }
   bool getPadTransforms() { return mPadTransforms; }

   bool isEmbedded() { return mIsEmbedded; }
   bool isCyclic() { return mIsCyclical; }
   bool isBlend() { return mIsBlend; }

   S32 getBlendFrame() { return mBlendFrame; }

   S32 getAnimationCount();
};

DefineConsoleType(TypeShapeAnimationAssetPtr, ShapeAnimationAsset)

//-----------------------------------------------------------------------------
// TypeAssetId GuiInspectorField Class
//-----------------------------------------------------------------------------
/*class GuiInspectorTypeShapeAnimationAssetPtr : public GuiInspectorTypeFileName
{
   typedef GuiInspectorTypeFileName Parent;
public:

   GuiBitmapButtonCtrl  *mShapeEdButton;

   DECLARE_CONOBJECT(GuiInspectorTypeShapeAnimationAssetPtr);
   static void consoleInit();

   virtual GuiControl* constructEditControl();
   virtual bool updateRects();
};*/

#endif // _ASSET_BASE_H_


text:
var RefInfos = function () {
    // id所在的对象列表
    this.objList = [];
    // 关键字列表
    this.keyList = [];
    // 引用的id列表
    this.referncedIDList = [];
    // 引用id的次数
    this.referencedCounts = [];
    // 保存有标记_iN$t列表
    this.temporaryDataList = [];
};

var nicifySerialized = function (serialized) {

    var mainObject = serialized[0];

    if (typeof mainObject === 'undefined') {
        return;
    }

    var refInfos = new RefInfos();
    refInfos.referencedCounts = new Array(serialized.length);

    var id;
    var obj;
    var key;
    var value;
    var hasRepeatID;
    var tempSelf = serialized.slice();

    // 遍历,并且保存需要美化的数据
    _iterative(mainObject, serialized, refInfos);

    var idx = 0;

    // del _iN$t
    for (idx = 0; idx < refInfos.temporaryDataList.length; idx++) {
        delete refInfos.temporaryDataList[idx]._iN$t;
    }

    // dereference
    for (idx = 0; idx < refInfos.objList.length; idx++) {
        obj = refInfos.objList[idx];
        id = refInfos.referncedIDList[idx];
        key = refInfos.keyList[idx];
        value = tempSelf[id];
        hasRepeatID = refInfos.referencedCounts[id] > 1;
        if (hasRepeatID) {
            continue;
        }
        obj[key] = value;
        var delIdx = serialized.indexOf(value);
        serialized.splice(delIdx, 1);
    }

    // update id
    for (idx = 0; idx < refInfos.objList.length; idx++) {
        id = refInfos.referncedIDList[idx];
        key = refInfos.keyList[idx];
        obj = refInfos.objList[idx];
        hasRepeatID = refInfos.referencedCounts[id] > 1;
        if (hasRepeatID) {
            value = tempSelf[id];
            var newIdx = serialized.indexOf(value);
            obj[key].__id__ = newIdx;
        }
    }
};

var _iterative = function (obj, serialized, refInfos) {
    if (typeof obj !== 'object') {
        return;
    }
    obj._iN$t = true;
    refInfos.temporaryDataList.push(obj);
    if (obj.content) {
        var type = obj.__type__ && Fire.JS._getClassById(obj.__type__);
        if (type && type.prototype._serialize) {
            // skip customized data
            return;
        }
    }

    var element;
    if (Array.isArray(obj)) {
        for (var key = 0; key < obj.length; key++) {
            element = obj[key];
            if (element) {
                _traversalChild(element, key, obj, serialized, refInfos);
            }
        }
    }
    else {
        for (var i in obj) {
            element = obj[i];
            if (element) {
                _traversalChild(element, i, obj, serialized, refInfos);
            }
        }
    }
};

var _traversalChild = function (element, key, obj, serialized, refInfos) {
    var hasRepeatID;
    var id = element.__id__;
    var hasID = typeof id !== 'undefined';
    if (hasID) {
        element = serialized[id];
        hasRepeatID = refInfos.referncedIDList.indexOf(id) !== -1;
        if (hasRepeatID) {
            refInfos.referencedCounts[id]++;
        }
        else {
            refInfos.referencedCounts[id] = 1;
        }
        refInfos.referncedIDList.push(id);
        refInfos.keyList.push(key);
        refInfos.objList.push(obj);
    }
    var isNew = !element._iN$t;
    if (isNew) {
        _iterative(element, serialized, refInfos);
    }
    else {
        if (hasID) {
            refInfos.referencedCounts[id]++;
        }
    }
};

Fire._nicifySerialized = nicifySerialized;
module.exports = nicifySerialized;


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

import java.math.BigInteger;

import ghidra.program.model.address.*;
import ghidra.util.GhidraDataConverter;

/**
 * MemBufferImpl implements the MemBuffer interface.  It buffers up N bytes
 * at time, reducing the overall number of calls to Memory, greatly reducing
 * the overhead of various error checks.  This implementation will not wrap
 * if the end of the memory space is encountered.
 *
 * The {@link #getByte(int)} method can cause the buffer cache to adjust if
 * outside the current cache range.  This is not the case for other methods which
 * will simply defer to the underlying memory if outside the cache range.
 */

public class MemoryBufferImpl implements MutableMemBuffer {

	private final GhidraDataConverter converter;

	private static final int DEFAULT_BUFSIZE = 1024;

	private Memory mem;
	private Address startAddr;
	private byte[] buffer;
	private int startAddrIndex = 0;
	private int minOffset = 0;
	private int maxOffset = -1;
	private int threshold = 0;

	/**
	 * Construct a new MemoryBufferImpl
	 * @param mem memory associated with the given address
	 * @param addr start address
	 */
	public MemoryBufferImpl(Memory mem, Address addr) {
		this(mem, addr, DEFAULT_BUFSIZE);
	}

	/**
	 * Construct a new MemoryBufferImpl
	 * @param mem memory associated with the given address
	 * @param addr start address
	 * @param bufSize the size of the memory buffer.
	 */
	public MemoryBufferImpl(Memory mem, Address addr, int bufSize) {
		this.mem = mem;
		buffer = new byte[bufSize];
		threshold = bufSize / 100; // 1/100 of buffer size

		this.converter = GhidraDataConverter.getInstance(mem.isBigEndian());
		setPosition(addr);
	}

	@Override
	public MemoryBufferImpl clone() {
		return new MemoryBufferImpl(mem, startAddr, buffer.length);
	}

	@Override
	public void advance(int displacement) throws AddressOverflowException {
		Address addr = startAddr.addNoWrap(displacement);
		setPosition(addr);
	}

	@Override
	public void setPosition(Address addr) {
		if (minOffset <= maxOffset) {
			if (addr.getAddressSpace().equals(startAddr.getAddressSpace())) {
				long diff = addr.subtract(startAddr);
				if (diff >= minOffset && diff < maxOffset - threshold) {
					startAddr = addr;
					minOffset -= (int) diff;
					maxOffset -= (int) diff;
					startAddrIndex += diff;
					return;
				}
			}
		}
		startAddr = addr;
		startAddrIndex = 0;
		minOffset = 0;
		maxOffset = -1;

		try {
			maxOffset = mem.getBytes(addr, buffer, 0, buffer.length) - 1;
		}
		catch (AddressOutOfBoundsException | MemoryAccessException e) {
			// handled by maxOffset == -1
		}
	}

	@Override
	public byte getByte(int offset) throws MemoryAccessException {
		if ((offset >= minOffset) && (offset <= maxOffset)) {
			return buffer[startAddrIndex + offset];
		}
		try {
			Address addr = startAddr.addNoWrap(offset);

			int nRead = mem.getBytes(addr, buffer, 0, buffer.length);

			startAddrIndex = -offset;
			minOffset = offset;
			maxOffset = offset + nRead - 1;

			return buffer[0];
		}
		catch (AddressOverflowException e) {
			throw new MemoryAccessException(e.getMessage());
		}
	}

	@Override
	public Address getAddress() {
		return startAddr;
	}

	@Override
	public Memory getMemory() {
		return mem;
	}

	@Override
	public int getBytes(byte[] b, int offset) {
		if (offset >= minOffset && (b.length + offset) <= maxOffset) {
			System.arraycopy(buffer, startAddrIndex + offset, b, 0, b.length);
			return b.length;
		}
		try {
			return mem.getBytes(startAddr.addNoWrap(offset), b);
		}
		catch (AddressOverflowException | MemoryAccessException e) {
			return 0;
		}
	}

	@Override
	public boolean isBigEndian() {
		return mem.isBigEndian();
	}

	@Override
	public short getShort(int offset) throws MemoryAccessException {
		return converter.getShort(this, offset);
	}

	@Override
	public int getInt(int offset) throws MemoryAccessException {
		return converter.getInt(this, offset);
	}

	@Override
	public long getLong(int offset) throws MemoryAccessException {
		return converter.getLong(this, offset);
	}

	@Override
	public BigInteger getBigInteger(int offset, int size, boolean signed)
			throws MemoryAccessException {
		return converter.getBigInteger(this, offset, size, signed);
	}
}


text:
Particle Photon Sensors - DHT22

### What is this repository for? ###

This script allows to read data from a DHT22 (or other sensors supported by PietteTech_DHT library) using Particle Photon and publish retrieved data on the web and print it on serial

### How do I get set up? ###

* Copy the code contained into dht22.ino into Particle Build: https://build.particle.io/build/new
* Add the required PietteTech_DHT library to your project searching it in "Libraries", in your Particle Build project
* Flash it to your Particle Photon
* Cackle into a dark cave

### Possible problems ###

If you get weird output from serial, in 99% of the cases, it is because of a bad connection or the use of a wrong resistor.

I had success with 4.7k resistor but your mileage may vary.

### Retrieve published variables using Particle API ###

* Temperature: https://api.particle.io/v1/devices/YOUR_DEVICE_ID/temperature/?access_token=YOUR_ACCESS_TOKEN
* Humidity: https://api.particle.io/v1/devices/YOUR_DEVICE_ID/humidity/?access_token=YOUR_ACCESS_TOKEN

Read Particle Documentation if you need further details: https://docs.particle.io/reference/api/

### Contribution guidelines ###

* If you have any idea or suggestion contact directly the Repo Owner

### Who do I talk to? ###

* ltpitt: Repo Owner


text:
@implementation TripleDESEncrypt

+ (NSString*)tripleDES:(NSString*)plainText encryptOrDecrypt:(CCOperation)encryptOrDecrypt
{
    const void *vkey = (const void *)[DESKEY UTF8String];
    NSString *result = [self tripleDES:plainText encryptOrDecrypt:encryptOrDecrypt vkey:vkey];

    return result;
}

+ (NSString*)tripleDES:(NSString*)plainText encryptOrDecrypt:(CCOperation)encryptOrDecrypt vkey:(const void *)vkey
{
    const void *vplainText;
    size_t plainTextBufferSize;

    if (encryptOrDecrypt == kCCDecrypt)//解密
    {

        NSData *EncryptData = [NSData dataFromBase64String:plainText];
        plainTextBufferSize = [EncryptData length];
        vplainText = [EncryptData bytes];
    }
    else //加密
    {
        NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
        plainTextBufferSize = [data length];
        vplainText = (const void *)[data bytes];
    }

    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;

    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);

    ccStatus = CCCrypt(encryptOrDecrypt,
                       kCCAlgorithm3DES,
                       kCCOptionPKCS7Padding | kCCOptionECBMode,
                       vkey,
                       kCCKeySize3DES,
                       nil,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);

    NSString *result;

    if (encryptOrDecrypt == kCCDecrypt)
    {
        result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
                                                               length:(NSUInteger)movedBytes]
                                       encoding:NSUTF8StringEncoding];
    }
    else
    {
        NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
        result = [myData base64EncodedString];
    }
    free(bufferPtr);

    return result;
}

@end


text:
require 'rails_helper'

RSpec.describe Contacts::FindByIdInUsersScope, type: :model do
  let!(:user) { UserRepository.new.create!({ email: "user1@example.com", password: '123456789' }) }
  let!(:user2) { UserRepository.new.create!({ email: "user2@example.com", password: '123456789' }) }
  let!(:contact) { ContactRepository.new.create!( {user_id: user.id}) }
  let(:query) { Contacts::FindByIdInUsersScope.new(user, contact.id) }

  it 'returns contact if correct id is passed' do
    expect(query.execute).to be_present
  end

  it 'returns proper contact' do
    expect(query.execute.id).to eq(contact.id)
  end

  it 'throws Repository::RecordNotFound if wrong user passed' do
    query = Contacts::FindByIdInUsersScope.new(user2, contact.id)
    expect {query.execute }.to raise_exception(Repository::RecordNotFound)
  end

  it 'throws Repository::RecordNotFound if wrong id is passed' do
    query = Contacts::FindByIdInUsersScope.new(user, 9999)
    expect {query.execute }.to raise_exception(Repository::RecordNotFound)
  end
end


text:
<?php
/*
 * This file is part of the PagerBundle package.
 */
namespace HealthCareAbroad\PagerBundle\Templating\Helper;

use Symfony\Component\Templating\Helper\Helper;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Routing\RouterInterface;
use HealthCareAbroad\PagerBundle\Pager;

/**
 * PagerHelper
 */
class PagerHelper extends Helper
{
    /**
     *
     * @var EngineInterface
     */
    protected $engine;
    /**
     *
     * @var RouterInterface
     */
    protected $router;

    /**
     * Constructor
     *
     * @param EngineInterface $engine The template engine service
     * @param RouterInterface $router The router service
     */
    public function __construct(EngineInterface $engine, RouterInterface $router)
    {
        $this->engine = $engine;

        $this->router = $router;
    }

    /**
     * Renders the HTML for a given pager
     *
     * @param Pager $pager A Pager instance
     * @param string $route The route name
     * @param array $parameters Additional route parameters
     * @param string $template The template name
     * @return string The html markup
     */
    public function paginate(Pager $pager, $route, array $parameters = array(), $template = 'PagerBundle:Pager:paginate.html.php')
    {
        return $this->engine->render($template, array('pager' => $pager, 'route' => $route, 'parameters' => $parameters));
    }

    /**
     * Generates a URL for a given route and page
     *
     * This method employs a workaround for "routes" that have no configuration.
     *
     * @param string $route Route name
     * @param int $page Page number
     * @param array $parameters Optional route parameters
     * @return string The url path
     */
    public function path($route, $page, array $parameters = array())
    {
        //TODO: this is just a quick fix and is a temporary workaround for
        //routes that are not known at runtime
        if (isset($parameters['hasNoRouteName'])) {
            return $this->generateUri($route, $page);
        }

        if (isset($parameters['_page'])) {
            $parameters[$parameters['_page']] = $page;

            unset($parameters['_page']);
        } else {
            $parameters['page'] = $page;
        }

        return $this->router->generate($route, $parameters);
    }

    public function getName()
    {
        return 'pager';
    }

    private function generateUri($uri, $page)
    {
        //normalize the uri
        $uriParts = explode('?', $uri);

        return $uriParts[0] . '?page=' . $page;
    }
}


text:
set +euo pipefail
source ~/.bashrc
set -euo pipefail
source ./dev-env.sh
radia_run beamsim-codes build ./dev-build.sh "${1:-}"