cgl.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. Tideland Common Go Library
  3. Copyright (C) 2009-2011 Frank Mueller / Oldenburg / Germany
  4. Redistribution and use in source and binary forms, with or
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. Redistributions of source code must retain the above copyright notice, this
  8. list of conditions and the following disclaimer.
  9. Redistributions in binary form must reproduce the above copyright notice,
  10. this list of conditions and the following disclaimer in the documentation
  11. and/or other materials provided with the distribution.
  12. Neither the name of Tideland nor the names of its contributors may be
  13. used to endorse or promote products derived from this software without
  14. specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  19. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  20. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  21. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  22. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  23. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  24. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  25. THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. // The package 'cgl' contains a lot of helpful stuff for many kinds of software. Those
  28. // are a map/reduce, sorting, time handling, UUIDs, lazy evaluation, chronological jobs,
  29. // state machines, monitoring, suervision, a simple markup language and much more.
  30. package cgl
  31. //--------------------
  32. // IMPORTS
  33. //--------------------
  34. import (
  35. "bytes"
  36. "crypto/rand"
  37. "fmt"
  38. "encoding/hex"
  39. "io"
  40. "log"
  41. "reflect"
  42. "runtime"
  43. "strings"
  44. "unicode"
  45. )
  46. //--------------------
  47. // CONST
  48. //--------------------
  49. const RELEASE = "Tideland Common Go Library Release 2011-08-02"
  50. //--------------------
  51. // DEBUGGING
  52. //--------------------
  53. // Debug prints a debug information to the log with file and line.
  54. func Debug(format string, a ...interface{}) {
  55. _, file, line, _ := runtime.Caller(1)
  56. info := fmt.Sprintf(format, a...)
  57. log.Printf("[cgl] debug %s:%d %v", file, line, info)
  58. }
  59. //--------------------
  60. // UUID
  61. //--------------------
  62. // UUID represent a universal identifier with 16 bytes.
  63. type UUID []byte
  64. // NewUUID generates a new UUID based on version 4.
  65. func NewUUID() UUID {
  66. uuid := make([]byte, 16)
  67. _, err := io.ReadFull(rand.Reader, uuid)
  68. if err != nil {
  69. log.Fatal(err)
  70. }
  71. // Set version (4) and variant (2).
  72. var version byte = 4 << 4
  73. var variant byte = 2 << 4
  74. uuid[6] = version | (uuid[6] & 15)
  75. uuid[8] = variant | (uuid[8] & 15)
  76. return uuid
  77. }
  78. // Raw returns a copy of the UUID bytes.
  79. func (uuid UUID) Raw() []byte {
  80. raw := make([]byte, 16)
  81. copy(raw, uuid[0:16])
  82. return raw
  83. }
  84. // String returns a hexadecimal string representation with
  85. // standardized separators.
  86. func (uuid UUID) String() string {
  87. base := hex.EncodeToString(uuid.Raw())
  88. return base[0:8] + "-" + base[8:12] + "-" + base[12:16] + "-" + base[16:20] + "-" + base[20:32]
  89. }
  90. //--------------------
  91. // MORE ID FUNCTIONS
  92. //--------------------
  93. // LimitedSepIdentifier builds an identifier out of multiple parts,
  94. // all as lowercase strings and concatenated with the separator
  95. // Non letters and digits are exchanged with dashes and
  96. // reduced to a maximum of one each. If limit is true only
  97. // 'a' to 'z' and '0' to '9' are allowed.
  98. func LimitedSepIdentifier(sep string, limit bool, parts ...interface{}) string {
  99. iparts := make([]string, 0)
  100. for _, p := range parts {
  101. tmp := strings.Map(func(r int) int {
  102. // Check letter and digit.
  103. if unicode.IsLetter(r) || unicode.IsDigit(r) {
  104. lcr := unicode.ToLower(r)
  105. if limit {
  106. // Only 'a' to 'z' and '0' to '9'.
  107. if lcr <= unicode.MaxASCII {
  108. return lcr
  109. } else {
  110. return ' '
  111. }
  112. } else {
  113. // Every char is allowed.
  114. return lcr
  115. }
  116. }
  117. return ' '
  118. }, fmt.Sprintf("%v", p))
  119. // Only use non-empty identifier parts.
  120. if ipart := strings.Join(strings.Fields(tmp), "-"); len(ipart) > 0 {
  121. iparts = append(iparts, ipart)
  122. }
  123. }
  124. return strings.Join(iparts, sep)
  125. }
  126. // SepIdentifier builds an identifier out of multiple parts, all
  127. // as lowercase strings and concatenated with the separator
  128. // Non letters and digits are exchanged with dashes and
  129. // reduced to a maximum of one each.
  130. func SepIdentifier(sep string, parts ...interface{}) string {
  131. return LimitedSepIdentifier(sep, false, parts...)
  132. }
  133. // Identifier works like SepIdentifier but the seperator
  134. // is set to be a colon.
  135. func Identifier(parts ...interface{}) string {
  136. return SepIdentifier(":", parts...)
  137. }
  138. // TypeAsIdentifierPart transforms the name of the arguments type into
  139. // a part for identifiers. It's splitted at each uppercase char,
  140. // concatenated with dashes and transferred to lowercase.
  141. func TypeAsIdentifierPart(i interface{}) string {
  142. var buf bytes.Buffer
  143. fullTypeName := reflect.TypeOf(i).String()
  144. lastDot := strings.LastIndex(fullTypeName, ".")
  145. typeName := fullTypeName[lastDot+1:]
  146. for i, r := range typeName {
  147. if unicode.IsUpper(r) {
  148. if i > 0 {
  149. buf.WriteRune('-')
  150. }
  151. }
  152. buf.WriteRune(r)
  153. }
  154. return strings.ToLower(buf.String())
  155. }
  156. //--------------------
  157. // METHOD DISPATCHING
  158. //--------------------
  159. // Dispatch a string to a method of a type.
  160. func Dispatch(variable interface{}, name string, args ...interface{}) ([]interface{}, bool) {
  161. numArgs := len(args)
  162. value := reflect.ValueOf(variable)
  163. valueType := value.Type()
  164. numMethods := valueType.NumMethod()
  165. for i := 0; i < numMethods; i++ {
  166. method := valueType.Method(i)
  167. if (method.PkgPath == "") && (method.Type.NumIn() == numArgs+1) {
  168. if method.Name == name {
  169. // Prepare all args with variable and args.
  170. callArgs := make([]reflect.Value, numArgs+1)
  171. callArgs[0] = value
  172. for i, a := range args {
  173. callArgs[i+1] = reflect.ValueOf(a)
  174. }
  175. // Make the function call.
  176. results := method.Func.Call(callArgs)
  177. // Transfer results into slice of interfaces.
  178. allResults := make([]interface{}, len(results))
  179. for i, v := range results {
  180. allResults[i] = v.Interface()
  181. }
  182. return allResults, true
  183. }
  184. }
  185. }
  186. return nil, false
  187. }
  188. //--------------------
  189. // LAZY EVALUATOR BUILDERS
  190. //--------------------
  191. // Function to evaluate.
  192. type EvalFunc func(interface{}) (interface{}, interface{})
  193. // Generic builder for lazy evaluators.
  194. func BuildLazyEvaluator(evalFunc EvalFunc, initState interface{}) func() interface{} {
  195. retValChan := make(chan interface{})
  196. loopFunc := func() {
  197. var actState interface{} = initState
  198. var retVal interface{}
  199. for {
  200. retVal, actState = evalFunc(actState)
  201. retValChan <- retVal
  202. }
  203. }
  204. retFunc := func() interface{} {
  205. return <-retValChan
  206. }
  207. go loopFunc()
  208. return retFunc
  209. }
  210. // Builder for lazy evaluators with ints as result.
  211. func BuildLazyIntEvaluator(evalFunc EvalFunc, initState interface{}) func() int {
  212. ef := BuildLazyEvaluator(evalFunc, initState)
  213. return func() int {
  214. return ef().(int)
  215. }
  216. }
  217. /*
  218. EOF
  219. */