funcs_misc.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. // Copyright 2022-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package function
  15. import (
  16. "crypto/md5"
  17. "crypto/sha1"
  18. "crypto/sha256"
  19. "crypto/sha512"
  20. b64 "encoding/base64"
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "math"
  25. "reflect"
  26. "strings"
  27. "time"
  28. "github.com/google/uuid"
  29. "github.com/lf-edge/ekuiper/internal/conf"
  30. "github.com/lf-edge/ekuiper/internal/keyedstate"
  31. "github.com/lf-edge/ekuiper/pkg/api"
  32. "github.com/lf-edge/ekuiper/pkg/ast"
  33. "github.com/lf-edge/ekuiper/pkg/cast"
  34. )
  35. func registerMiscFunc() {
  36. builtins["cast"] = builtinFunc{
  37. fType: ast.FuncTypeScalar,
  38. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  39. value := args[0]
  40. newType := args[1]
  41. return cast.ToType(value, newType)
  42. },
  43. val: func(_ api.FunctionContext, args []ast.Expr) error {
  44. if err := ValidateLen(2, len(args)); err != nil {
  45. return err
  46. }
  47. a := args[1]
  48. if ast.IsNumericArg(a) || ast.IsTimeArg(a) || ast.IsBooleanArg(a) {
  49. return ProduceErrInfo(0, "string")
  50. }
  51. if av, ok := a.(*ast.StringLiteral); ok {
  52. if !(av.Val == "bigint" || av.Val == "float" || av.Val == "string" || av.Val == "boolean" || av.Val == "datetime") {
  53. return fmt.Errorf("Expect one of following value for the 2nd parameter: bigint, float, string, boolean, datetime.")
  54. }
  55. }
  56. return nil
  57. },
  58. check: returnNilIfHasAnyNil,
  59. }
  60. builtins["to_json"] = builtinFunc{
  61. fType: ast.FuncTypeScalar,
  62. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  63. rr, err := json.Marshal(args[0])
  64. if err != nil {
  65. return fmt.Errorf("fail to convert %v to json", args[0]), false
  66. }
  67. return string(rr), true
  68. },
  69. val: ValidateOneArg,
  70. check: returnNilIfHasAnyNil,
  71. }
  72. builtins["parse_json"] = builtinFunc{
  73. fType: ast.FuncTypeScalar,
  74. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  75. if args[0] == nil || args[0] == "null" {
  76. return nil, true
  77. }
  78. text, err := cast.ToString(args[0], cast.CONVERT_SAMEKIND)
  79. if err != nil {
  80. return fmt.Errorf("fail to convert %v to string", args[0]), false
  81. }
  82. var data interface{}
  83. err = json.Unmarshal(cast.StringToBytes(text), &data)
  84. if err != nil {
  85. return fmt.Errorf("fail to parse json: %v", err), false
  86. }
  87. return data, true
  88. },
  89. val: ValidateOneStrArg,
  90. }
  91. builtins["chr"] = builtinFunc{
  92. fType: ast.FuncTypeScalar,
  93. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  94. if v, ok := args[0].(int); ok {
  95. return rune(v), true
  96. } else if v, ok := args[0].(float64); ok {
  97. temp := int(v)
  98. return rune(temp), true
  99. } else if v, ok := args[0].(string); ok {
  100. if len(v) > 1 {
  101. return fmt.Errorf("Parameter length cannot larger than 1."), false
  102. }
  103. r := []rune(v)
  104. return r[0], true
  105. } else {
  106. return fmt.Errorf("Only bigint, float and string type can be convert to char type."), false
  107. }
  108. },
  109. val: func(_ api.FunctionContext, args []ast.Expr) error {
  110. if err := ValidateLen(1, len(args)); err != nil {
  111. return err
  112. }
  113. if ast.IsFloatArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  114. return ProduceErrInfo(0, "int")
  115. }
  116. return nil
  117. },
  118. check: returnNilIfHasAnyNil,
  119. }
  120. builtins["encode"] = builtinFunc{
  121. fType: ast.FuncTypeScalar,
  122. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  123. if v, ok := args[1].(string); ok {
  124. if strings.EqualFold(v, "base64") {
  125. if v1, ok1 := args[0].(string); ok1 {
  126. return b64.StdEncoding.EncodeToString([]byte(v1)), true
  127. } else {
  128. return fmt.Errorf("Only string type can be encoded."), false
  129. }
  130. } else {
  131. return fmt.Errorf("Only base64 encoding is supported."), false
  132. }
  133. }
  134. return nil, false
  135. },
  136. val: func(_ api.FunctionContext, args []ast.Expr) error {
  137. if err := ValidateLen(2, len(args)); err != nil {
  138. return err
  139. }
  140. if ast.IsNumericArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  141. return ProduceErrInfo(0, "string")
  142. }
  143. a := args[1]
  144. if !ast.IsStringArg(a) {
  145. return ProduceErrInfo(1, "string")
  146. }
  147. if av, ok := a.(*ast.StringLiteral); ok {
  148. if av.Val != "base64" {
  149. return fmt.Errorf("Only base64 is supported for the 2nd parameter.")
  150. }
  151. }
  152. return nil
  153. },
  154. check: returnNilIfHasAnyNil,
  155. }
  156. builtins["decode"] = builtinFunc{
  157. fType: ast.FuncTypeScalar,
  158. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  159. if v, ok := args[1].(string); ok {
  160. if strings.EqualFold(v, "base64") {
  161. if v1, ok1 := args[0].(string); ok1 {
  162. r, e := b64.StdEncoding.DecodeString(v1)
  163. if e != nil {
  164. return fmt.Errorf("fail to decode base64 string: %v", e), false
  165. }
  166. return r, true
  167. } else {
  168. return fmt.Errorf("Only string type can be decoded."), false
  169. }
  170. } else {
  171. return fmt.Errorf("Only base64 decoding is supported."), false
  172. }
  173. }
  174. return nil, false
  175. },
  176. val: func(_ api.FunctionContext, args []ast.Expr) error {
  177. if err := ValidateLen(2, len(args)); err != nil {
  178. return err
  179. }
  180. if ast.IsNumericArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  181. return ProduceErrInfo(0, "string")
  182. }
  183. a := args[1]
  184. if !ast.IsStringArg(a) {
  185. return ProduceErrInfo(1, "string")
  186. }
  187. if av, ok := a.(*ast.StringLiteral); ok {
  188. if av.Val != "base64" {
  189. return fmt.Errorf("Only base64 is supported for the 2nd parameter.")
  190. }
  191. }
  192. return nil
  193. },
  194. check: returnNilIfHasAnyNil,
  195. }
  196. builtins["trunc"] = builtinFunc{
  197. fType: ast.FuncTypeScalar,
  198. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  199. var v0 float64
  200. if v1, ok := args[0].(int); ok {
  201. v0 = float64(v1)
  202. } else if v1, ok := args[0].(float64); ok {
  203. v0 = v1
  204. } else {
  205. return fmt.Errorf("Only int and float type can be truncated."), false
  206. }
  207. if v2, ok := args[1].(int); ok {
  208. return toFixed(v0, v2), true
  209. } else {
  210. return fmt.Errorf("The 2nd parameter must be int value."), false
  211. }
  212. },
  213. val: func(_ api.FunctionContext, args []ast.Expr) error {
  214. if err := ValidateLen(2, len(args)); err != nil {
  215. return err
  216. }
  217. if ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) || ast.IsStringArg(args[0]) {
  218. return ProduceErrInfo(0, "number - float or int")
  219. }
  220. if ast.IsFloatArg(args[1]) || ast.IsTimeArg(args[1]) || ast.IsBooleanArg(args[1]) || ast.IsStringArg(args[1]) {
  221. return ProduceErrInfo(1, "int")
  222. }
  223. return nil
  224. },
  225. check: returnNilIfHasAnyNil,
  226. }
  227. builtins["md5"] = builtinFunc{
  228. fType: ast.FuncTypeScalar,
  229. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  230. arg0 := cast.ToStringAlways(args[0])
  231. h := md5.New()
  232. _, err := io.WriteString(h, arg0)
  233. if err != nil {
  234. return err, false
  235. }
  236. return fmt.Sprintf("%x", h.Sum(nil)), true
  237. },
  238. val: ValidateOneStrArg,
  239. check: returnNilIfHasAnyNil,
  240. }
  241. builtins["sha1"] = builtinFunc{
  242. fType: ast.FuncTypeScalar,
  243. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  244. arg0 := cast.ToStringAlways(args[0])
  245. h := sha1.New()
  246. _, err := io.WriteString(h, arg0)
  247. if err != nil {
  248. return err, false
  249. }
  250. return fmt.Sprintf("%x", h.Sum(nil)), true
  251. },
  252. val: ValidateOneStrArg,
  253. check: returnNilIfHasAnyNil,
  254. }
  255. builtins["sha256"] = builtinFunc{
  256. fType: ast.FuncTypeScalar,
  257. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  258. arg0 := cast.ToStringAlways(args[0])
  259. h := sha256.New()
  260. _, err := io.WriteString(h, arg0)
  261. if err != nil {
  262. return err, false
  263. }
  264. return fmt.Sprintf("%x", h.Sum(nil)), true
  265. },
  266. val: ValidateOneStrArg,
  267. check: returnNilIfHasAnyNil,
  268. }
  269. builtins["sha384"] = builtinFunc{
  270. fType: ast.FuncTypeScalar,
  271. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  272. arg0 := cast.ToStringAlways(args[0])
  273. h := sha512.New384()
  274. _, err := io.WriteString(h, arg0)
  275. if err != nil {
  276. return err, false
  277. }
  278. return fmt.Sprintf("%x", h.Sum(nil)), true
  279. },
  280. val: ValidateOneStrArg,
  281. check: returnNilIfHasAnyNil,
  282. }
  283. builtins["sha512"] = builtinFunc{
  284. fType: ast.FuncTypeScalar,
  285. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  286. arg0 := cast.ToStringAlways(args[0])
  287. h := sha512.New()
  288. _, err := io.WriteString(h, arg0)
  289. if err != nil {
  290. return err, false
  291. }
  292. return fmt.Sprintf("%x", h.Sum(nil)), true
  293. },
  294. val: ValidateOneStrArg,
  295. check: returnNilIfHasAnyNil,
  296. }
  297. builtinStatfulFuncs["compress"] = func() api.Function {
  298. conf.Log.Infof("initializing compress function")
  299. return &compressFunc{}
  300. }
  301. builtinStatfulFuncs["decompress"] = func() api.Function {
  302. conf.Log.Infof("initializing decompress function")
  303. return &decompressFunc{}
  304. }
  305. builtins["isnull"] = builtinFunc{
  306. fType: ast.FuncTypeScalar,
  307. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  308. if args[0] == nil {
  309. return true, true
  310. } else {
  311. v := reflect.ValueOf(args[0])
  312. switch v.Kind() {
  313. case reflect.Slice, reflect.Map:
  314. return v.IsNil(), true
  315. default:
  316. return false, true
  317. }
  318. }
  319. },
  320. val: ValidateOneArg,
  321. }
  322. builtins["coalesce"] = builtinFunc{
  323. fType: ast.FuncTypeScalar,
  324. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  325. for _, arg := range args {
  326. if arg != nil {
  327. return arg, true
  328. }
  329. }
  330. return nil, true
  331. },
  332. val: func(_ api.FunctionContext, args []ast.Expr) error {
  333. if len(args) == 0 {
  334. return fmt.Errorf("The arguments should be at least one.")
  335. }
  336. return nil
  337. },
  338. }
  339. builtins["newuuid"] = builtinFunc{
  340. fType: ast.FuncTypeScalar,
  341. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  342. if newUUID, err := uuid.NewUUID(); err != nil {
  343. return err, false
  344. } else {
  345. return newUUID.String(), true
  346. }
  347. },
  348. val: ValidateNoArg,
  349. }
  350. builtins["tstamp"] = builtinFunc{
  351. fType: ast.FuncTypeScalar,
  352. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  353. return conf.GetNowInMilli(), true
  354. },
  355. val: ValidateNoArg,
  356. }
  357. builtins["mqtt"] = builtinFunc{
  358. fType: ast.FuncTypeScalar,
  359. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  360. if v, ok := args[0].(string); ok {
  361. return v, true
  362. }
  363. return nil, false
  364. },
  365. val: func(_ api.FunctionContext, args []ast.Expr) error {
  366. if err := ValidateLen(1, len(args)); err != nil {
  367. return err
  368. }
  369. if ast.IsIntegerArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) || ast.IsStringArg(args[0]) || ast.IsFloatArg(args[0]) {
  370. return ProduceErrInfo(0, "meta reference")
  371. }
  372. if p, ok := args[0].(*ast.MetaRef); ok {
  373. name := strings.ToLower(p.Name)
  374. if name != "topic" && name != "messageid" {
  375. return fmt.Errorf("Parameter of mqtt function can be only topic or messageid.")
  376. }
  377. }
  378. return nil
  379. },
  380. check: returnNilIfHasAnyNil,
  381. }
  382. builtins["rule_id"] = builtinFunc{
  383. fType: ast.FuncTypeScalar,
  384. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  385. return ctx.GetRuleId(), true
  386. },
  387. val: ValidateNoArg,
  388. }
  389. builtins["meta"] = builtinFunc{
  390. fType: ast.FuncTypeScalar,
  391. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  392. return args[0], true
  393. },
  394. val: func(_ api.FunctionContext, args []ast.Expr) error {
  395. if err := ValidateLen(1, len(args)); err != nil {
  396. return err
  397. }
  398. if _, ok := args[0].(*ast.MetaRef); ok {
  399. return nil
  400. }
  401. expr := args[0]
  402. for {
  403. if be, ok := expr.(*ast.BinaryExpr); ok {
  404. if _, ok := be.LHS.(*ast.MetaRef); ok && be.OP == ast.ARROW {
  405. return nil
  406. }
  407. expr = be.LHS
  408. } else {
  409. break
  410. }
  411. }
  412. return ProduceErrInfo(0, "meta reference")
  413. },
  414. }
  415. builtins["cardinality"] = builtinFunc{
  416. fType: ast.FuncTypeScalar,
  417. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  418. val := reflect.ValueOf(args[0])
  419. if val.Kind() == reflect.Slice {
  420. return val.Len(), true
  421. }
  422. return 0, true
  423. },
  424. val: ValidateOneArg,
  425. check: return0IfHasAnyNil,
  426. }
  427. builtins["json_path_query"] = builtinFunc{
  428. fType: ast.FuncTypeScalar,
  429. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  430. result, err := jsonCall(ctx, args)
  431. if err != nil {
  432. return err, false
  433. }
  434. return result, true
  435. },
  436. val: ValidateJsonFunc,
  437. }
  438. builtins["json_path_query_first"] = builtinFunc{
  439. fType: ast.FuncTypeScalar,
  440. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  441. result, err := jsonCall(ctx, args)
  442. if err != nil {
  443. return err, false
  444. }
  445. if arr, ok := result.([]interface{}); ok {
  446. return arr[0], true
  447. } else {
  448. return fmt.Errorf("query result (%v) is not an array", result), false
  449. }
  450. },
  451. val: ValidateJsonFunc,
  452. }
  453. builtins["json_path_exists"] = builtinFunc{
  454. fType: ast.FuncTypeScalar,
  455. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  456. result, err := jsonCall(ctx, args)
  457. if err != nil {
  458. return false, true
  459. }
  460. if result == nil {
  461. return false, true
  462. }
  463. e := true
  464. switch reflect.TypeOf(result).Kind() {
  465. case reflect.Slice, reflect.Array:
  466. e = reflect.ValueOf(result).Len() > 0
  467. default:
  468. e = result != nil
  469. }
  470. return e, true
  471. },
  472. val: ValidateJsonFunc,
  473. }
  474. builtins["window_start"] = builtinFunc{
  475. fType: ast.FuncTypeScalar,
  476. exec: nil, // directly return in the valuer
  477. val: ValidateNoArg,
  478. }
  479. builtins["window_end"] = builtinFunc{
  480. fType: ast.FuncTypeScalar,
  481. exec: nil, // directly return in the valuer
  482. val: ValidateNoArg,
  483. }
  484. builtins["object_construct"] = builtinFunc{
  485. fType: ast.FuncTypeScalar,
  486. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  487. result := make(map[string]interface{})
  488. for i := 0; i < len(args); i += 2 {
  489. if args[i+1] != nil {
  490. s, err := cast.ToString(args[i], cast.CONVERT_SAMEKIND)
  491. if err != nil {
  492. return fmt.Errorf("key %v is not a string", args[i]), false
  493. }
  494. result[s] = args[i+1]
  495. }
  496. }
  497. return result, true
  498. },
  499. val: func(_ api.FunctionContext, args []ast.Expr) error {
  500. if len(args)%2 != 0 {
  501. return fmt.Errorf("the args must be key value pairs")
  502. }
  503. for i, arg := range args {
  504. if i%2 == 0 {
  505. if ast.IsNumericArg(arg) || ast.IsTimeArg(arg) || ast.IsBooleanArg(arg) {
  506. return ProduceErrInfo(i, "string")
  507. }
  508. }
  509. }
  510. return nil
  511. },
  512. check: returnNilIfHasAnyNil,
  513. }
  514. builtins["delay"] = builtinFunc{
  515. fType: ast.FuncTypeScalar,
  516. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  517. d, err := cast.ToInt(args[0], cast.CONVERT_SAMEKIND)
  518. if err != nil {
  519. return err, false
  520. }
  521. time.Sleep(time.Duration(d) * time.Millisecond)
  522. return args[1], true
  523. },
  524. val: func(_ api.FunctionContext, args []ast.Expr) error {
  525. if err := ValidateLen(2, len(args)); err != nil {
  526. return err
  527. }
  528. if ast.IsStringArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  529. return ProduceErrInfo(0, "number - float or int")
  530. }
  531. return nil
  532. },
  533. check: returnNilIfHasAnyNil,
  534. }
  535. builtins["get_keyed_state"] = builtinFunc{
  536. fType: ast.FuncTypeScalar,
  537. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  538. if len(args) != 3 {
  539. return fmt.Errorf("the args must be two or three"), false
  540. }
  541. key, ok := args[0].(string)
  542. if !ok {
  543. return fmt.Errorf("key %v is not a string", args[0]), false
  544. }
  545. value, err := keyedstate.GetKeyedState(key)
  546. if err != nil {
  547. return args[2], true
  548. }
  549. return cast.ToType(value, args[1])
  550. },
  551. val: func(_ api.FunctionContext, args []ast.Expr) error {
  552. if err := ValidateLen(3, len(args)); err != nil {
  553. return err
  554. }
  555. a := args[1]
  556. if ast.IsNumericArg(a) || ast.IsTimeArg(a) || ast.IsBooleanArg(a) {
  557. return ProduceErrInfo(0, "string")
  558. }
  559. if av, ok := a.(*ast.StringLiteral); ok {
  560. if !(av.Val == "bigint" || av.Val == "float" || av.Val == "string" || av.Val == "boolean" || av.Val == "datetime") {
  561. return fmt.Errorf("expect one of following value for the 2nd parameter: bigint, float, string, boolean, datetime")
  562. }
  563. }
  564. return nil
  565. },
  566. check: returnNilIfHasAnyNil,
  567. }
  568. }
  569. func round(num float64) int {
  570. return int(num + math.Copysign(0.5, num))
  571. }
  572. func toFixed(num float64, precision int) float64 {
  573. output := math.Pow(10, float64(precision))
  574. return float64(round(num*output)) / output
  575. }
  576. func jsonCall(ctx api.StreamContext, args []interface{}) (interface{}, error) {
  577. jp, ok := args[1].(string)
  578. if !ok {
  579. return nil, fmt.Errorf("invalid jsonPath, must be a string but got %v", args[1])
  580. }
  581. return ctx.ParseJsonPath(jp, args[0])
  582. }
  583. // page Rotate storage for in memory cache
  584. // Not thread safe!
  585. type ringqueue struct {
  586. data []interface{}
  587. h int
  588. t int
  589. l int
  590. size int
  591. }
  592. func newRingqueue(size int) *ringqueue {
  593. return &ringqueue{
  594. data: make([]interface{}, size),
  595. h: 0, // When deleting, head++, if tail == head, it is empty
  596. t: 0, // When append, tail++, if tail== head, it is full
  597. size: size,
  598. }
  599. }
  600. // fill item will fill the queue with item value
  601. func (p *ringqueue) fill(item interface{}) {
  602. for {
  603. if !p.append(item) {
  604. return
  605. }
  606. }
  607. }
  608. // append item if list is not full and return true; otherwise return false
  609. func (p *ringqueue) append(item interface{}) bool {
  610. if p.l == p.size { // full
  611. return false
  612. }
  613. p.data[p.t] = item
  614. p.t++
  615. if p.t == p.size {
  616. p.t = 0
  617. }
  618. p.l++
  619. return true
  620. }
  621. // fetch get the first item in the cache and remove
  622. func (p *ringqueue) fetch() (interface{}, bool) {
  623. if p.l == 0 {
  624. return nil, false
  625. }
  626. result := p.data[p.h]
  627. p.h++
  628. if p.h == p.size {
  629. p.h = 0
  630. }
  631. p.l--
  632. return result, true
  633. }
  634. // peek get the first item in the cache but keep it
  635. func (p *ringqueue) peek() (interface{}, bool) {
  636. if p.l == 0 {
  637. return nil, false
  638. }
  639. result := p.data[p.h]
  640. return result, true
  641. }
  642. func (p *ringqueue) isFull() bool {
  643. return p.l == p.size
  644. }