rsfn4py 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ name: Release to PyPI
2
+
3
+ # A action vai rodar apenas quando você fizer o push de uma Tag do tipo v1.0.0
4
+ on:
5
+ push:
6
+ tags:
7
+ - 'v*'
8
+
9
+ jobs:
10
+ # 1. Compilação para Linux (arquitetura x86_64 e ARM via manylinux)
11
+ linux:
12
+ runs-on: ubuntu-latest
13
+ strategy:
14
+ matrix:
15
+ target: [x86_64, aarch64]
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - name: Build wheels
19
+ uses: PyO3/maturin-action@v1
20
+ with:
21
+ target: ${{ matrix.target }}
22
+ args: --release --out dist -i python3.8 python3.9 python3.10 python3.11 python3.12
23
+ manylinux: auto
24
+ - name: Upload wheels
25
+ uses: actions/upload-artifact@v4
26
+ with:
27
+ name: wheels-linux-${{ matrix.target }}
28
+ path: dist
29
+
30
+ # 2. Compilação para Windows
31
+ windows:
32
+ runs-on: windows-latest
33
+ steps:
34
+ - uses: actions/checkout@v4
35
+ - name: Build wheels
36
+ uses: PyO3/maturin-action@v1
37
+ with:
38
+ args: --release --out dist -i python3.8 python3.9 python3.10 python3.11 python3.12
39
+ - name: Upload wheels
40
+ uses: actions/upload-artifact@v4
41
+ with:
42
+ name: wheels-windows
43
+ path: dist
44
+
45
+ # 3. Compilação para macOS (Universal para rodar em Intel e Apple Silicon M1/M2)
46
+ macos:
47
+ runs-on: macos-latest
48
+ steps:
49
+ - uses: actions/checkout@v4
50
+ - name: Build wheels
51
+ uses: PyO3/maturin-action@v1
52
+ with:
53
+ target: universal2-apple-darwin
54
+ args: --release --out dist -i python3.8 python3.9 python3.10 python3.11 python3.12
55
+ - name: Upload wheels
56
+ uses: actions/upload-artifact@v4
57
+ with:
58
+ name: wheels-macos
59
+ path: dist
60
+
61
+ # 4. Geração do Source Distribution (sdist)
62
+ sdist:
63
+ runs-on: ubuntu-latest
64
+ steps:
65
+ - uses: actions/checkout@v4
66
+ - name: Build sdist
67
+ uses: PyO3/maturin-action@v1
68
+ with:
69
+ command: sdist
70
+ args: --out dist
71
+ - name: Upload sdist
72
+ uses: actions/upload-artifact@v4
73
+ with:
74
+ name: wheels-sdist
75
+ path: dist
76
+
77
+ # 5. Download dos artefatos e publicação no PyPI
78
+ release:
79
+ name: Publish to PyPI
80
+ runs-on: ubuntu-latest
81
+ needs: [linux, windows, macos, sdist]
82
+ # Usaremos o mecanismo de "Trusted Publishers" via OIDC no PyPI (não requer token hardcoded)
83
+ permissions:
84
+ id-token: write
85
+ contents: write
86
+ steps:
87
+ - uses: actions/download-artifact@v4
88
+ with:
89
+ # O merge-multiple: true garante que sdist e wheels caiam na mesma pasta 'dist/'
90
+ merge-multiple: true
91
+ path: dist
92
+ - name: Publish to PyPI
93
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,72 @@
1
+ name: Run Tests
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - master
8
+ pull_request:
9
+ branches:
10
+ - main
11
+ - master
12
+
13
+ jobs:
14
+ test:
15
+ name: Test on ${{ matrix.os }} with Python ${{ matrix.python-version }}
16
+ runs-on: ${{ matrix.os }}
17
+ strategy:
18
+ fail-fast: false
19
+ matrix:
20
+ os: [ubuntu-latest, macos-latest, windows-latest]
21
+ python-version: ["3.8", "3.10", "3.12"]
22
+
23
+ steps:
24
+ - name: Checkout repository
25
+ uses: actions/checkout@v4
26
+
27
+ - name: Set up Rust
28
+ uses: dtolnay/rust-toolchain@stable
29
+
30
+ - name: Set up Python ${{ matrix.python-version }}
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: ${{ matrix.python-version }}
34
+ cache: 'pip'
35
+
36
+ - name: Create Virtual Environment and Install Dependencies
37
+ shell: bash
38
+ run: |
39
+ python -m venv .venv
40
+
41
+ # Habilita o VENV local baseando-se no SO
42
+ if [ "$RUNNER_OS" == "Windows" ]; then
43
+ source .venv/Scripts/activate
44
+ else
45
+ source .venv/bin/activate
46
+ fi
47
+
48
+ # Instala dependências e build system
49
+ python -m pip install --upgrade pip
50
+ pip install pytest maturin
51
+
52
+ - name: Build Rust Extension
53
+ shell: bash
54
+ run: |
55
+ if [ "$RUNNER_OS" == "Windows" ]; then
56
+ source .venv/Scripts/activate
57
+ else
58
+ source .venv/bin/activate
59
+ fi
60
+ # maturin develop constrói os bindings e instala silenciosamente no site-packages do VENV
61
+ maturin develop --release
62
+
63
+ - name: Run Pytest
64
+ shell: bash
65
+ run: |
66
+ if [ "$RUNNER_OS" == "Windows" ]; then
67
+ source .venv/Scripts/activate
68
+ else
69
+ source .venv/bin/activate
70
+ fi
71
+ # Roda os testes na pasta "tests"
72
+ pytest -v tests/
@@ -0,0 +1,26 @@
1
+ # Generated by Cargo
2
+ # will have compiled files and executables
3
+ debug
4
+ target
5
+
6
+ # These are backup files generated by rustfmt
7
+ **/*.rs.bk
8
+
9
+ # MSVC Windows builds of rustc generate these, which store debugging information
10
+ *.pdb
11
+
12
+ # Generated by cargo mutants
13
+ # Contains mutation testing data
14
+ **/mutants.out*/
15
+
16
+ # RustRover
17
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
18
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
19
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
20
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
21
+ #.idea/
22
+
23
+
24
+ # Added by cargo
25
+
26
+ /target
@@ -0,0 +1,132 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "heck"
7
+ version = "0.5.0"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
10
+
11
+ [[package]]
12
+ name = "libc"
13
+ version = "0.2.186"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
16
+
17
+ [[package]]
18
+ name = "once_cell"
19
+ version = "1.21.4"
20
+ source = "registry+https://github.com/rust-lang/crates.io-index"
21
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
22
+
23
+ [[package]]
24
+ name = "portable-atomic"
25
+ version = "1.13.1"
26
+ source = "registry+https://github.com/rust-lang/crates.io-index"
27
+ checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
28
+
29
+ [[package]]
30
+ name = "proc-macro2"
31
+ version = "1.0.106"
32
+ source = "registry+https://github.com/rust-lang/crates.io-index"
33
+ checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
34
+ dependencies = [
35
+ "unicode-ident",
36
+ ]
37
+
38
+ [[package]]
39
+ name = "pyo3"
40
+ version = "0.29.0"
41
+ source = "registry+https://github.com/rust-lang/crates.io-index"
42
+ checksum = "cd274650b21d4bfc26a0a47587962c1edb425f69287324355cd040c3ea66071c"
43
+ dependencies = [
44
+ "libc",
45
+ "once_cell",
46
+ "portable-atomic",
47
+ "pyo3-build-config",
48
+ "pyo3-ffi",
49
+ "pyo3-macros",
50
+ ]
51
+
52
+ [[package]]
53
+ name = "pyo3-build-config"
54
+ version = "0.29.0"
55
+ source = "registry+https://github.com/rust-lang/crates.io-index"
56
+ checksum = "c5e2a7d2f0d013342f295c048ad19237add5154a55b1c5a254c0ec93d4109078"
57
+ dependencies = [
58
+ "target-lexicon",
59
+ ]
60
+
61
+ [[package]]
62
+ name = "pyo3-ffi"
63
+ version = "0.29.0"
64
+ source = "registry+https://github.com/rust-lang/crates.io-index"
65
+ checksum = "ca85c467da1bbc8d866eea5deff9cf29ea5f7785054a17da36e65bda9c05845b"
66
+ dependencies = [
67
+ "libc",
68
+ "pyo3-build-config",
69
+ ]
70
+
71
+ [[package]]
72
+ name = "pyo3-macros"
73
+ version = "0.29.0"
74
+ source = "registry+https://github.com/rust-lang/crates.io-index"
75
+ checksum = "9ac53762fd065daa3194dd09337a38bd793a188100fd1a9304c4ab312d901771"
76
+ dependencies = [
77
+ "proc-macro2",
78
+ "pyo3-macros-backend",
79
+ "quote",
80
+ "syn",
81
+ ]
82
+
83
+ [[package]]
84
+ name = "pyo3-macros-backend"
85
+ version = "0.29.0"
86
+ source = "registry+https://github.com/rust-lang/crates.io-index"
87
+ checksum = "4ca3a1557399783172dc5bf39cfca835157732532cba56b71d2292161e53b362"
88
+ dependencies = [
89
+ "heck",
90
+ "proc-macro2",
91
+ "quote",
92
+ "syn",
93
+ ]
94
+
95
+ [[package]]
96
+ name = "quote"
97
+ version = "1.0.45"
98
+ source = "registry+https://github.com/rust-lang/crates.io-index"
99
+ checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
100
+ dependencies = [
101
+ "proc-macro2",
102
+ ]
103
+
104
+ [[package]]
105
+ name = "rsfn4py"
106
+ version = "0.1.0"
107
+ dependencies = [
108
+ "pyo3",
109
+ ]
110
+
111
+ [[package]]
112
+ name = "syn"
113
+ version = "2.0.118"
114
+ source = "registry+https://github.com/rust-lang/crates.io-index"
115
+ checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
116
+ dependencies = [
117
+ "proc-macro2",
118
+ "quote",
119
+ "unicode-ident",
120
+ ]
121
+
122
+ [[package]]
123
+ name = "target-lexicon"
124
+ version = "0.13.5"
125
+ source = "registry+https://github.com/rust-lang/crates.io-index"
126
+ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
127
+
128
+ [[package]]
129
+ name = "unicode-ident"
130
+ version = "1.0.24"
131
+ source = "registry+https://github.com/rust-lang/crates.io-index"
132
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
@@ -0,0 +1,15 @@
1
+ [package]
2
+ name = "rsfn4py"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ authors = ["Jose Luis da Cruz Junior"]
6
+ description = "High-performance Rust modules for Python applications."
7
+ readme = "README.md"
8
+
9
+ [lib]
10
+ name = "rsfn4py"
11
+ # "cdylib" é necessário para produzir a biblioteca compartilhada que o Python irá importar.
12
+ crate-type = ["cdylib"]
13
+
14
+ [dependencies]
15
+ pyo3 = { version = "0.29.0", features = ["extension-module"] }
rsfn4py-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
rsfn4py-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: rsfn4py
3
+ Version: 0.1.0
4
+ Classifier: Programming Language :: Rust
5
+ Classifier: Programming Language :: Python :: Implementation :: CPython
6
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
7
+ License-File: LICENSE
8
+ Summary: High-performance Rust modules for Python applications.
9
+ Author: Jose Luis da Cruz Junior
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
12
+
13
+ # 🦀🐍 Rust Functions for Python (rsfn4py)
14
+
15
+ ![CI/CD Tests](https://github.com/seu-usuario/rust-services-for-python/actions/workflows/test.yml/badge.svg)
16
+ ![Release](https://github.com/seu-usuario/rust-services-for-python/actions/workflows/release.yml/badge.svg)
17
+ ![Python Versions](https://img.shields.io/pypi/pyversions/rust-services-for-python)
18
+
19
+ Uma coleção de módulos de alta performance escritos em **Rust** para serem consumidos nativamente em projetos **Python**, focando em processamento rápido e baixo consumo de memória.
20
+
21
+ O primeiro módulo desta biblioteca traz a validação do **Novo CNPJ Alfanumérico** (IN RFB 2.119/2022, válido a partir de julho de 2026), processado em Rust com um ganho de performance de aproximadamente **25x** em comparação à implementação em Python puro.
22
+
23
+ ---
24
+
25
+ ## 🚀 Recursos
26
+
27
+ - **Performance Extrema**: Algoritmos matemáticos e *parsing* de strings otimizados usando iterators do Rust.
28
+ - **Novo Padrão RFB**: Suporte nativo ao cálculo de DV (Dígito Verificador) do CNPJ utilizando a tabela ASCII, aceitando tanto os CNPJs antigos (somente números) quanto o novo formato alfanumérico.
29
+ - **Integração PyO3**: A biblioteca é exportada como um C-Extension (`cdylib`), funcionando como um pacote Python comum sem necessidade de configurações complexas por parte de quem a utiliza.
30
+ - **Fallback em Python**: Inclui a mesma implementação em Python puro para casos de teste, comparação ou ambientes restritos.
31
+
32
+ ---
33
+
34
+ ## 📦 Instalação
35
+
36
+ Você pode instalar o pacote diretamente via `pip`:
37
+
38
+ ```bash
39
+ pip install rsfn4py
40
+ ```
41
+
42
+ *(O pacote já distribui wheels pré-compilados para Linux, macOS e Windows nas versões mais recentes do Python).*
43
+
44
+ ---
45
+
46
+ ## 💻 Como Usar
47
+
48
+ O uso é idêntico a qualquer outra biblioteca Python. A função de validação automaticamente limpa a string (removendo pontos, barras e traços) e faz a validação matemática.
49
+
50
+ ```python
51
+ from rust_services_for_python import validate_cnpj_rust, validate_cnpj_python
52
+
53
+ cnpj_valido = "12.345.678/0001-95"
54
+ novo_cnpj_alfanumerico = "12ABC34501DE35"
55
+ cnpj_invalido = "11.111.111/1111-11"
56
+
57
+ # Validação ultra-rápida em Rust (Recomendado para produção)
58
+ print(validate_cnpj_rust(cnpj_valido)) # Saída: True
59
+ print(validate_cnpj_rust(novo_cnpj_alfanumerico)) # Saída: True
60
+ print(validate_cnpj_rust(cnpj_invalido)) # Saída: False
61
+
62
+ # Implementação em Python puro (Para comparação ou fallback)
63
+ print(validate_cnpj_python(cnpj_valido)) # Saída: True
64
+ ```
65
+
66
+ ---
67
+
68
+ ## ⚡ Benchmark
69
+
70
+ Em testes rodando lotes de **100.000 validações** mistas (CNPJs formatados, não formatados e alfanuméricos), a extensão em Rust apresentou uma eficiência drástica no ecossistema CPython:
71
+
72
+ | Linguagem | Tempo de Execução | Validações por Segundo |
73
+ | :--- | :--- | :--- |
74
+ | **Python Puro** | ~ 0.475s | ~ 210.000 req/s |
75
+ | **Rust (PyO3)** | **~ 0.019s** | **~ 5.250.000 req/s** |
76
+
77
+ ---
78
+
79
+ ## 🛠️ Setup Local e Desenvolvimento
80
+
81
+ Se você deseja clonar o repositório para contribuir ou adicionar novos serviços em Rust, siga o passo a passo abaixo.
82
+
83
+ ### Pré-requisitos
84
+ - [Rust & Cargo](https://rustup.rs/) (Instalador `rustup`)
85
+ - Python 3.8+
86
+
87
+ ### 1. Preparando o Ambiente
88
+
89
+ Clone o repositório e crie um ambiente virtual (venv):
90
+
91
+ ```bash
92
+ git clone https://github.com/seu-usuario/rust-services-for-python.git
93
+ cd rust-services-for-python
94
+
95
+ python -m venv .venv
96
+ source .venv/bin/activate # No Windows use: .venv\Scripts\activate
97
+ ```
98
+
99
+ ### 2. Instalando Dependências de Build
100
+
101
+ Utilizamos o **Maturin** como *build system* para compilar o código Rust e linká-lo ao Python.
102
+
103
+ ```bash
104
+ pip install -U pip pytest maturin
105
+ ```
106
+
107
+ ### 3. Compilando o Código Rust Localmente
108
+
109
+ Para compilar o módulo C-Extension de forma transparente e já instalá-lo no seu `.venv`, basta rodar:
110
+
111
+ ```bash
112
+ maturin develop --release
113
+ ```
114
+ *O parâmetro `--release` aplica as otimizações completas do compilador Rust. Se omitido, a compilação será mais rápida, porém a execução será mais lenta (modo debug).*
115
+
116
+ ### 4. Executando os Testes
117
+
118
+ Com os bindings instalados localmente, execute o `pytest` para validar o comportamento do módulo nativo contra os casos de teste:
119
+
120
+ ```bash
121
+ pytest -v tests/
122
+ ```
123
+
124
+ ---
125
+
126
+ ## 📄 Licença
127
+
128
+ Este projeto está sob a licença MIT. Sinta-se livre para usá-lo, modificá-lo e distribuí-lo. Veja o arquivo `LICENSE` para mais detalhes.
@@ -0,0 +1,116 @@
1
+ # 🦀🐍 Rust Functions for Python (rsfn4py)
2
+
3
+ ![CI/CD Tests](https://github.com/seu-usuario/rust-services-for-python/actions/workflows/test.yml/badge.svg)
4
+ ![Release](https://github.com/seu-usuario/rust-services-for-python/actions/workflows/release.yml/badge.svg)
5
+ ![Python Versions](https://img.shields.io/pypi/pyversions/rust-services-for-python)
6
+
7
+ Uma coleção de módulos de alta performance escritos em **Rust** para serem consumidos nativamente em projetos **Python**, focando em processamento rápido e baixo consumo de memória.
8
+
9
+ O primeiro módulo desta biblioteca traz a validação do **Novo CNPJ Alfanumérico** (IN RFB 2.119/2022, válido a partir de julho de 2026), processado em Rust com um ganho de performance de aproximadamente **25x** em comparação à implementação em Python puro.
10
+
11
+ ---
12
+
13
+ ## 🚀 Recursos
14
+
15
+ - **Performance Extrema**: Algoritmos matemáticos e *parsing* de strings otimizados usando iterators do Rust.
16
+ - **Novo Padrão RFB**: Suporte nativo ao cálculo de DV (Dígito Verificador) do CNPJ utilizando a tabela ASCII, aceitando tanto os CNPJs antigos (somente números) quanto o novo formato alfanumérico.
17
+ - **Integração PyO3**: A biblioteca é exportada como um C-Extension (`cdylib`), funcionando como um pacote Python comum sem necessidade de configurações complexas por parte de quem a utiliza.
18
+ - **Fallback em Python**: Inclui a mesma implementação em Python puro para casos de teste, comparação ou ambientes restritos.
19
+
20
+ ---
21
+
22
+ ## 📦 Instalação
23
+
24
+ Você pode instalar o pacote diretamente via `pip`:
25
+
26
+ ```bash
27
+ pip install rsfn4py
28
+ ```
29
+
30
+ *(O pacote já distribui wheels pré-compilados para Linux, macOS e Windows nas versões mais recentes do Python).*
31
+
32
+ ---
33
+
34
+ ## 💻 Como Usar
35
+
36
+ O uso é idêntico a qualquer outra biblioteca Python. A função de validação automaticamente limpa a string (removendo pontos, barras e traços) e faz a validação matemática.
37
+
38
+ ```python
39
+ from rust_services_for_python import validate_cnpj_rust, validate_cnpj_python
40
+
41
+ cnpj_valido = "12.345.678/0001-95"
42
+ novo_cnpj_alfanumerico = "12ABC34501DE35"
43
+ cnpj_invalido = "11.111.111/1111-11"
44
+
45
+ # Validação ultra-rápida em Rust (Recomendado para produção)
46
+ print(validate_cnpj_rust(cnpj_valido)) # Saída: True
47
+ print(validate_cnpj_rust(novo_cnpj_alfanumerico)) # Saída: True
48
+ print(validate_cnpj_rust(cnpj_invalido)) # Saída: False
49
+
50
+ # Implementação em Python puro (Para comparação ou fallback)
51
+ print(validate_cnpj_python(cnpj_valido)) # Saída: True
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚡ Benchmark
57
+
58
+ Em testes rodando lotes de **100.000 validações** mistas (CNPJs formatados, não formatados e alfanuméricos), a extensão em Rust apresentou uma eficiência drástica no ecossistema CPython:
59
+
60
+ | Linguagem | Tempo de Execução | Validações por Segundo |
61
+ | :--- | :--- | :--- |
62
+ | **Python Puro** | ~ 0.475s | ~ 210.000 req/s |
63
+ | **Rust (PyO3)** | **~ 0.019s** | **~ 5.250.000 req/s** |
64
+
65
+ ---
66
+
67
+ ## 🛠️ Setup Local e Desenvolvimento
68
+
69
+ Se você deseja clonar o repositório para contribuir ou adicionar novos serviços em Rust, siga o passo a passo abaixo.
70
+
71
+ ### Pré-requisitos
72
+ - [Rust & Cargo](https://rustup.rs/) (Instalador `rustup`)
73
+ - Python 3.8+
74
+
75
+ ### 1. Preparando o Ambiente
76
+
77
+ Clone o repositório e crie um ambiente virtual (venv):
78
+
79
+ ```bash
80
+ git clone https://github.com/seu-usuario/rust-services-for-python.git
81
+ cd rust-services-for-python
82
+
83
+ python -m venv .venv
84
+ source .venv/bin/activate # No Windows use: .venv\Scripts\activate
85
+ ```
86
+
87
+ ### 2. Instalando Dependências de Build
88
+
89
+ Utilizamos o **Maturin** como *build system* para compilar o código Rust e linká-lo ao Python.
90
+
91
+ ```bash
92
+ pip install -U pip pytest maturin
93
+ ```
94
+
95
+ ### 3. Compilando o Código Rust Localmente
96
+
97
+ Para compilar o módulo C-Extension de forma transparente e já instalá-lo no seu `.venv`, basta rodar:
98
+
99
+ ```bash
100
+ maturin develop --release
101
+ ```
102
+ *O parâmetro `--release` aplica as otimizações completas do compilador Rust. Se omitido, a compilação será mais rápida, porém a execução será mais lenta (modo debug).*
103
+
104
+ ### 4. Executando os Testes
105
+
106
+ Com os bindings instalados localmente, execute o `pytest` para validar o comportamento do módulo nativo contra os casos de teste:
107
+
108
+ ```bash
109
+ pytest -v tests/
110
+ ```
111
+
112
+ ---
113
+
114
+ ## 📄 Licença
115
+
116
+ Este projeto está sob a licença MIT. Sinta-se livre para usá-lo, modificá-lo e distribuí-lo. Veja o arquivo `LICENSE` para mais detalhes.
rsfn4py-0.1.0/example ADDED
Binary file
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["maturin>=1.4,<2.0"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "rsfn4py"
7
+ description = "High-performance Rust modules for Python applications."
8
+ readme = "README.md"
9
+ requires-python = ">=3.8"
10
+ classifiers = [
11
+ "Programming Language :: Rust",
12
+ "Programming Language :: Python :: Implementation :: CPython",
13
+ "Programming Language :: Python :: Implementation :: PyPy",
14
+ ]
15
+ # Permite ao Maturin pegar as informações abaixo do Cargo.toml para não repetir
16
+ dynamic = ["version", "authors"]
17
+
18
+ [tool.maturin]
19
+ # Dizemos ao Maturin onde estão os arquivos Python puro caso deseje misturar o código
20
+ python-source = "python"
21
+ # Especifica como os binários devem ser empacotados para subir no repositório PyPI
22
+ features = ["pyo3/extension-module"]
@@ -0,0 +1,4 @@
1
+ from .rsfn4py import validate_cnpj_rust
2
+ from .validations import validate_cnpj_python
3
+
4
+ __all__ = ["validate_cnpj_rust", "validate_cnpj_python"]
@@ -0,0 +1,27 @@
1
+ import re
2
+
3
+ def validate_cnpj_python(cnpj: str) -> bool:
4
+ """Valida CNPJ (numérico ou alfanumérico) usando a implementação em Python puro."""
5
+ cnpj = re.sub(r'[^a-zA-Z0-9]', '', cnpj).upper()
6
+ if len(cnpj) != 14:
7
+ return False
8
+
9
+ def get_ascii_val(char):
10
+ return ord(char) - 48
11
+
12
+ if len(set(cnpj)) == 1:
13
+ return False
14
+
15
+ weights1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
16
+ sum1 = sum(get_ascii_val(cnpj[i]) * weights1[i] for i in range(12))
17
+ mod1 = sum1 % 11
18
+ dv1 = 0 if mod1 < 2 else 11 - mod1
19
+ if get_ascii_val(cnpj[12]) != dv1:
20
+ return False
21
+
22
+ weights2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
23
+ sum2 = sum(get_ascii_val(cnpj[i]) * weights2[i] for i in range(13))
24
+ mod2 = sum2 % 11
25
+ dv2 = 0 if mod2 < 2 else 11 - mod2
26
+
27
+ return get_ascii_val(cnpj[13]) == dv2
@@ -0,0 +1,50 @@
1
+ use pyo3::prelude::*;
2
+
3
+ #[pyfunction]
4
+ fn validate_cnpj_rust(cnpj: &str) -> bool {
5
+ let cleaned: Vec<char> = cnpj.chars()
6
+ .filter(|c| c.is_ascii_alphanumeric())
7
+ .map(|c| c.to_ascii_uppercase())
8
+ .collect();
9
+
10
+ if cleaned.len() != 14 {
11
+ return false;
12
+ }
13
+
14
+ // Rejeita caso todos os caracteres sejam iguais
15
+ if cleaned.iter().all(|&c| c == cleaned[0]) {
16
+ return false;
17
+ }
18
+
19
+ let get_val = |c: char| -> i32 { c as i32 - 48 };
20
+
21
+ // Cálculo do primeiro dígito (DV1)
22
+ let weights1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
23
+ let mut sum1 = 0;
24
+ for i in 0..12 {
25
+ sum1 += get_val(cleaned[i]) * weights1[i];
26
+ }
27
+ let mod1 = sum1 % 11;
28
+ let dv1 = if mod1 < 2 { 0 } else { 11 - mod1 };
29
+
30
+ if get_val(cleaned[12]) != dv1 {
31
+ return false;
32
+ }
33
+
34
+ // Cálculo do segundo dígito (DV2)
35
+ let weights2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
36
+ let mut sum2 = 0;
37
+ for i in 0..13 {
38
+ sum2 += get_val(cleaned[i]) * weights2[i];
39
+ }
40
+ let mod2 = sum2 % 11;
41
+ let dv2 = if mod2 < 2 { 0 } else { 11 - mod2 };
42
+
43
+ get_val(cleaned[13]) == dv2
44
+ }
45
+
46
+ #[pymodule]
47
+ fn rsfn4py(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
48
+ m.add_function(wrap_pyfunction!(validate_cnpj_rust, m)?)?;
49
+ Ok(())
50
+ }
@@ -0,0 +1,3 @@
1
+ fn main() {
2
+ println!("Hello, world!");
3
+ }
@@ -0,0 +1,28 @@
1
+ import pytest
2
+ from rsfn4py import validate_cnpj_rust, validate_cnpj_python
3
+
4
+ # Casos de testes comuns:
5
+ # - CNPJ numérico válido
6
+ # - Novo CNPJ alfanumérico válido
7
+ # - CNPJ inválido por Dígito Verificador (DV) errado
8
+ # - CNPJ inválido por repetição (ex: 11.111.111/1111-11)
9
+ # - String aleatória sem sentido
10
+ test_cases = [
11
+ ("12.345.678/0001-95", True), # Numérico válido genérico formatado
12
+ ("12345678000195", True), # Numérico válido sem formatação
13
+ ("12ABC34501DE35", True), # Alfanumérico (IN RFB 2.119/2022) simulado válido
14
+ ("12.345.678/0001-00", False), # DV Incorreto
15
+ ("11111111111111", False), # Rejeição de repetição de caracteres
16
+ ("12.ABC.678/000X-95", False), # Dígito final x não numérico no validador
17
+ ("NONSENSE", False) # Totalmente inválido e curto
18
+ ]
19
+
20
+ @pytest.mark.parametrize("cnpj, expected", test_cases)
21
+ def test_rust_validation(cnpj, expected):
22
+ """Testa a biblioteca compilada no módulo nativo do PyO3."""
23
+ assert validate_cnpj_rust(cnpj) == expected
24
+
25
+ @pytest.mark.parametrize("cnpj, expected", test_cases)
26
+ def test_python_validation(cnpj, expected):
27
+ """Testa o fallback em Python puro."""
28
+ assert validate_cnpj_python(cnpj) == expected