ops.go 988 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package expr
  2. import (
  3. `fmt`
  4. )
  5. func idiv(v int64, d int64) (int64, error) {
  6. if d != 0 {
  7. return v / d, nil
  8. } else {
  9. return 0, newRuntimeError("division by zero")
  10. }
  11. }
  12. func imod(v int64, d int64) (int64, error) {
  13. if d != 0 {
  14. return v % d, nil
  15. } else {
  16. return 0, newRuntimeError("division by zero")
  17. }
  18. }
  19. func ipow(v int64, e int64) (int64, error) {
  20. mul := v
  21. ret := int64(1)
  22. /* value must be 0 or positive */
  23. if v < 0 {
  24. return 0, newRuntimeError(fmt.Sprintf("negative base value: %d", v))
  25. }
  26. /* exponent must be non-negative */
  27. if e < 0 {
  28. return 0, newRuntimeError(fmt.Sprintf("negative exponent: %d", e))
  29. }
  30. /* fast power first round */
  31. if (e & 1) != 0 {
  32. ret *= mul
  33. }
  34. /* fast power remaining rounds */
  35. for e >>= 1; e != 0; e >>= 1 {
  36. if mul *= mul; (e & 1) != 0 {
  37. ret *= mul
  38. }
  39. }
  40. /* all done */
  41. return ret, nil
  42. }