funcs_misc.go 18 KB

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