ops.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // Copyright 2024 CloudWeGo Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. package expr
  17. import (
  18. "fmt"
  19. )
  20. func idiv(v int64, d int64) (int64, error) {
  21. if d != 0 {
  22. return v / d, nil
  23. } else {
  24. return 0, newRuntimeError("division by zero")
  25. }
  26. }
  27. func imod(v int64, d int64) (int64, error) {
  28. if d != 0 {
  29. return v % d, nil
  30. } else {
  31. return 0, newRuntimeError("division by zero")
  32. }
  33. }
  34. func ipow(v int64, e int64) (int64, error) {
  35. mul := v
  36. ret := int64(1)
  37. /* value must be 0 or positive */
  38. if v < 0 {
  39. return 0, newRuntimeError(fmt.Sprintf("negative base value: %d", v))
  40. }
  41. /* exponent must be non-negative */
  42. if e < 0 {
  43. return 0, newRuntimeError(fmt.Sprintf("negative exponent: %d", e))
  44. }
  45. /* fast power first round */
  46. if (e & 1) != 0 {
  47. ret *= mul
  48. }
  49. /* fast power remaining rounds */
  50. for e >>= 1; e != 0; e >>= 1 {
  51. if mul *= mul; (e & 1) != 0 {
  52. ret *= mul
  53. }
  54. }
  55. /* all done */
  56. return ret, nil
  57. }