mpi-cmp.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* mpi-cmp.c - MPI functions
  2. * Copyright (C) 1998, 1999 Free Software Foundation, Inc.
  3. *
  4. * This file is part of GnuPG.
  5. *
  6. * GnuPG is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * GnuPG is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
  19. */
  20. #include "mpi-internal.h"
  21. int mpi_cmp_ui(MPI u, unsigned long v)
  22. {
  23. mpi_limb_t limb = v;
  24. mpi_normalize(u);
  25. if (u->nlimbs == 0) {
  26. if (v == 0)
  27. return 0;
  28. else
  29. return -1;
  30. }
  31. if (u->sign)
  32. return -1;
  33. if (u->nlimbs > 1)
  34. return 1;
  35. if (u->d[0] == limb)
  36. return 0;
  37. else if (u->d[0] > limb)
  38. return 1;
  39. else
  40. return -1;
  41. }
  42. EXPORT_SYMBOL_GPL(mpi_cmp_ui);
  43. static int do_mpi_cmp(MPI u, MPI v, int absmode)
  44. {
  45. mpi_size_t usize;
  46. mpi_size_t vsize;
  47. int usign;
  48. int vsign;
  49. int cmp;
  50. mpi_normalize(u);
  51. mpi_normalize(v);
  52. usize = u->nlimbs;
  53. vsize = v->nlimbs;
  54. usign = absmode ? 0 : u->sign;
  55. vsign = absmode ? 0 : v->sign;
  56. /* Compare sign bits. */
  57. if (!usign && vsign)
  58. return 1;
  59. if (usign && !vsign)
  60. return -1;
  61. /* U and V are either both positive or both negative. */
  62. if (usize != vsize && !usign && !vsign)
  63. return usize - vsize;
  64. if (usize != vsize && usign && vsign)
  65. return vsize + usize;
  66. if (!usize)
  67. return 0;
  68. cmp = mpihelp_cmp(u->d, v->d, usize);
  69. if (!cmp)
  70. return 0;
  71. if ((cmp < 0?1:0) == (usign?1:0))
  72. return 1;
  73. return -1;
  74. }
  75. int mpi_cmp(MPI u, MPI v)
  76. {
  77. return do_mpi_cmp(u, v, 0);
  78. }
  79. EXPORT_SYMBOL_GPL(mpi_cmp);
  80. int mpi_cmpabs(MPI u, MPI v)
  81. {
  82. return do_mpi_cmp(u, v, 1);
  83. }
  84. EXPORT_SYMBOL_GPL(mpi_cmpabs);