Debian Codegraph @

src/Util/ZUtil/Pow2Mod.v

raw
1 From Coq Require Import ZArith.
2 From Coq Require Import Lia.
3 Require Import Crypto.Util.ZUtil.Definitions.
4 Require Import Crypto.Util.ZUtil.Notations.
5 Require Import Crypto.Util.ZUtil.Hints.Core.
6 Require Import Crypto.Util.ZUtil.Hints.Ztestbit.
7 Require Import Crypto.Util.ZUtil.Tactics.ZeroBounds.
8 Require Import Crypto.Util.ZUtil.Testbit.
9 Require Import Crypto.Util.Tactics.BreakMatch.
10 Local Open Scope Z_scope.
11
12 Module Z.
13 Lemma pow2_mod_spec : forall a b, (0 <= b) -> Z.pow2_mod a b = a mod (2 ^ b).
14 Proof.
15 intros.
16 unfold Z.pow2_mod.
17 rewrite Z.land_ones; auto.
18 Qed.
19 #[global]
20 Hint Rewrite <- Z.pow2_mod_spec using zutil_arith : convert_to_Ztestbit.
21
22 Lemma pow2_mod_0_r : forall a, Z.pow2_mod a 0 = 0.
23 Proof.
24 intros; rewrite Z.pow2_mod_spec, Z.mod_1_r; reflexivity.
25 Qed.
26
27 Lemma pow2_mod_0_l : forall n, 0 <= n -> Z.pow2_mod 0 n = 0.
28 Proof.
29 intros; rewrite Z.pow2_mod_spec, Z.mod_0_l; try reflexivity; try apply Z.pow_nonzero; lia.
30 Qed.
31
32 Lemma pow2_mod_split : forall a n m, 0 <= n -> 0 <= m ->
33 Z.pow2_mod a (n + m) = Z.lor (Z.pow2_mod a n) ((Z.pow2_mod (a >> n) m) << n).
34 Proof.
35 intros; cbv [Z.pow2_mod].
36 apply Z.bits_inj'; intros.
37 repeat progress (try break_match; autorewrite with Ztestbit zsimplify; try reflexivity).
38 try match goal with H : ?a < ?b |- context[Z.testbit _ (?a - ?b)] =>
39 rewrite !Z.testbit_neg_r with (n := a - b) by lia end.
40 autorewrite with Ztestbit; reflexivity.
41 Qed.
42
43 Lemma pow2_mod_pow2_mod : forall a n m, 0 <= n -> 0 <= m ->
44 Z.pow2_mod (Z.pow2_mod a n) m = Z.pow2_mod a (Z.min n m).
45 Proof.
46 intros; cbv [Z.pow2_mod].
47 apply Z.bits_inj'; intros.
48 apply Z.min_case_strong; intros; repeat progress (try break_match; autorewrite with Ztestbit zsimplify; try reflexivity).
49 Qed.
50
51 Lemma pow2_mod_pos_bound a b : 0 < b -> 0 <= Z.pow2_mod a b < 2^b.
52 Proof.
53 intros; rewrite Z.pow2_mod_spec by lia.
54 auto with zarith.
55 Qed.
56 #[global]
57 Hint Resolve pow2_mod_pos_bound : zarith.
58
59 Lemma pow2_mod_id_iff : forall a n, 0 <= n ->
60 (Z.pow2_mod a n = a <-> 0 <= a < 2 ^ n).
61 Proof.
62 intros a n H.
63 rewrite Z.pow2_mod_spec by assumption.
64 assert (0 < 2 ^ n) by Z.zero_bounds.
65 rewrite Z.mod_small_iff by lia.
66 split; intros; intuition lia.
67 Qed.
68 End Z.