mirror of
https://github.com/vinezombie/vinezombie.git
synced 2026-01-24 23:17:34 +00:00
Burn the world
This commit marks the start of a major rewrite and shift in goals. While there is a significant amount of prior design experimentation leading up to this point, the codebase essentially gets rewritten here.
This commit is contained in:
31
.build.yml
Normal file
31
.build.yml
Normal file
@@ -0,0 +1,31 @@
|
||||
image: archlinux # We need rustup, and Arch happily packages it.
|
||||
packages:
|
||||
- rustup
|
||||
sources:
|
||||
- https://git.sr.ht/~daemoness/vinezombie
|
||||
environment:
|
||||
CARGO_TERM_COLOR: always
|
||||
tasks:
|
||||
- setup: |
|
||||
rustup install stable
|
||||
- build-min: |
|
||||
cd vinezombie
|
||||
cargo build --no-default-features --message-format short
|
||||
- build-default: |
|
||||
cd vinezombie
|
||||
cargo build --message-format short
|
||||
- build-max: |
|
||||
cd vinezombie
|
||||
cargo build --all-features --message-format short
|
||||
- examples: |
|
||||
cd vinezombie
|
||||
cargo build --all-features --examples --message-format short
|
||||
- test: |
|
||||
cd vinezombie
|
||||
cargo test --all-features
|
||||
- lint: |
|
||||
cd vinezombie
|
||||
cargo clippy --all-features
|
||||
- fmt: |
|
||||
cd vinezombie
|
||||
cargo fmt --check
|
||||
10
.editorconfig
Normal file
10
.editorconfig
Normal file
@@ -0,0 +1,10 @@
|
||||
[*]
|
||||
charset = utf-8
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
max_line_length = 78
|
||||
|
||||
[*.rs]
|
||||
indent_size = 4
|
||||
max_line_length = 100
|
||||
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
/img
|
||||
6
.rustfmt.toml
Normal file
6
.rustfmt.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
edition = "2021" # Included to simplify non-cargo fmt runs.
|
||||
max_width = 100
|
||||
use_small_heuristics = "Max"
|
||||
use_try_shorthand = true
|
||||
wrap_comments = true
|
||||
use_field_init_shorthand = true
|
||||
675
COPYING
Normal file
675
COPYING
Normal file
@@ -0,0 +1,675 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
36
Cargo.toml
Normal file
36
Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "vinezombie"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
license = "GPL-3.0-only"
|
||||
description = "A modular IRCv3 client library"
|
||||
homepage = "https://sr.ht/~daemoness/vinezombie/"
|
||||
repository = "https://git.sr.ht/~daemoness/vinezombie"
|
||||
readme = "README.md"
|
||||
keywords = ["irc", "ircv3"]
|
||||
categories = ["network-programming", "parser-implementations"]
|
||||
|
||||
# https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
base64 = { version = "0.13.1", optional = true }
|
||||
log = { version = "0.4.17", optional = true }
|
||||
rustls = { version = "0.20.7", optional = true }
|
||||
rustls-native-certs = { version = "0.6.2", optional = true }
|
||||
whoami = { version = "1.3.0", optional = true }
|
||||
|
||||
[dependencies.graveseed]
|
||||
git = "https://git.sr.ht/~daemoness/graveseed"
|
||||
rev = "536d6201bbee483e3cd61ff91c6ec7bc2c2a04f6"
|
||||
optional = true
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.9.3"
|
||||
|
||||
[features]
|
||||
tls = ["dep:rustls", "dep:rustls-native-certs"]
|
||||
default = ["graveseed", "log", "base64"]
|
||||
|
||||
# [[example]]
|
||||
# name = "hello-libera"
|
||||
50
README.md
Normal file
50
README.md
Normal file
@@ -0,0 +1,50 @@
|
||||
*vinezombie is slowly stabilizing. Please hold.*
|
||||
|
||||
# vinezombie
|
||||
|
||||
**An abstracting IRCv3 client library in Rust.**
|
||||
|
||||
[](https://builds.sr.ht/~daemoness/vinezombie/?)
|
||||
[](https://web.libera.chat/gamja/?channel=#vinezombie)
|
||||
|
||||
`vinezombie` is an opinionated Rust library for writing IRCv3 utilities,
|
||||
namely IRC clients, bots, and plugins for said clients and bots.
|
||||
It is designed to provide thin abstractions over the underlying protocol
|
||||
while allowing the mapping between them be highly-configurable at runtime.
|
||||
The goal is to allow client logic to be written as agnostically as reasonably
|
||||
possible to the quirks of whatever server is being connected to.
|
||||
|
||||
## Optional Features
|
||||
|
||||
`vinezombie` aims to have minimal mandatory dependencies.
|
||||
The default feature set is designed to be enough to write IRC bots,
|
||||
and includes the following:
|
||||
|
||||
* `graveseed`: Adds [graveseed](https://sr.ht/~daemoness/graveseed/)
|
||||
integrations, allowing it to be used for I/O and message handling.
|
||||
* `base64`: Adds base64 encoding/decoding. Required for SASL.
|
||||
* `log`: Enables utilities for logging using `log`.
|
||||
|
||||
The following optional features are also available:
|
||||
|
||||
* `whoami`: Uses system acocunt info for `crate::init::Register::default()`.
|
||||
|
||||
## License
|
||||
|
||||
`vinezombie` is licensed under the GNU GPL v3 (only).
|
||||
Disclosing the source code of bots written using `vinezombie` to
|
||||
end users over IRC is also strongly encouraged, but not required.
|
||||
|
||||
## Discussion
|
||||
|
||||
The author somtimes rambles about code design in #vinezombie on
|
||||
[Libera.Chat](ircs://irc.libera.chat/#vinezombie).
|
||||
A link to a webchat is available at the top by clicking the libera.chat badge.
|
||||
|
||||
---
|
||||
|
||||
```
|
||||
<jess> why vinezombie lmao
|
||||
<TheDaemoness> Because. Grapevines. Undead chat protocols.
|
||||
<jess> oh my god
|
||||
```
|
||||
16
dia/strings.d2
Normal file
16
dia/strings.d2
Normal file
@@ -0,0 +1,16 @@
|
||||
Bytes.shape: class
|
||||
Line.shape: class
|
||||
Word.shape: class
|
||||
Arg.shape: class
|
||||
User.shape: class
|
||||
Nick.shape: class
|
||||
Kind.shape: class
|
||||
TagKey.shape: class
|
||||
|
||||
Bytes <- Line: "Non-empty; no CR, LF, or NUL"
|
||||
Line <- Word: No spaces
|
||||
Word <- Arg: "No leading :"
|
||||
Arg <- Nick: "No ! or @"
|
||||
Arg <- User: "No @ or %"
|
||||
Arg <- Kind: "ASCII uppercase"
|
||||
Word <- TagKey: "No +, =, /, or ;"
|
||||
108
doc/strings.d2.svg
Normal file
108
doc/strings.d2.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 26 KiB |
158
src/handlers.rs
Normal file
158
src/handlers.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
//! Common handlers for writing IRC applications.
|
||||
|
||||
pub mod init;
|
||||
|
||||
use std::{collections::VecDeque, iter::FusedIterator, time::Duration};
|
||||
|
||||
use crate::msg::{
|
||||
data::Ping, ClientMsg, DefaultMsgWriter, MsgWriter, NewMsgWriter, RawClientMsg, RawServerMsg,
|
||||
};
|
||||
use graveseed::{
|
||||
handler::{
|
||||
inline::{InlineHandler, RateLimited},
|
||||
Action, Handler,
|
||||
},
|
||||
time::rate_limiters::LeakyBucket,
|
||||
};
|
||||
|
||||
/// A collection of [`MsgWriter`]s usable as an iterator or a [`Handler`].
|
||||
#[derive(Default)]
|
||||
pub struct Send<'a>(VecDeque<Box<dyn MsgWriter<'a> + 'a>>);
|
||||
|
||||
impl<'a> Send<'a> {
|
||||
/// Creates a new empty message burst.
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Adds the provided [`ClientMsg`] to the end of this burst.
|
||||
///
|
||||
/// The data of the message must have a default message writer
|
||||
/// whose `Options` implement `Default`.
|
||||
pub fn with_msg<W>(self, what: ClientMsg<'a, W>) -> Self
|
||||
where
|
||||
W: DefaultMsgWriter<'a> + 'a,
|
||||
<<W as DefaultMsgWriter<'a>>::Writer as NewMsgWriter<'a>>::Options: Default,
|
||||
{
|
||||
self.with_writer(W::Writer::new_msg_writer(what, Default::default()))
|
||||
}
|
||||
/// Adds the provided [`ClientMsg`] to the end of this burst using `opts`
|
||||
/// for writer options.
|
||||
///
|
||||
/// The data of the message must have a default message writer.
|
||||
pub fn with_msg_and_opts<W>(
|
||||
self,
|
||||
what: ClientMsg<'a, W>,
|
||||
opts: <<W as DefaultMsgWriter<'a>>::Writer as NewMsgWriter<'a>>::Options,
|
||||
) -> Self
|
||||
where
|
||||
W: DefaultMsgWriter<'a> + 'a,
|
||||
{
|
||||
self.with_writer(W::Writer::new_msg_writer(what, opts))
|
||||
}
|
||||
|
||||
/// Adds the provided boxed [`MsgWriter`] to the end of this burst.
|
||||
pub fn with_writer(mut self, what: Box<dyn MsgWriter<'a> + 'a>) -> Self {
|
||||
self.0.push_back(what);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Default> Handler<T, RawServerMsg<'a>, RawClientMsg<'static>> for Send<'static> {
|
||||
fn handle(
|
||||
self: Box<Self>,
|
||||
_: Option<&RawServerMsg<'a>>,
|
||||
) -> Action<T, RawServerMsg<'a>, RawClientMsg<'static>> {
|
||||
Action::done(T::default()).with_send(self)
|
||||
}
|
||||
|
||||
fn timeout(&self) -> Option<std::time::Duration> {
|
||||
Some(std::time::Duration::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Send<'a> {
|
||||
type Item = RawClientMsg<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let back = self.0.pop_front()?;
|
||||
let (msg, cont) = back.write_msg();
|
||||
if let Some(cont) = cont {
|
||||
self.0.push_front(cont);
|
||||
}
|
||||
Some(msg)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.0.len(), self.0.is_empty().then_some(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a rate-limiting inline handler.
|
||||
///
|
||||
/// RFC 1459 recommends a burst of up to 5 messages,
|
||||
/// followed by one message every 2 seconds.
|
||||
/// By specifying `None` for both arguments,
|
||||
/// these recommendations will be used.
|
||||
pub fn rate_limited_queue<S>(
|
||||
rate: Option<Duration>,
|
||||
burst: Option<u32>,
|
||||
) -> RateLimited<VecDeque<S>, LeakyBucket> {
|
||||
let rate = rate.unwrap_or_else(|| Duration::from_secs(2));
|
||||
let max = rate * burst.unwrap_or(5);
|
||||
RateLimited::new::<S>(LeakyBucket::new(rate, max))
|
||||
}
|
||||
|
||||
/// Inline handler that logs messages at the debug level.
|
||||
///
|
||||
/// This should NOT be used in production,
|
||||
/// as it can and will log messages containing sensitive information unredacted,
|
||||
/// such as AUTHENTICATE messages.
|
||||
#[cfg(feature = "log")]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct DebugLog;
|
||||
|
||||
#[cfg(feature = "log")]
|
||||
impl<'a> InlineHandler<RawServerMsg<'a>, RawClientMsg<'static>> for DebugLog {
|
||||
fn handle_recv(&mut self, msg: Option<RawServerMsg<'a>>) -> Option<RawServerMsg<'a>> {
|
||||
if let Some(ref msg) = msg {
|
||||
log::debug!("recv: {msg}");
|
||||
}
|
||||
msg
|
||||
}
|
||||
|
||||
fn handle_send(
|
||||
&mut self,
|
||||
msg: Result<RawClientMsg<'static>, graveseed::time::Deadline>,
|
||||
) -> Result<RawClientMsg<'static>, graveseed::time::Deadline> {
|
||||
if let Ok(ref msg) = msg {
|
||||
log::debug!("send: {msg}");
|
||||
}
|
||||
msg
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> FusedIterator for Send<'a> {}
|
||||
|
||||
// Do NOT impl DoubleEndedIterator.
|
||||
|
||||
/// Handler that auto-replies to pings.
|
||||
///
|
||||
/// You almost always want to have this handler in use
|
||||
/// in order to avoid being auto-disconnected.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct AutoPong;
|
||||
|
||||
impl<'a> Handler<(), RawServerMsg<'a>, RawClientMsg<'static>> for AutoPong {
|
||||
fn handle(
|
||||
self: Box<Self>,
|
||||
msg: Option<&RawServerMsg<'a>>,
|
||||
) -> graveseed::handler::Action<(), RawServerMsg<'a>, RawClientMsg<'static>> {
|
||||
let retval = Action::next(self);
|
||||
let Some(msg) = msg.and_then(|m| m.to_parsed::<Ping<'a>>(())) else {
|
||||
return retval;
|
||||
};
|
||||
let reply = ClientMsg::new(msg.data.pong());
|
||||
retval.with_send(Send::new().with_msg(reply))
|
||||
}
|
||||
}
|
||||
233
src/handlers/init.rs
Normal file
233
src/handlers/init.rs
Normal file
@@ -0,0 +1,233 @@
|
||||
//! Handlers for connection registration and state-tracking initialization.
|
||||
|
||||
use crate::{
|
||||
init::nick::NickGen,
|
||||
known::{Cap, Cmd, MaybeKnown, Numeric},
|
||||
msg::{
|
||||
data::{CapClientData, CapServerData, Ping},
|
||||
ClientMsg, RawClientMsg, RawServerMsg,
|
||||
},
|
||||
IoResult, IrcStr, IrcWord,
|
||||
};
|
||||
use graveseed::handler::{Action, Handler, IntoHandler};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
io::ErrorKind,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// [`IntoHandler`] for [`Register`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegisterBuilder<N> {
|
||||
username: IrcWord<'static>,
|
||||
realname: IrcStr<'static>,
|
||||
nick: IrcWord<'static>,
|
||||
fallbacks: N,
|
||||
caps: BTreeSet<IrcWord<'static>>,
|
||||
timeout: Option<Duration>, // TODO: server password, sasl.
|
||||
}
|
||||
|
||||
impl<N> RegisterBuilder<N> {
|
||||
/// Creates a new `RegisterBuilder` from an [`init::Register`][crate::init::Register].
|
||||
///
|
||||
/// Returns `None` if the nick generator returns `None`.
|
||||
/// This should usually be treated as end user error.
|
||||
pub fn from_opts<G: NickGen<Iter = N>, S: crate::sasl::Secret>(
|
||||
opts: crate::init::Register<G, S>,
|
||||
) -> Option<Self> {
|
||||
let new = Self::new(opts.username, opts.realname, opts.nicks)?;
|
||||
// TODO: SASL.
|
||||
Some(new)
|
||||
}
|
||||
/// Creates a new `RegisterBuilder`.
|
||||
///
|
||||
/// Specifies a timeout of 10s by default, which should be considerably longer
|
||||
/// than is necessary for a server to fail rDNS and ident lookup
|
||||
/// under typical conditions.
|
||||
///
|
||||
/// Returns `None` if `nicks.nick_gen()` returns `None`.
|
||||
/// This should usually be treated as end user error.
|
||||
pub fn new(
|
||||
username: impl Into<IrcWord<'static>>,
|
||||
realname: impl Into<IrcStr<'static>>,
|
||||
nicks: impl NickGen<Iter = N>,
|
||||
) -> Option<Self> {
|
||||
let (nick, fallbacks) = nicks.nick_gen()?;
|
||||
Some(RegisterBuilder {
|
||||
username: username.into(),
|
||||
realname: realname.into(),
|
||||
nick,
|
||||
fallbacks,
|
||||
caps: BTreeSet::new(),
|
||||
timeout: Some(Duration::from_secs(10)),
|
||||
})
|
||||
}
|
||||
/// Adds a capability to request in addition to any capabilities implicitly required.
|
||||
pub fn add_cap(&mut self, cap: impl Into<MaybeKnown<'static, Cap>>) -> &mut Self {
|
||||
self.caps.insert(cap.into().into_word());
|
||||
self
|
||||
}
|
||||
/// Sets the timeout.
|
||||
///
|
||||
/// The timeout is the maximum amount of time that may pass between messages
|
||||
/// before the handler simply times out.
|
||||
pub fn set_timeout(&mut self, timeout: Option<Duration>) -> &mut Self {
|
||||
self.timeout = timeout;
|
||||
self
|
||||
}
|
||||
// TODO: SASL.
|
||||
}
|
||||
|
||||
/// Success! Start normal message processing.
|
||||
///
|
||||
/// The included message will always be RPL_WELCOME.
|
||||
pub struct Success<'a> {
|
||||
// TODO: Rich RPL_WELCOME.
|
||||
/// The RPL_WELCOME message.
|
||||
pub welcome: RawServerMsg<'a>,
|
||||
/// The connection state.
|
||||
pub state: crate::state::Connection,
|
||||
}
|
||||
|
||||
/// Handler that performs connection registration.
|
||||
#[derive(Clone)]
|
||||
pub struct Register<N> {
|
||||
needs_cap_end: bool,
|
||||
userinfo: Option<(IrcWord<'static>, IrcStr<'static>)>,
|
||||
nick_fallbacks: N,
|
||||
conn_state: crate::state::Connection,
|
||||
caps: BTreeSet<IrcWord<'static>>,
|
||||
timeout: Option<(Duration, Instant)>, // TODO: server password, sasl
|
||||
}
|
||||
|
||||
impl<N: Iterator<Item = IrcWord<'static>> + 'static> Register<N> {
|
||||
fn handle_msg<'a>(
|
||||
mut self: Box<Self>,
|
||||
msg: &RawServerMsg<'a>,
|
||||
mut send: super::Send<'static>,
|
||||
) -> Action<IoResult<Success<'a>>, RawServerMsg<'a>, RawClientMsg<'static>> {
|
||||
let mut can_cap_end = false;
|
||||
if msg.kind().as_known_into() == Some(Numeric::RplWelcome) {
|
||||
// Handle successful connection.
|
||||
// TODO: Probably abort if SASL is required and didn't happen.
|
||||
let success = Success { welcome: msg.clone(), state: self.conn_state };
|
||||
return Action::ok(success).with_send(send);
|
||||
} else if msg.kind().as_known_into() == Some(Numeric::ErrNicknameinuse) {
|
||||
// Handle the nick being in use.
|
||||
if let Some(new_nick) = self.nick_fallbacks.next() {
|
||||
self.conn_state.nick = new_nick.clone();
|
||||
// TODO: NICK message data type.
|
||||
let mut msg_n = ClientMsg::new_raw(Cmd::Nick);
|
||||
msg_n.data_mut().args.add_word(new_nick);
|
||||
send = send.with_msg(msg_n);
|
||||
} else {
|
||||
return Action::io_err(ErrorKind::AlreadyExists, "all nicknames are in use");
|
||||
}
|
||||
} else if let Some(msg) = msg.to_parsed::<Ping>(()) {
|
||||
// Handle pings.
|
||||
send = send.with_msg(ClientMsg::new(msg.data().pong()))
|
||||
} else if let Some(msg) = msg.to_parsed::<CapServerData>(()) {
|
||||
// Handle CAP messages.
|
||||
let caps = msg.into_parts().1;
|
||||
self.conn_state.update_caps(caps.caps);
|
||||
if caps.is_last {
|
||||
if !self.caps.is_empty() {
|
||||
let req = CapClientData::req(std::mem::take(&mut self.caps)).1;
|
||||
send = send.with_msg(ClientMsg::new(req));
|
||||
} else {
|
||||
// TODO: SASL!!!
|
||||
can_cap_end = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ignore messages that the client doesn't know how to handle
|
||||
// and just let the timeout kill the connection.
|
||||
if can_cap_end && self.needs_cap_end {
|
||||
send = send.with_msg(ClientMsg::new(CapClientData::End));
|
||||
}
|
||||
Action::next(self).with_send(send)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Definitely need macros for these horrific type signatures.
|
||||
|
||||
impl<'a, N: Iterator<Item = IrcWord<'static>> + 'static>
|
||||
Handler<IoResult<Success<'a>>, RawServerMsg<'a>, RawClientMsg<'static>> for Register<N>
|
||||
{
|
||||
fn handle(
|
||||
mut self: Box<Self>,
|
||||
msg: Option<&RawServerMsg<'a>>,
|
||||
) -> Action<IoResult<Success<'a>>, RawServerMsg<'a>, RawClientMsg<'static>> {
|
||||
let send = if let Some((uname, rname)) = std::mem::take(&mut self.userinfo) {
|
||||
self.needs_cap_end = !self.caps.is_empty();
|
||||
register_burst(self.needs_cap_end, uname, rname, self.conn_state.nick.clone())
|
||||
} else {
|
||||
super::Send::default()
|
||||
};
|
||||
// Handle the inbound message or lack thereof.
|
||||
if let Some(msg) = msg {
|
||||
// Update the deadline.
|
||||
if let Some((timeout, deadline)) = &mut self.timeout {
|
||||
*deadline = Instant::now() + *timeout;
|
||||
}
|
||||
return self.handle_msg(msg, send);
|
||||
} else if let Some((_, deadline)) = self.timeout {
|
||||
if deadline < Instant::now() {
|
||||
return Action::io_err(ErrorKind::TimedOut, "connection registration timed out");
|
||||
}
|
||||
}
|
||||
Action::next(self).with_send(send)
|
||||
}
|
||||
|
||||
fn timeout(&self) -> Option<std::time::Duration> {
|
||||
if self.userinfo.is_some() {
|
||||
Some(std::time::Duration::ZERO)
|
||||
} else {
|
||||
self.timeout.map(|(_, i)| i.saturating_duration_since(Instant::now()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, N: Iterator<Item = IrcWord<'static>> + 'static>
|
||||
IntoHandler<IoResult<Success<'a>>, RawServerMsg<'a>, RawClientMsg<'static>>
|
||||
for RegisterBuilder<N>
|
||||
{
|
||||
fn into_handler(
|
||||
self,
|
||||
) -> Box<dyn Handler<IoResult<Success<'a>>, RawServerMsg<'a>, RawClientMsg<'static>>> {
|
||||
Box::new(Register {
|
||||
needs_cap_end: false,
|
||||
userinfo: Some((self.username, self.realname)),
|
||||
conn_state: crate::state::Connection::new(self.nick, None),
|
||||
nick_fallbacks: self.fallbacks,
|
||||
caps: self.caps,
|
||||
timeout: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [`Send`][super::Send] with the initial messages needed to register a user connection.
|
||||
pub fn register_burst(
|
||||
cap: bool,
|
||||
uname: IrcWord<'static>,
|
||||
rname: IrcStr<'static>,
|
||||
nick: IrcWord<'static>,
|
||||
) -> super::Send<'static> {
|
||||
let mut send = super::Send::default();
|
||||
if cap {
|
||||
let msg = ClientMsg::new(CapClientData::Ls);
|
||||
send = send.with_msg(msg);
|
||||
}
|
||||
// TODO: USER message data type.
|
||||
let mut msg_u = ClientMsg::new_raw(Cmd::User);
|
||||
let args = &mut msg_u.data_mut().args;
|
||||
args.add_word(uname);
|
||||
// Some IRCds still rely on 8 to set +i by default.
|
||||
args.add_word("8");
|
||||
args.add_word("*");
|
||||
args.add(rname);
|
||||
// TODO: NICK message data type.
|
||||
let mut msg_n = ClientMsg::new_raw(Cmd::Nick);
|
||||
msg_n.data_mut().args.add_word(nick);
|
||||
send.with_msg(msg_u).with_msg(msg_n)
|
||||
}
|
||||
6
src/init.rs
Normal file
6
src/init.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
//! Data types for connection initialization.
|
||||
|
||||
pub mod nick;
|
||||
mod opts;
|
||||
|
||||
pub use opts::*;
|
||||
126
src/init/nick.rs
Normal file
126
src/init/nick.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Nickname generation and fallback strategies.
|
||||
|
||||
use crate::IrcWord;
|
||||
use std::error::Error;
|
||||
|
||||
/// Error indicating that a nickname generator cannot generate any more nicknames.
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
pub struct EndOfNicks;
|
||||
|
||||
impl std::fmt::Display for EndOfNicks {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "no more nicknames")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for EndOfNicks {}
|
||||
|
||||
/// Types that can be used as nickname generators.
|
||||
pub trait NickGen {
|
||||
/// The type of the fallback iterator.
|
||||
type Iter: Iterator<Item = IrcWord<'static>>;
|
||||
/// Creates both the first nickname and an iterator of fallback nicknames.
|
||||
fn nick_gen(self) -> Option<(IrcWord<'static>, Self::Iter)>;
|
||||
}
|
||||
|
||||
impl<T: IntoIterator<Item = IrcWord<'static>>> NickGen for T {
|
||||
type Iter = T::IntoIter;
|
||||
|
||||
fn nick_gen(self) -> Option<(IrcWord<'static>, Self::Iter)> {
|
||||
let mut iter = self.into_iter();
|
||||
let first = iter.next()?;
|
||||
Some((first, iter))
|
||||
}
|
||||
}
|
||||
|
||||
impl NickGen for IrcWord<'static> {
|
||||
type Iter = std::iter::Empty<IrcWord<'static>>;
|
||||
|
||||
fn nick_gen(self) -> Option<(IrcWord<'static>, Self::Iter)> {
|
||||
Some((self, std::iter::empty()))
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: More nick generators!
|
||||
// TODO: Trait for nick generators that can be seeded with a starting nick!
|
||||
|
||||
/// Suffixes a nick with several low-quality pesudorandom digits.
|
||||
///
|
||||
/// This nick generator uses a 32-bit
|
||||
/// [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator).
|
||||
/// It uses the 3 most significant bits of each run to generate octal digits,
|
||||
/// which it appends to the provided nick.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SuffixRandom {
|
||||
nick: String,
|
||||
seed: u32,
|
||||
digits: u8,
|
||||
}
|
||||
|
||||
impl SuffixRandom {
|
||||
/// Creates a new nick generator seeded from the current time.
|
||||
///
|
||||
/// The seed is derived from the current UNIX timestamp at high resolutions where possible.
|
||||
pub fn new<'a>(nick: impl Into<IrcWord<'a>>, digits: u8) -> SuffixRandom {
|
||||
use std::time;
|
||||
let seed = if let Ok(dur) = time::SystemTime::now().duration_since(time::UNIX_EPOCH) {
|
||||
(dur.as_millis() as u32) ^ (dur.as_nanos() as u32)
|
||||
} else {
|
||||
// Something's wrong with the wall clock.
|
||||
// Hope the current stack frame's address is random enough instead.
|
||||
std::ptr::addr_of!(digits) as u32
|
||||
};
|
||||
Self::with_seed(nick, digits, seed)
|
||||
}
|
||||
/// Creates a new nick generator with the specified seed.
|
||||
pub fn with_seed<'a>(nick: impl Into<IrcWord<'a>>, digits: u8, seed: u32) -> SuffixRandom {
|
||||
let digits_usize: usize = digits.into();
|
||||
let prefix = nick.into();
|
||||
let mut nick = String::with_capacity(prefix.len_bytes() + digits_usize);
|
||||
nick.push_str(prefix.as_ref());
|
||||
nick.extend(std::iter::repeat('0').take(digits_usize));
|
||||
let mut retval = SuffixRandom { nick, seed, digits };
|
||||
retval.step();
|
||||
retval
|
||||
}
|
||||
fn lcg(int: u32) -> u32 {
|
||||
// LCG constants taken from Numerical Recipes.
|
||||
int.wrapping_mul(1664525).wrapping_add(1013904223)
|
||||
}
|
||||
fn step(&mut self) {
|
||||
let iter = unsafe { self.nick.as_bytes_mut().iter_mut().rev().take(self.digits.into()) };
|
||||
for digit in iter {
|
||||
self.seed = SuffixRandom::lcg(self.seed);
|
||||
*digit = b'0' + (self.seed >> 29) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for SuffixRandom {
|
||||
type Item = IrcWord<'static>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let retval = unsafe { IrcWord::new_unchecked(self.nick.as_str()).owning() };
|
||||
self.step();
|
||||
Some(retval)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
pub fn gen_crude() {
|
||||
use super::{NickGen, SuffixRandom};
|
||||
let gen = SuffixRandom::with_seed("Foo", 9, 1337);
|
||||
let mut prev: u32 = 9;
|
||||
let (mut nick, mut rest) = gen.nick_gen().unwrap();
|
||||
for _ in 0..16 {
|
||||
let num = nick.strip_prefix("Foo").unwrap();
|
||||
assert_eq!(num.len(), 9);
|
||||
let num: u32 = num.parse().unwrap();
|
||||
assert_ne!(num, prev);
|
||||
prev = num;
|
||||
nick = rest.next().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
63
src/init/opts.rs
Normal file
63
src/init/opts.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use crate::{
|
||||
sasl::{External, Plain},
|
||||
IrcStr, IrcWord,
|
||||
};
|
||||
|
||||
/// Enum of included SASL mechanisms and options for them.
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum AnySasl<S> {
|
||||
External(External),
|
||||
Plain(Plain<S>),
|
||||
}
|
||||
|
||||
impl<S> From<External> for AnySasl<S> {
|
||||
fn from(value: External) -> Self {
|
||||
AnySasl::External(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<Plain<S>> for AnySasl<S> {
|
||||
fn from(value: Plain<S>) -> Self {
|
||||
AnySasl::Plain(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Connection registration options.
|
||||
///
|
||||
/// These are used to create the messages sent during the initial connection registration phase,
|
||||
/// such as USER and NICK.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Register<N, S> {
|
||||
/// The nickname generator.
|
||||
pub nicks: N,
|
||||
/// The username, historically one's local account name.
|
||||
pub username: IrcWord<'static>,
|
||||
/// The realname, also sometimes known as the gecos.
|
||||
pub realname: IrcStr<'static>,
|
||||
/// A list of SASL authenticators.
|
||||
pub sasl: Vec<AnySasl<S>>,
|
||||
}
|
||||
|
||||
impl<N, S> Register<N, S> {
|
||||
/// Creates a new `Register` using the provided nickname generator.
|
||||
pub fn new(nicks: N) -> Self {
|
||||
let username: IrcWord<'static> = unsafe { IrcWord::new_unchecked("user") };
|
||||
#[cfg(feature = "whoami")]
|
||||
let username: IrcWord<'static> = IrcWord::new(whoami::username()).unwrap_or(username);
|
||||
let realname: IrcStr<'static> = "???".into();
|
||||
#[cfg(feature = "whoami")]
|
||||
let realname: IrcStr<'static> = whoami::realname().try_into().unwrap_or(realname);
|
||||
Register { nicks, username, realname, sasl: Vec::new() }
|
||||
}
|
||||
/// Adds a SASL authenticator.
|
||||
pub fn add_sasl(&mut self, sasl: impl Into<AnySasl<S>>) {
|
||||
self.sasl.push(sasl.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<N: Default, S> Default for Register<N, S> {
|
||||
fn default() -> Self {
|
||||
Register::<N, S>::new(Default::default())
|
||||
}
|
||||
}
|
||||
60
src/io.rs
Normal file
60
src/io.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
//! [`Translator`][graveseed::io::Translator] impls and other connection-related utilities.
|
||||
|
||||
use std::num::NonZeroUsize;
|
||||
|
||||
use graveseed::io::Translator;
|
||||
|
||||
use crate::msg::{MsgParseError, RawClientMsg, RawServerMsg};
|
||||
|
||||
/// [`Translator`] for the client side of an IRC connection.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct ClientTranslator;
|
||||
|
||||
// 512 IRCv2 bytes + 8192 tag bytes.
|
||||
const MAX_RECV_LEN: usize = 8704;
|
||||
|
||||
impl Translator for ClientTranslator {
|
||||
// Power of two, almost double the largest IRCv3 message.
|
||||
const RECV_HINT: usize = 16384;
|
||||
|
||||
// 512 bytes of message content and 512 bytes of tag content.
|
||||
// Should be enough in most cases.
|
||||
const SEND_HINT: usize = 1024;
|
||||
|
||||
type RecvMsg<'a> = RawServerMsg<'a>;
|
||||
|
||||
type SendMsg<'a> = RawClientMsg<'a>;
|
||||
|
||||
fn write_msg<T: std::io::Write>(
|
||||
&mut self,
|
||||
buf: &mut T,
|
||||
msg: &Self::SendMsg<'_>,
|
||||
) -> std::io::Result<()> {
|
||||
write!(buf, "{msg}\r\n")
|
||||
}
|
||||
|
||||
fn identify_msg(
|
||||
&mut self,
|
||||
mut buf: &[u8],
|
||||
) -> Result<(usize, Option<NonZeroUsize>), Box<dyn std::error::Error + Send + Sync + 'static>>
|
||||
{
|
||||
let Some(skip) = buf.iter().position(|c| !c.is_ascii_whitespace()) else {
|
||||
return Ok((buf.len(), None));
|
||||
};
|
||||
buf = buf.split_at(skip).1;
|
||||
if let Some(idx) = buf.iter().position(|c| *c == b'\n') {
|
||||
Ok((skip, NonZeroUsize::new(idx + 1)))
|
||||
} else if buf.len() >= MAX_RECV_LEN {
|
||||
Err(MsgParseError::TooLong.into())
|
||||
} else {
|
||||
Ok((skip, None))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_msg<'a>(
|
||||
&mut self,
|
||||
buf: &'a [u8],
|
||||
) -> Result<Self::RecvMsg<'a>, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
Ok(RawServerMsg::parse(String::from_utf8_lossy(buf))?)
|
||||
}
|
||||
}
|
||||
17
src/lib.rs
Normal file
17
src/lib.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
//! [Vinezombie](https://git.sr.ht/~daemoness/vinezombie)
|
||||
#![deny(missing_docs)]
|
||||
#![deny(clippy::missing_safety_doc)]
|
||||
|
||||
//#[cfg(feature = "graveseed")]
|
||||
//pub mod handlers;
|
||||
//pub mod init;
|
||||
//#[cfg(feature = "graveseed")]
|
||||
//pub mod io;
|
||||
//pub mod known;
|
||||
//pub mod msg;
|
||||
//pub mod sasl;
|
||||
//pub mod state;
|
||||
//mod string;
|
||||
|
||||
//pub use crate::string::strmap;
|
||||
//pub use crate::string::*;
|
||||
98
src/msg.rs
Normal file
98
src/msg.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! IRC messages and fragments.
|
||||
|
||||
pub mod args;
|
||||
mod client;
|
||||
pub mod data;
|
||||
mod server;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use self::{client::*, server::*};
|
||||
|
||||
/// Convenience alias for a [ClientMsg] with unprocessed arguments and tags.
|
||||
pub type RawClientMsg<'a> = ClientMsg<'a, data::RawData<'a>>;
|
||||
/// Convenience alias for a [ServerMsg] with unprocessed arguments and tags.
|
||||
pub type RawServerMsg<'a> = ServerMsg<'a, data::RawData<'a>>;
|
||||
|
||||
use crate::known;
|
||||
|
||||
/// State of a [ServerMsg] parsing operation.
|
||||
pub enum MsgParserStatus<'a, T> {
|
||||
/// The message is ready.
|
||||
Ready(ServerMsg<'a, T>),
|
||||
/// More messages are required for complete message data.
|
||||
Pending(Box<dyn MsgParser<'a, Data = T> + 'a>),
|
||||
/// A message was received that was of a valid kind but incorrectly structured.
|
||||
Invalid(std::borrow::Cow<'static, str>),
|
||||
}
|
||||
|
||||
impl<'a, T: 'a> MsgParserStatus<'a, T> {
|
||||
/// Ends parsing and attempts to return a [ServerMsg].
|
||||
pub fn finish(self) -> Option<ServerMsg<'a, T>> {
|
||||
match self {
|
||||
MsgParserStatus::Ready(m) => Some(m),
|
||||
MsgParserStatus::Pending(b) => b.finish_early(),
|
||||
MsgParserStatus::Invalid(e) => {
|
||||
#[cfg(feature = "log")]
|
||||
log::warn!("secondary message parsing failed: {}", e);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Types that can process [RawServerMsg] data into more-useful versions.
|
||||
pub trait MsgParser<'a> {
|
||||
// Would be nice if this was generic, but that kills object safety at this tie.
|
||||
/// The data type for messages that this parser can generate.
|
||||
type Data: Sized + 'a;
|
||||
/// Parses one [RawServerMsg].
|
||||
fn parse_msg(self: Box<Self>, msg: &RawServerMsg<'a>) -> MsgParserStatus<'a, Self::Data>;
|
||||
/// Ends message parsing and attempts to return a [ServerMsg] from
|
||||
/// whatever has already been parsed.
|
||||
///
|
||||
/// Not all parsers will implement this method to return anything other than `None`,
|
||||
fn finish_early(self: Box<Self>) -> Option<ServerMsg<'a, Self::Data>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// [MsgParser]s with a consistent way of being constructed.
|
||||
pub trait NewMsgParser<'a>: MsgParser<'a> {
|
||||
/// The type of options for constructing the parser.
|
||||
type Options: 'a;
|
||||
/// Constructs a new message parser.
|
||||
fn new_msg_parser(options: Self::Options) -> Box<Self>
|
||||
where
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
/// Message data types with a sensible default [MsgParser].
|
||||
pub trait DefaultMsgParser<'a> {
|
||||
/// The message parser type.
|
||||
type Parser: NewMsgParser<'a, Data = Self>;
|
||||
}
|
||||
|
||||
/// Types that can process client messages into [RawClientMsg]s suitable to be sent.
|
||||
pub trait MsgWriter<'a> {
|
||||
/// Writes one [RawClientMsg].
|
||||
fn write_msg(self: Box<Self>) -> (RawClientMsg<'a>, Option<Box<dyn MsgWriter<'a> + 'a>>);
|
||||
}
|
||||
|
||||
/// [MsgWriter]s with a consistent way of being constructed.
|
||||
pub trait NewMsgWriter<'a>: MsgWriter<'a> {
|
||||
/// The type of options for constructing the writer.
|
||||
type Options: 'a;
|
||||
/// The data type for messages that this writer can be constructed out of.
|
||||
type Data: Sized + 'a;
|
||||
/// Constructs a new message writer.
|
||||
fn new_msg_writer(init: ClientMsg<'a, Self::Data>, options: Self::Options) -> Box<Self>
|
||||
where
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
/// Message data types with a sensible default [MsgWriter].
|
||||
pub trait DefaultMsgWriter<'a> {
|
||||
/// The message writer type.
|
||||
type Writer: NewMsgWriter<'a, Data = Self>;
|
||||
}
|
||||
139
src/msg/args.rs
Normal file
139
src/msg/args.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
//! IRC message argument utilities.
|
||||
|
||||
use crate::{IrcStr, IrcWord};
|
||||
|
||||
/// IRC message argument array.
|
||||
///
|
||||
/// This type enforces the invariant that
|
||||
/// only the last argument may be longer than one word.
|
||||
#[derive(Clone, PartialEq, Eq, Default, Debug)]
|
||||
pub struct Args<'a>(Vec<IrcStr<'a>>, bool);
|
||||
|
||||
impl<'a> Args<'a> {
|
||||
/// Creates a new empty argument array.
|
||||
pub fn new() -> Args<'a> {
|
||||
Default::default()
|
||||
}
|
||||
/// Parses an argument array from a string.
|
||||
pub fn parse(s: impl Into<IrcStr<'a>>) -> Args<'a> {
|
||||
let mut s = s.into();
|
||||
let mut args = Args::default();
|
||||
loop {
|
||||
s.slice(str::trim_start);
|
||||
if s.lex_char(|c| *c == ':').is_some() {
|
||||
args.add(std::mem::take(&mut s));
|
||||
break;
|
||||
} else if let Some(word) = s.lex_word() {
|
||||
args.add_word(word);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
args
|
||||
}
|
||||
/// Clears the argument array.
|
||||
pub fn clear(&mut self) {
|
||||
self.0.clear();
|
||||
self.1 = false;
|
||||
}
|
||||
/// Removes the last argument and returns it, or None is the argument array is empty.
|
||||
pub fn pop(&mut self) -> Option<IrcStr<'a>> {
|
||||
self.1 = false;
|
||||
self.0.pop()
|
||||
}
|
||||
/// Adds a word to the argument array.
|
||||
///
|
||||
/// The word will be added to the end of the argument array unless the last argument is long,
|
||||
/// in which case it will be added just before it.
|
||||
pub fn add_word<'b: 'a>(&mut self, w: impl Into<IrcWord<'b>>) {
|
||||
let mut s: IrcStr<'a> = w.into().into();
|
||||
if self.1 {
|
||||
std::mem::swap(&mut s, self.0.last_mut().unwrap());
|
||||
}
|
||||
self.0.push(s);
|
||||
}
|
||||
/// Adds a word to the argument array in the second-to-last position.
|
||||
///
|
||||
/// If the argument array is empty, just adds the word.
|
||||
/// Use this when the last argument in the array has special meaning.
|
||||
pub fn add_word_before_last<'b: 'a>(&mut self, w: impl Into<IrcWord<'b>>) {
|
||||
let mut s: IrcStr<'a> = w.into().into();
|
||||
if let Some(last) = self.0.last_mut() {
|
||||
std::mem::swap(&mut s, last);
|
||||
}
|
||||
self.0.push(s);
|
||||
}
|
||||
/// Adds a string to the end of this argument array.
|
||||
///
|
||||
/// If the last string in the argument array is long, it will be replaced.
|
||||
pub fn add<'b: 'a>(&mut self, s: impl Into<IrcStr<'b>>) {
|
||||
let s = s.into();
|
||||
let long = !s.is_word();
|
||||
if self.1 {
|
||||
*self.0.last_mut().unwrap() = s;
|
||||
} else {
|
||||
self.0.push(s);
|
||||
}
|
||||
self.1 = long;
|
||||
}
|
||||
/// Returns true if there are no arguments.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
/// Returns true if the last argument is more than one word long.
|
||||
pub fn is_last_long(&self) -> bool {
|
||||
self.1
|
||||
}
|
||||
/// Returns a slice of all of the arguments.
|
||||
pub fn all(&self) -> &[IrcStr<'a>] {
|
||||
self.0.as_slice()
|
||||
}
|
||||
/// Returns a slice of arguments that are single-word arguments.
|
||||
pub fn words(&self) -> &[IrcWord<'a>] {
|
||||
match self.0.split_last() {
|
||||
Some((l, rest)) if !l.is_word() => unsafe {
|
||||
// IrcWord and IrcStr are transmutable between each other.
|
||||
IrcWord::cast_slice(rest)
|
||||
},
|
||||
_ => unsafe { IrcWord::cast_slice(self.0.as_slice()) },
|
||||
}
|
||||
}
|
||||
/// Returns the arguments with the last argument split off.
|
||||
pub fn split_last(&self) -> (&[IrcWord<'a>], Option<&IrcStr<'a>>) {
|
||||
if let Some((last, rest)) = self.0.split_last() {
|
||||
(unsafe { IrcWord::cast_slice(rest) }, Some(last))
|
||||
} else {
|
||||
(Default::default(), None)
|
||||
}
|
||||
}
|
||||
/// Returns the arguments with the last argument split off and mutable.
|
||||
pub fn split_last_mut(&mut self) -> (&[IrcWord<'a>], Option<&mut IrcStr<'a>>) {
|
||||
if let Some((last, rest)) = self.0.split_last_mut() {
|
||||
(unsafe { IrcWord::cast_slice(rest) }, Some(last))
|
||||
} else {
|
||||
(Default::default(), None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Args<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut pad = false;
|
||||
let (words, long) =
|
||||
if self.is_last_long() { self.split_last() } else { (self.words(), None) };
|
||||
for arg in words {
|
||||
if pad {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
write!(f, "{}", arg)?;
|
||||
pad = true;
|
||||
}
|
||||
if let Some(c) = long {
|
||||
if pad {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
write!(f, ":{}", c)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
113
src/msg/client.rs
Normal file
113
src/msg/client.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use super::{
|
||||
data::{FlexibleKind, RawData, TerminalKind},
|
||||
known::{self, Cmd},
|
||||
server::ServerMsg,
|
||||
DefaultMsgWriter, NewMsgWriter, Source,
|
||||
};
|
||||
use crate::known::MaybeKnown;
|
||||
|
||||
/// Convenience alias for the kind of a [ClientMsg].
|
||||
pub type ClientMsgKind<'a> = MaybeKnown<'a, Cmd>;
|
||||
|
||||
/// Message sent by an IRC client.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ClientMsg<'a, T> {
|
||||
/// The command for this message.
|
||||
kind: ClientMsgKind<'a>,
|
||||
/// The data associated with this message.
|
||||
data: T,
|
||||
}
|
||||
|
||||
impl<'a> ClientMsg<'a, RawData<'a>> {
|
||||
/// Creates an empty [crate::msg::RawClientMsg].
|
||||
pub fn new_raw(kind: impl Into<known::MaybeKnown<'a, Cmd>>) -> Self {
|
||||
ClientMsg { kind: kind.into(), data: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: new functions for T: TerminalKind<Data = constraint>
|
||||
|
||||
impl<'a, T: FlexibleKind> ClientMsg<'a, T> {
|
||||
/// Constructs a new message with the provided data and kind.
|
||||
pub fn new_with_kind(kind: impl Into<known::MaybeKnown<'a, Cmd>>, data: T) -> Self {
|
||||
ClientMsg { kind: kind.into(), data }
|
||||
}
|
||||
/// Returns a mutable reference to this message's kind.
|
||||
pub fn kind_mut(&mut self) -> &mut ClientMsgKind<'a> {
|
||||
&mut self.kind
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: FlexibleKind + Default> ClientMsg<'a, T> {
|
||||
/// Constructs a new message with the provided kind.
|
||||
pub fn new_default_with_kind(kind: impl Into<ClientMsgKind<'a>>) -> Self {
|
||||
ClientMsg { kind: kind.into(), data: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, K: Into<ClientMsgKind<'static>>, T: TerminalKind<Kind = K>> ClientMsg<'a, T> {
|
||||
/// Constructs a new message with the provided data.
|
||||
pub fn new(data: T) -> Self {
|
||||
ClientMsg { kind: T::terminal_kind().into(), data }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, K: Into<ClientMsgKind<'static>>, T: TerminalKind<Kind = K> + Default> ClientMsg<'a, T> {
|
||||
/// Constructs a new message.
|
||||
pub fn new_default() -> Self {
|
||||
ClientMsg { kind: T::terminal_kind().into(), data: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: DefaultMsgWriter<'a>> ClientMsg<'a, T> {
|
||||
/// Converts this message into the default [MsgWriter] for its data type.
|
||||
pub fn to_default_writer(
|
||||
self,
|
||||
options: <<T as DefaultMsgWriter<'a>>::Writer as NewMsgWriter<'a>>::Options,
|
||||
) -> Box<T::Writer> {
|
||||
T::Writer::new_msg_writer(self, options)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> ClientMsg<'a, T> {
|
||||
/// Breaks this message up into its members.
|
||||
pub fn into_parts(self) -> (MaybeKnown<'a, Cmd>, T) {
|
||||
(self.kind, self.data)
|
||||
}
|
||||
/// Returns a reference to this message's kind.
|
||||
pub fn kind(&self) -> &ClientMsgKind<'a> {
|
||||
&self.kind
|
||||
}
|
||||
/// Returns a reference to this message's data.
|
||||
pub fn data(&self) -> &T {
|
||||
&self.data
|
||||
}
|
||||
/// Returns a mutable reference to this message's data.
|
||||
pub fn data_mut(&mut self) -> &mut T {
|
||||
&mut self.data
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Clone> ClientMsg<'a, T> {
|
||||
/// Converts this message into a [ServerMsg] as another client would receive it.
|
||||
pub fn preview<'b, 'c>(&self, source: Source<'b>) -> ServerMsg<'c, T>
|
||||
where
|
||||
'a: 'c,
|
||||
'b: 'c,
|
||||
{
|
||||
let kind = self.kind.clone().map_known(known::Kind::from);
|
||||
let data = self.data.clone();
|
||||
super::ServerMsg { source, kind, data }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ClientMsg<'_, RawData<'_>> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// TODO: Tags.
|
||||
write!(f, "{}", self.kind)?;
|
||||
if !self.data.args.is_empty() {
|
||||
write!(f, " {}", self.data.args)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
182
src/msg/server.rs
Normal file
182
src/msg/server.rs
Normal file
@@ -0,0 +1,182 @@
|
||||
use super::{
|
||||
args,
|
||||
client::ClientMsg,
|
||||
data::{FlexibleKind, RawData, TerminalKind},
|
||||
known, DefaultMsgParser, NewMsgParser,
|
||||
};
|
||||
use crate::{
|
||||
known::{Kind, MaybeKnown},
|
||||
IrcStr, IrcWord,
|
||||
};
|
||||
|
||||
/// Convenience alias for the kind of a [ServerMsg].
|
||||
pub type ServerMsgKind<'a> = MaybeKnown<'a, Kind>;
|
||||
/// Representation of the source of a server message.
|
||||
pub type Source<'a> = Option<IrcWord<'a>>;
|
||||
|
||||
/// Error type when parsing a [`ServerMsg`].
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum MsgParseError {
|
||||
/// Message exceeds permissible length limits.
|
||||
///
|
||||
/// [`ServerMsg::parse`] does not return this, but an I/O step may.
|
||||
TooLong,
|
||||
/// Expected tags but none were provided.
|
||||
NoTags,
|
||||
/// Expected a source but none was provided.
|
||||
NoSource,
|
||||
/// There was no message kind in the provided message.
|
||||
NoKind,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for MsgParseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
MsgParseError::TooLong => write!(f, "invalid message: length limits exceeded"),
|
||||
MsgParseError::NoTags => write!(f, "invalid message: no tags after @"),
|
||||
MsgParseError::NoSource => write!(f, "invalid message: no source after :"),
|
||||
MsgParseError::NoKind => write!(f, "invalid message: kind/command"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for MsgParseError {}
|
||||
|
||||
/// Message sent by an IRC server.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ServerMsg<'a, T> {
|
||||
/// The sender of this message.
|
||||
pub source: Source<'a>,
|
||||
/// What kind of message this is, usually a command or numeric reply.
|
||||
pub kind: ServerMsgKind<'a>,
|
||||
/// The data associated with this message.
|
||||
pub data: T,
|
||||
}
|
||||
|
||||
impl<'a> ServerMsg<'a, RawData<'a>> {
|
||||
/// Parses a message from a string.
|
||||
pub fn parse(msg: impl Into<IrcStr<'a>>) -> Result<ServerMsg<'a, RawData<'a>>, MsgParseError> {
|
||||
let mut msg = msg.into();
|
||||
let mut source = None;
|
||||
msg.slice(str::trim);
|
||||
if msg.lex_char(|c| *c == '@').is_some() {
|
||||
// TODO: Tags. Specifically, actually parse them.
|
||||
let _ = msg.lex_word().ok_or(MsgParseError::NoTags)?;
|
||||
msg.slice(str::trim_start);
|
||||
}
|
||||
if msg.lex_char(|c| *c == ':').is_some() {
|
||||
source = Some(msg.lex_word().ok_or(MsgParseError::NoSource)?);
|
||||
msg.slice(str::trim_start);
|
||||
}
|
||||
let kind = msg.lex_word().ok_or(MsgParseError::NoKind)?.into();
|
||||
let args = args::Args::parse(msg);
|
||||
let data = RawData { args };
|
||||
Ok(ServerMsg { source, kind, data })
|
||||
}
|
||||
/// The number of bytes of space remaining in this message.
|
||||
///
|
||||
/// If the returned value is negative, this message is too long
|
||||
/// to guarantee its delivery in whole for most IRCd client/server pairs.
|
||||
pub fn bytes_left(&self) -> isize {
|
||||
// TODO: Encoding.
|
||||
// TODO: Tags!
|
||||
let mut size = self.kind.len_bytes() + 2; // Newline.
|
||||
if let Some(ref word) = self.source {
|
||||
size += 2 + word.len_bytes();
|
||||
}
|
||||
for arg in self.data.args.all() {
|
||||
size += arg.len_bytes() + 1; // Space.
|
||||
}
|
||||
if self.data.args.is_last_long() {
|
||||
size += 1; // Colon.
|
||||
}
|
||||
let size: isize = size.try_into().unwrap_or(isize::MAX);
|
||||
512 - size
|
||||
}
|
||||
/// Tries to convert this message into one with a different data type.
|
||||
pub fn to_parsed<T: DefaultMsgParser<'a> + 'a>(
|
||||
&self,
|
||||
options: <<T as DefaultMsgParser<'a>>::Parser as NewMsgParser<'a>>::Options,
|
||||
) -> Option<ServerMsg<'a, T>> {
|
||||
use crate::msg::MsgParser;
|
||||
let parser = T::Parser::new_msg_parser(options);
|
||||
parser.parse_msg(self).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> ServerMsg<'a, T> {
|
||||
/// Breaks this message up into its members.
|
||||
pub fn into_parts(self) -> (ServerMsgKind<'a>, T, Source<'a>) {
|
||||
(self.kind, self.data, self.source)
|
||||
}
|
||||
/// Returns a reference to this message's kind.
|
||||
pub fn kind(&self) -> &ServerMsgKind<'a> {
|
||||
&self.kind
|
||||
}
|
||||
/// Returns a reference to this message's data.
|
||||
pub fn data(&self) -> &T {
|
||||
&self.data
|
||||
}
|
||||
/// Returns a mutable reference to this message's data.
|
||||
pub fn data_mut(&mut self) -> &mut T {
|
||||
&mut self.data
|
||||
}
|
||||
/// Returns a reference to this message's source.
|
||||
pub fn source(&self) -> &Source<'a> {
|
||||
&self.source
|
||||
}
|
||||
/// Returns a mutable reference to this message's source.
|
||||
pub fn source_mut(&mut self) -> &mut Source<'a> {
|
||||
&mut self.source
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: FlexibleKind + Clone + 'a> ServerMsg<'a, T> {
|
||||
/// Returns a mutable reference to this message's kind.
|
||||
pub fn kind_mut(&mut self) -> &mut known::MaybeKnown<'a, known::Kind> {
|
||||
&mut self.kind
|
||||
}
|
||||
/// Creates a [ClientMsg] with the same arguments as this message.
|
||||
pub fn reply_with_kind<'b, 'c>(
|
||||
&self,
|
||||
kind: impl Into<known::MaybeKnown<'b, known::Cmd>>,
|
||||
) -> ClientMsg<'c, T>
|
||||
where
|
||||
'a: 'c,
|
||||
'b: 'c,
|
||||
{
|
||||
ClientMsg::new_with_kind(kind, self.data.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: FlexibleKind + 'a> ServerMsg<'a, T> {
|
||||
/// Constructs a new [ServerMsg] with the provided kind, data, and source.
|
||||
pub fn new_with_kind(
|
||||
kind: impl Into<ServerMsgKind<'a>>,
|
||||
data: T,
|
||||
source: Source<'a>,
|
||||
) -> ServerMsg<'a, T> {
|
||||
ServerMsg { kind: kind.into(), data, source }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: TerminalKind + 'a> ServerMsg<'a, T> {
|
||||
/// Constructs a new [ServerMsg] with the provided data and source
|
||||
pub fn new(data: T, source: Source<'a>) -> ServerMsg<'a, T> {
|
||||
ServerMsg { kind: T::terminal_kind().into(), data, source }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ServerMsg<'_, RawData<'_>> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// TODO: Tags.
|
||||
if let Some(ref src) = self.source {
|
||||
write!(f, ":{} ", src.as_ref())?;
|
||||
}
|
||||
write!(f, "{}", self.kind)?;
|
||||
if !self.data.args.is_empty() {
|
||||
write!(f, " {}", self.data.args)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
70
src/msg/tests.rs
Normal file
70
src/msg/tests.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use super::{known::*, RawServerMsg};
|
||||
|
||||
#[test]
|
||||
pub fn parse_cmd() {
|
||||
let msg = RawServerMsg::parse("privMSG").unwrap();
|
||||
assert_eq!(msg.kind.as_known_into(), Some(Cmd::Privmsg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn parse_source_word() {
|
||||
let msg = RawServerMsg::parse(":server PING 123").unwrap();
|
||||
assert_eq!(msg.source.clone().unwrap().as_ref(), "server");
|
||||
assert_eq!(msg.kind.into_word(), "PING");
|
||||
assert_eq!(msg.data.args.split_last(), ([].as_slice(), Some(&"123".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn parse_word() {
|
||||
let msg = RawServerMsg::parse("PONG 123").unwrap();
|
||||
assert_eq!(msg.data.args.split_last(), ([].as_slice(), Some(&"123".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn parse_words() {
|
||||
let msg = RawServerMsg::parse("NOTICE #foo :beep").unwrap();
|
||||
assert_eq!(msg.data.args.words(), &["#foo", "beep"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn parse_words_long() {
|
||||
let msg = RawServerMsg::parse("PRIVMSG #foo #bar :Hello world").unwrap();
|
||||
let (chans, last) = msg.data.args.split_last();
|
||||
let last = last.unwrap();
|
||||
assert_eq!(chans, &["#foo", "#bar"]);
|
||||
assert_eq!(last.as_ref(), "Hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn parse_tag() {
|
||||
let msg = RawServerMsg::parse("@tag TAGMSG").unwrap();
|
||||
assert_eq!(msg.source, None);
|
||||
assert_eq!(msg.kind.into_word(), "TAGMSG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn to_string() {
|
||||
let cases = ["CMD", "CMD word :some words", ":src CMD word", ":numeric 001"];
|
||||
for case in cases {
|
||||
let looped = RawServerMsg::parse(case).unwrap().to_string();
|
||||
assert_eq!(looped, case);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn len_bytes() {
|
||||
let cases = [
|
||||
"CMD\r\n",
|
||||
"CMD word\r\n",
|
||||
"CMD word1 word2\r\n",
|
||||
"CMD word :some words\r\n",
|
||||
":src CMD word\r\n",
|
||||
"CMD uniçödé\r\n",
|
||||
"001\r\n",
|
||||
];
|
||||
for case in cases {
|
||||
let testlen = 512 - RawServerMsg::parse(case).unwrap().bytes_left();
|
||||
let caselen = case.as_bytes().len() as isize;
|
||||
assert_eq!(testlen, caselen, "wrong length calculation for: {}", case);
|
||||
}
|
||||
}
|
||||
159
src/sasl.rs
Normal file
159
src/sasl.rs
Normal file
@@ -0,0 +1,159 @@
|
||||
//! SASL mechanisms and related types.
|
||||
|
||||
use std::{error::Error, ffi::CString, sync::Arc};
|
||||
|
||||
/// Types that can store sensitive byte strings.
|
||||
pub trait Secret {
|
||||
/// Appends the secret's bytes to the provided string.
|
||||
///
|
||||
/// This method may fail if retrieving the secret fails.
|
||||
fn append_to(&self, data: &mut Vec<u8>) -> Result<(), Box<dyn Error>>;
|
||||
/// Returns a hint for how many bytes should be preallocated for this secret.
|
||||
fn len_hint(&self) -> usize {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero-added-security implementation of `Secret`.
|
||||
impl Secret for String {
|
||||
fn append_to(&self, data: &mut Vec<u8>) -> Result<(), Box<dyn Error>> {
|
||||
data.extend(self.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
fn len_hint(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// The type used for [SaslLogic] replies.
|
||||
///
|
||||
/// Bundles the body of the reply with a continuation for the logic.
|
||||
type SaslReply = (Vec<u8>, Box<dyn SaslLogic>);
|
||||
|
||||
/// The logic of a SASL mechanism.
|
||||
///
|
||||
/// This trait uses a similar pattern to [crate::handler::Handler],
|
||||
/// where every state change is explicitly modeled but
|
||||
/// the state may change types during execution.
|
||||
pub trait SaslLogic {
|
||||
/// Handles data sent by the server.
|
||||
fn reply(self: Box<Self>, data: Vec<u8>) -> Result<SaslReply, Box<dyn Error>>;
|
||||
}
|
||||
|
||||
/// [SaslLogic] that marks the end of expected server messages.
|
||||
pub struct SaslLogicDone;
|
||||
|
||||
impl SaslLogic for SaslLogicDone {
|
||||
fn reply(self: Box<Self>, _: Vec<u8>) -> Result<SaslReply, Box<dyn Error>> {
|
||||
Err("unexpected reply from server".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// SASL mechanisms.
|
||||
pub trait Sasl: std::fmt::Debug {
|
||||
/// The name of this mechanism, as the client requests it.
|
||||
fn name(&self) -> &'static str;
|
||||
/// Returns the logic for this mechanism as a [SaslLogic].
|
||||
fn logic(&self) -> Box<dyn SaslLogic>;
|
||||
}
|
||||
|
||||
/// The [EXTERNAL SASL mechanism](https://www.rfc-editor.org/rfc/rfc4422#appendix-A).
|
||||
///
|
||||
/// This is what is used when authentication occurs out-of-band,
|
||||
/// such as when using TLS client certificate authentication.
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
pub struct External;
|
||||
|
||||
struct ExternalLogic;
|
||||
|
||||
impl SaslLogic for ExternalLogic {
|
||||
fn reply(self: Box<Self>, _: Vec<u8>) -> Result<SaslReply, Box<dyn Error>> {
|
||||
// TODO: Strictness?
|
||||
Ok((Vec::new(), Box::new(SaslLogicDone)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Sasl for External {
|
||||
fn name(&self) -> &'static str {
|
||||
"EXTERNAL"
|
||||
}
|
||||
fn logic(&self) -> Box<dyn SaslLogic> {
|
||||
Box::new(ExternalLogic)
|
||||
}
|
||||
}
|
||||
|
||||
/// The [PLAIN SASL mechanism](https://www.rfc-editor.org/rfc/rfc4616).
|
||||
///
|
||||
/// This is what is used for typical username/password authentication.
|
||||
#[derive(Clone)]
|
||||
pub struct Plain<S> {
|
||||
authzid: Arc<CString>,
|
||||
authcid: Arc<CString>,
|
||||
passwd: Arc<S>,
|
||||
}
|
||||
|
||||
impl<S: Secret> Plain<S> {
|
||||
/// Creates a [Plain] that logs in to the specified account.
|
||||
/// The authzid is left empty; compliant implementations should infer it.
|
||||
///
|
||||
/// `passwd` should be UTF-8 encoded and not contain a null character,
|
||||
/// but this is not enforced.
|
||||
pub fn new(account: CString, passwd: S) -> Self {
|
||||
Plain {
|
||||
authzid: Arc::new(CString::new("").unwrap()),
|
||||
authcid: Arc::new(account),
|
||||
passwd: Arc::new(passwd),
|
||||
}
|
||||
}
|
||||
/// Creates a [Plain] that logs into the account specified by authzid
|
||||
/// using the credentials for the account specified by authcid.
|
||||
///
|
||||
/// `passwd` should be UTF-8 encoded and not contain a null character,
|
||||
/// but this is not enforced.
|
||||
pub fn new_as(authzid: CString, authcid: CString, passwd: S) -> Self {
|
||||
Plain { authzid: Arc::new(authzid), authcid: Arc::new(authcid), passwd: Arc::new(passwd) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> std::fmt::Debug for Plain<S> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Plain")
|
||||
.field("authzid", &self.authzid)
|
||||
.field("authcid", &self.authcid)
|
||||
.field("passwd", &format_args!("<?>"))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
struct PlainLogic<S> {
|
||||
authzid: Arc<CString>,
|
||||
authcid: Arc<CString>,
|
||||
passwd: Arc<S>,
|
||||
}
|
||||
|
||||
impl<S: Secret> SaslLogic for PlainLogic<S> {
|
||||
fn reply(self: Box<Self>, mut data: Vec<u8>) -> Result<SaslReply, Box<dyn Error>> {
|
||||
// TODO: Strictness?
|
||||
data.clear();
|
||||
let authzid = self.authzid.as_bytes_with_nul();
|
||||
let authcid = self.authcid.as_bytes_with_nul();
|
||||
data.reserve(self.passwd.len_hint() + authcid.len() + authzid.len());
|
||||
data.extend(authzid);
|
||||
data.extend(authcid);
|
||||
self.passwd.append_to(&mut data)?;
|
||||
Ok((data, Box::new(SaslLogicDone)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Secret + 'static> Sasl for Plain<S> {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLAIN"
|
||||
}
|
||||
fn logic(&self) -> Box<dyn SaslLogic> {
|
||||
Box::new(PlainLogic {
|
||||
authzid: self.authzid.clone(),
|
||||
authcid: self.authcid.clone(),
|
||||
passwd: self.passwd.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
84
src/state.rs
Normal file
84
src/state.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
//! Representations of IRC network and connection state, including users and channels.
|
||||
|
||||
use crate::known::{Cap, MaybeKnown};
|
||||
use crate::msg::data::CapStatus;
|
||||
use crate::IrcWord;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// The observed state of an entire IRC network.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct Network {
|
||||
// TODO: Channel lists, user lists.
|
||||
/// The capabilities that are available on this network.
|
||||
pub caps: BTreeSet<MaybeKnown<'static, Cap>>,
|
||||
/// The values of some capabilities that are available on this network.
|
||||
///
|
||||
/// Presence of a key in this map does not imply that a capability is available,
|
||||
/// that it has the specified value if it is available.
|
||||
/// You should ideally ensure that the set of keys is a subset of [Network::caps].
|
||||
pub caps_values: BTreeMap<MaybeKnown<'static, Cap>, IrcWord<'static>>,
|
||||
}
|
||||
|
||||
impl Network {
|
||||
/// Adds a capability.
|
||||
pub fn cap_add(
|
||||
&mut self,
|
||||
cap: impl Into<MaybeKnown<'static, Cap>>,
|
||||
value: Option<IrcWord<'static>>,
|
||||
) {
|
||||
let cap = cap.into();
|
||||
if let Some(value) = value {
|
||||
self.caps_values.insert(cap.clone(), value);
|
||||
}
|
||||
self.caps.insert(cap);
|
||||
}
|
||||
/// Removes a capability.
|
||||
pub fn cap_del(&mut self, cap: impl Into<MaybeKnown<'static, Cap>>) {
|
||||
let cap = cap.into();
|
||||
self.caps_values.remove(&cap);
|
||||
self.caps.remove(&cap);
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of an active connection to an IRC network.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Connection {
|
||||
/// The nickname currently in use.
|
||||
pub nick: IrcWord<'static>,
|
||||
/// The capabilities that have been enabled for this connection.
|
||||
pub caps: BTreeSet<MaybeKnown<'static, Cap>>,
|
||||
/// The state of the network.
|
||||
pub net: Arc<RwLock<Network>>,
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Creates a new connection state tracker using the given nick and shared network state.
|
||||
pub fn new(nick: IrcWord<'static>, net: Option<Arc<RwLock<Network>>>) -> Self {
|
||||
Connection { nick, caps: BTreeSet::new(), net: net.unwrap_or_default() }
|
||||
}
|
||||
/// Updates the statuses of capabilities.
|
||||
pub fn update_caps(
|
||||
&mut self,
|
||||
iter: impl IntoIterator<Item = (MaybeKnown<'static, Cap>, CapStatus)>,
|
||||
) {
|
||||
// TODO: Use LazyCell whenever that stabilizes to acquire the net lock lazily.
|
||||
let mut net = self.net.write().unwrap();
|
||||
for (cap, status) in iter {
|
||||
match status {
|
||||
CapStatus::Available(value) => net.cap_add(cap, value),
|
||||
CapStatus::Enabled => {
|
||||
net.caps.insert(cap.clone());
|
||||
self.caps.insert(cap);
|
||||
}
|
||||
CapStatus::Unchanged => (),
|
||||
CapStatus::Disabled(avail) => {
|
||||
self.caps.remove(&cap);
|
||||
if !avail {
|
||||
net.cap_del(cap);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
0
src/state/caps.rs
Normal file
0
src/state/caps.rs
Normal file
8
src/string.rs
Normal file
8
src/string.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
#[cfg(feature = "base64")]
|
||||
pub mod base64;
|
||||
mod ircstr;
|
||||
mod ircword;
|
||||
pub mod strmap;
|
||||
|
||||
pub use ircstr::IrcStr;
|
||||
pub use ircword::IrcWord;
|
||||
23
src/string/base64.rs
Normal file
23
src/string/base64.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
//! Base64 encoding and decoding.
|
||||
//!
|
||||
//! This module contains two functions,
|
||||
//! one for encoding octet strings as standard Base64,
|
||||
//! and one for decoding the same.
|
||||
|
||||
// TODO: Homebrew implementations here are possible.
|
||||
|
||||
use crate::{IrcStr, IrcWord};
|
||||
|
||||
static CONFIG: base64::Config =
|
||||
base64::Config::new(base64::CharacterSet::Standard, true).decode_allow_trailing_bits(true);
|
||||
|
||||
/// Encodes bytes as a Base64 string.
|
||||
pub fn encode(b256: &[u8]) -> IrcWord<'static> {
|
||||
let string: IrcStr<'static> = base64::encode_config(b256, CONFIG).into();
|
||||
unsafe { IrcWord::new_unchecked(string) }
|
||||
}
|
||||
|
||||
/// Decodes a Base64 string.
|
||||
pub fn decode(b64: &str) -> Option<Vec<u8>> {
|
||||
base64::decode_config(b64, CONFIG).ok()
|
||||
}
|
||||
213
src/string/ircstr.rs
Normal file
213
src/string/ircstr.rs
Normal file
@@ -0,0 +1,213 @@
|
||||
use std::{borrow::Cow, ops::Deref, sync::Arc};
|
||||
|
||||
use crate::IrcWord;
|
||||
|
||||
#[inline]
|
||||
fn owned_from_buf(data: &str) -> IrcStr<'static> {
|
||||
if data.is_empty() {
|
||||
return IrcStr::default();
|
||||
}
|
||||
let arc: Arc<str> = data.into();
|
||||
owned_from_rc(arc)
|
||||
}
|
||||
#[inline]
|
||||
fn owned_from_rc(arc: Arc<str>) -> IrcStr<'static> {
|
||||
let slice = unsafe { Arc::as_ptr(&arc).as_ref().unwrap_unchecked() };
|
||||
IrcStr(slice, Some(arc))
|
||||
}
|
||||
/*
|
||||
#[inline]
|
||||
fn mutated(data: &str, f: impl FnOnce(&mut str)) -> IrcStr<'static> {
|
||||
let mut arc: Arc<str> = data.into();
|
||||
// TODO: get_mut_unchecked
|
||||
f(unsafe { Arc::get_mut(&mut arc).unwrap_unchecked() });
|
||||
owned_from_arc(arc)
|
||||
}
|
||||
*/
|
||||
|
||||
/// A borrowing or shared-owning immutable UTF-8 string.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct IrcStr<'a>(&'a str, Option<Arc<str>>);
|
||||
// ^ Inner slice, if the option is Some, refers to data owned by that Arc.
|
||||
// It's very important that the slice never be returned with
|
||||
// a lifetime longer than the IrcStr it was obtained from.
|
||||
|
||||
impl<'a> IrcStr<'a> {
|
||||
/// Returns true if this string owns its data.
|
||||
pub fn is_owning(&self) -> bool {
|
||||
self.1.is_some()
|
||||
}
|
||||
/// Return an owning version of this string.
|
||||
///
|
||||
/// If this string already owns its data, this method only extends its lifetime.
|
||||
pub fn owning(&self) -> IrcStr<'static> {
|
||||
if self.is_owning() {
|
||||
// Lifetime extension.
|
||||
unsafe { std::mem::transmute(self.clone()) }
|
||||
} else {
|
||||
owned_from_buf(self.0)
|
||||
}
|
||||
}
|
||||
/// Returns a reference to the borrowed string with the same lifetime as the outer IrcStr.
|
||||
pub fn as_str_borrowed(&self) -> Option<&'a str> {
|
||||
(!self.is_owning()).then_some(self.0)
|
||||
}
|
||||
/// Shrinks this string using the provided function.
|
||||
pub fn slice<F>(&mut self, f: F) -> &mut Self
|
||||
where
|
||||
F: FnOnce(&str) -> &str,
|
||||
{
|
||||
// TODO: Is there a soundness hole here?
|
||||
self.0 = unsafe { std::mem::transmute(f(self.as_ref())) };
|
||||
self
|
||||
}
|
||||
/// Parses data from some or all of this string.
|
||||
pub fn parse<T, E, F>(&mut self, f: F) -> Result<T, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<(T, &str), E>,
|
||||
{
|
||||
let (t, s) = f(self.as_ref())?;
|
||||
// TODO: Is there a soundness hole here?
|
||||
self.0 = unsafe { std::mem::transmute(s) };
|
||||
Ok(t)
|
||||
}
|
||||
/// Extracts a slice from the string.
|
||||
pub fn lex<'b, F>(&'b mut self, f: F) -> Option<Self>
|
||||
where
|
||||
F: FnOnce(&'b str) -> Option<(&'b str, &'b str)>,
|
||||
{
|
||||
let (a, b) = f(self.0 as &'b str)?;
|
||||
// TODO: Is there a soundness hole here?
|
||||
self.0 = unsafe { std::mem::transmute(b) };
|
||||
let a = unsafe { std::mem::transmute(a) };
|
||||
Some(IrcStr(a, self.1.clone()))
|
||||
}
|
||||
/// Extracts a character from the string.
|
||||
pub fn lex_char<F>(&mut self, f: F) -> Option<char>
|
||||
where
|
||||
F: FnOnce(&char) -> bool,
|
||||
{
|
||||
let mut chars = self.chars();
|
||||
let c = chars.next();
|
||||
let s = chars.as_str();
|
||||
match c {
|
||||
Some(c) if f(&c) => {
|
||||
// TODO: Is there a soundness hole here?
|
||||
self.0 = unsafe { std::mem::transmute(s) };
|
||||
Some(c)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Extracts a word from the string.
|
||||
pub fn lex_word(&mut self) -> Option<IrcWord<'a>> {
|
||||
self.lex(|s| {
|
||||
let mut splitter = s.splitn(2, |c: char| c.is_ascii_whitespace());
|
||||
let w = splitter.next().filter(|w| !w.is_empty())?;
|
||||
let r = splitter.next().unwrap_or("");
|
||||
Some((w, r))
|
||||
})
|
||||
.map(|s| unsafe { IrcWord::new_unchecked(s) })
|
||||
}
|
||||
/// Returns true if this string is non-empty, contains no spaces, and doesn't begin with ':'.
|
||||
pub fn is_word(&self) -> bool {
|
||||
let Some(c) = self.as_bytes().get(0) else {
|
||||
return false;
|
||||
};
|
||||
*c != b':' && !self.chars().any(|c| c.is_ascii_whitespace())
|
||||
}
|
||||
/// Returns the length of this string in bytes.
|
||||
pub fn len_bytes(&self) -> usize {
|
||||
self.0.as_bytes().len()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Deref for IrcStr<'a> {
|
||||
type Target = str;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for IrcStr<'_> {
|
||||
fn as_ref(&self) -> &str {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::borrow::Borrow<str> for IrcStr<'_> {
|
||||
fn borrow(&self) -> &str {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
// Conversions to IrcStr.
|
||||
|
||||
impl From<String> for IrcStr<'static> {
|
||||
fn from(v: String) -> Self {
|
||||
let rc: Arc<str> = v.into_boxed_str().into();
|
||||
owned_from_rc(rc)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a str> for IrcStr<'a> {
|
||||
fn from(v: &'a str) -> Self {
|
||||
IrcStr(v, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<Cow<'a, str>> for IrcStr<'a> {
|
||||
fn from(v: Cow<'a, str>) -> Self {
|
||||
match v {
|
||||
Cow::Borrowed(s) => s.into(),
|
||||
Cow::Owned(s) => s.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Other impls.
|
||||
|
||||
impl PartialEq<&str> for IrcStr<'_> {
|
||||
fn eq(&self, other: &&str) -> bool {
|
||||
self.0 == *other
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for IrcStr<'_> {
|
||||
fn eq(&self, b: &IrcStr<'_>) -> bool {
|
||||
self.0 == b.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for IrcStr<'_> {}
|
||||
|
||||
impl PartialOrd for IrcStr<'_> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for IrcStr<'_> {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.0.cmp(other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for IrcStr<'_> {
|
||||
fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
|
||||
self.0.hash(hasher)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IrcStr<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for IrcStr<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
78
src/string/ircword.rs
Normal file
78
src/string/ircword.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use super::IrcStr;
|
||||
|
||||
/// One-word-only newtype around IrcStr.
|
||||
///
|
||||
/// This type upholds the invariant that the underlying string is exactly one word
|
||||
/// that does not begin with a colon, as defined by [IrcStr::is_word].
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
|
||||
pub struct IrcWord<'a>(IrcStr<'a>);
|
||||
|
||||
impl<'a> IrcWord<'a> {
|
||||
// TODO: mut variant when there's a point to it.
|
||||
// TODO: Public functions for slice casting?
|
||||
pub(crate) unsafe fn cast_slice<'b>(s: &'b [IrcStr<'a>]) -> &'b [Self] {
|
||||
std::mem::transmute(s)
|
||||
}
|
||||
/// Creates a new IrcWord without checking that the string is a word.
|
||||
///
|
||||
/// # Safety
|
||||
/// The provided string must be a word as defined by [IrcStr::is_word]
|
||||
/// in order do not violate invariants.
|
||||
///
|
||||
/// Misuse of this function is unlikely to cause UB,
|
||||
/// but it may result in sending malformed IRC messages.
|
||||
pub unsafe fn new_unchecked(s: impl Into<IrcStr<'a>>) -> IrcWord<'a> {
|
||||
IrcWord(s.into())
|
||||
}
|
||||
/// Creates a new IrcWord if the input string is a word.
|
||||
pub fn new(s: impl Into<IrcStr<'a>>) -> Option<IrcWord<'a>> {
|
||||
let s = s.into();
|
||||
s.is_word().then_some(IrcWord(s))
|
||||
}
|
||||
/// Returns true.
|
||||
///
|
||||
/// This method exists to shadow [IrcStr::is_word] during deref coersion.
|
||||
pub fn is_word(&self) -> bool {
|
||||
true
|
||||
}
|
||||
/// As [IrcStr::owning].
|
||||
pub fn owning(&self) -> IrcWord<'static> {
|
||||
IrcWord(self.0.owning())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> std::ops::Deref for IrcWord<'a> {
|
||||
type Target = IrcStr<'a>;
|
||||
fn deref(&self) -> &IrcStr<'a> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Panicking conversion from a static str.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if the provided string is not a single word.
|
||||
impl From<&'static str> for IrcWord<'static> {
|
||||
fn from(s: &'static str) -> IrcWord<'static> {
|
||||
IrcWord::new(s).expect("&'static str to IrcWord conversion")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<IrcWord<'a>> for IrcStr<'a> {
|
||||
fn from(s: IrcWord<'a>) -> IrcStr<'a> {
|
||||
s.0
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<&str> for IrcWord<'_> {
|
||||
fn eq(&self, other: &&str) -> bool {
|
||||
self.0 == *other
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IrcWord<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
121
src/string/strmap.rs
Normal file
121
src/string/strmap.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! String-mapping utilities.
|
||||
//!
|
||||
//! IRC has unusal casemapping rules that can vary from network to network,
|
||||
//! so this module provides a variety of casemapping rules.
|
||||
//! In addition, other forms of mapping and comparison of mapped strings are possible
|
||||
//! (example: stripping prefixes, converting nicks to user cloaks).
|
||||
|
||||
use crate::IrcStr;
|
||||
|
||||
// Do not use generics to improve the API here.
|
||||
// These traits must be object-safe.
|
||||
|
||||
/// Trait-object-safe string map.
|
||||
pub trait StrMap {
|
||||
/// Returns a mapped version of the provided string.
|
||||
fn map<'a>(&self, s: IrcStr<'a>) -> IrcStr<'a>;
|
||||
/// Tests for equality post-map.
|
||||
/// The right side is assumed to already have been mapped.
|
||||
fn eq_halfmapped<'a>(&self, a: IrcStr<'a>, b: &'a str) -> bool {
|
||||
self.map(a).as_ref().eq(b)
|
||||
}
|
||||
/// Tests for equality post-map.
|
||||
fn eq<'a>(&self, a: IrcStr<'a>, b: IrcStr<'a>) -> bool {
|
||||
self.eq_halfmapped(a, self.map(b).as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// String map where every codepoint maps 1:1.
|
||||
pub trait StrMapSimple {
|
||||
/// Returns a mapped version of the provided character.
|
||||
fn map_char(&self, c: char) -> char;
|
||||
}
|
||||
|
||||
impl<T: StrMapSimple> StrMap for T {
|
||||
fn map<'a>(&self, s: IrcStr<'a>) -> IrcStr<'a> {
|
||||
for (idx, c) in s.char_indices() {
|
||||
if c != self.map_char(c) {
|
||||
let (mapped, unmapped) = s.as_bytes().split_at(idx);
|
||||
let (mapped, unmapped) = unsafe {
|
||||
(std::str::from_utf8_unchecked(mapped), std::str::from_utf8_unchecked(unmapped))
|
||||
};
|
||||
let mut retval = String::with_capacity(s.as_bytes().len());
|
||||
retval.push_str(mapped);
|
||||
for c in unmapped.chars() {
|
||||
retval.push(self.map_char(c))
|
||||
}
|
||||
return retval.into();
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
fn eq_halfmapped<'a>(&self, a: IrcStr<'a>, b: &str) -> bool {
|
||||
std::iter::zip(a.chars(), b.chars()).all(|(a, b)| self.map_char(a) == b)
|
||||
}
|
||||
fn eq<'a>(&self, a: IrcStr<'a>, b: IrcStr<'a>) -> bool {
|
||||
std::iter::zip(a.chars(), b.chars()).all(|(a, b)| self.map_char(a) == self.map_char(b))
|
||||
}
|
||||
}
|
||||
|
||||
/// Casemaps.
|
||||
pub mod casemap {
|
||||
use super::StrMapSimple;
|
||||
use crate::IrcStr;
|
||||
/// Returns a casemap by name, based off of common casemap names in ISUPPORT.
|
||||
pub fn by_name(name: IrcStr<'_>) -> Option<&'static dyn StrMapSimple> {
|
||||
match name.as_ref() {
|
||||
"ascii" => Some(&Ascii),
|
||||
"rfc1459-strict" => Some(&Rfc1459Strict),
|
||||
"rfc1459" => Some(&Rfc1459),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// ASCII lowercase casemap.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Ascii;
|
||||
/// ASCII uppercase casemap.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AsciiUpper;
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
/// Stricter IRC-style casemapping.
|
||||
pub struct Rfc1459Strict;
|
||||
/// IRC-style casemapping.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Rfc1459;
|
||||
|
||||
// TODO: Other casemaps?
|
||||
|
||||
impl StrMapSimple for Ascii {
|
||||
fn map_char(&self, c: char) -> char {
|
||||
c.to_ascii_lowercase()
|
||||
}
|
||||
}
|
||||
|
||||
impl StrMapSimple for AsciiUpper {
|
||||
fn map_char(&self, c: char) -> char {
|
||||
c.to_ascii_uppercase()
|
||||
}
|
||||
}
|
||||
|
||||
impl StrMapSimple for Rfc1459Strict {
|
||||
fn map_char(&self, c: char) -> char {
|
||||
match c {
|
||||
'[' => '{',
|
||||
'\\' => '|',
|
||||
']' => '}',
|
||||
_ => Ascii.map_char(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StrMapSimple for Rfc1459 {
|
||||
fn map_char(&self, c: char) -> char {
|
||||
if c == '~' {
|
||||
'^'
|
||||
} else {
|
||||
Rfc1459Strict.map_char(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user