Auto merge of #108538 - matthiaskrgr:rollup-vw6h5ea, r=matthiaskrgr

Rollup of 8 pull requests

Successful merges:

 - #104265 (Move IpAddr, SocketAddr and V4+V6 related types to `core`)
 - #107110 ([stdio][windows] Use MBTWC and WCTMB)
 - #108308 (Allow building serde and serde_derive in parallel)
 - #108363 (Move the unused extern crate check back to the resolver.)
 - #108519 (Bages for easy access links to Rust community)
 - #108522 (Commit some new solver tests)
 - #108523 (Avoid `&str` to `String` conversions)
 - #108533 (diagnostics: avoid querying `associated_item` in the resolver)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2023-02-27 18:02:10 +00:00
commit 7281249a19
50 changed files with 4449 additions and 4024 deletions

View File

@ -1,5 +1,7 @@
# The Rust Programming Language
[![Rust Community](https://img.shields.io/badge/Rust_Community%20-Join_us-brightgreen?style=plastic&logo=rust)](https://www.rust-lang.org/community)
This is the main source code repository for [Rust]. It contains the compiler,
standard library, and documentation.

View File

@ -386,7 +386,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
).span_suggestion_verbose(
lhs.span.shrink_to_lo(),
"you might have meant to introduce a new binding",
"let ".to_string(),
"let ",
Applicability::MachineApplicable,
).emit();
}

View File

@ -467,7 +467,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
err.span_suggestion_verbose(
span.shrink_to_lo(),
"consider borrowing here",
"&".to_string(),
'&',
Applicability::MaybeIncorrect,
);
}

View File

@ -385,7 +385,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
err.span_suggestion_verbose(
local_decl.source_info.span.shrink_to_lo(),
"consider changing this to be mutable",
"mut ".to_string(),
"mut ",
Applicability::MachineApplicable,
);
let tcx = self.infcx.tcx;

View File

@ -62,14 +62,6 @@ hir_analysis_manual_implementation =
hir_analysis_substs_on_overridden_impl = could not resolve substs on overridden impl
hir_analysis_unused_extern_crate =
unused extern crate
.suggestion = remove it
hir_analysis_extern_crate_not_idiomatic =
`extern crate` is not idiomatic in the new edition
.suggestion = convert it to a `{$msg_code}`
hir_analysis_trait_object_declared_with_no_traits =
at least one trait is required for an object type
.alias_span = this alias does not contain a trait

View File

@ -1,12 +1,8 @@
use crate::errors::{ExternCrateNotIdiomatic, UnusedExternCrate};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::unord::UnordSet;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::def_id::LocalDefId;
use rustc_middle::ty::TyCtxt;
use rustc_session::lint;
use rustc_span::{Span, Symbol};
pub fn check_crate(tcx: TyCtxt<'_>) {
let mut used_trait_imports: UnordSet<LocalDefId> = Default::default();
@ -43,131 +39,4 @@ pub fn check_crate(tcx: TyCtxt<'_>) {
|lint| lint,
);
}
unused_crates_lint(tcx);
}
fn unused_crates_lint(tcx: TyCtxt<'_>) {
let lint = lint::builtin::UNUSED_EXTERN_CRATES;
// Collect first the crates that are completely unused. These we
// can always suggest removing (no matter which edition we are
// in).
let unused_extern_crates: FxHashMap<LocalDefId, Span> = tcx
.maybe_unused_extern_crates(())
.iter()
.filter(|&&(def_id, _)| {
tcx.extern_mod_stmt_cnum(def_id).map_or(true, |cnum| {
!tcx.is_compiler_builtins(cnum)
&& !tcx.is_panic_runtime(cnum)
&& !tcx.has_global_allocator(cnum)
&& !tcx.has_panic_handler(cnum)
})
})
.cloned()
.collect();
// Collect all the extern crates (in a reliable order).
let mut crates_to_lint = vec![];
for id in tcx.hir().items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::ExternCrate) {
let item = tcx.hir().item(id);
if let hir::ItemKind::ExternCrate(orig_name) = item.kind {
crates_to_lint.push(ExternCrateToLint {
def_id: item.owner_id.to_def_id(),
span: item.span,
orig_name,
warn_if_unused: !item.ident.as_str().starts_with('_'),
});
}
}
}
let extern_prelude = &tcx.resolutions(()).extern_prelude;
for extern_crate in &crates_to_lint {
let def_id = extern_crate.def_id.expect_local();
let item = tcx.hir().expect_item(def_id);
// If the crate is fully unused, we suggest removing it altogether.
// We do this in any edition.
if extern_crate.warn_if_unused {
if let Some(&span) = unused_extern_crates.get(&def_id) {
// Removal suggestion span needs to include attributes (Issue #54400)
let id = tcx.hir().local_def_id_to_hir_id(def_id);
let span_with_attrs = tcx
.hir()
.attrs(id)
.iter()
.map(|attr| attr.span)
.fold(span, |acc, attr_span| acc.to(attr_span));
tcx.emit_spanned_lint(lint, id, span, UnusedExternCrate { span: span_with_attrs });
continue;
}
}
// If we are not in Rust 2018 edition, then we don't make any further
// suggestions.
if !tcx.sess.rust_2018() {
continue;
}
// If the extern crate isn't in the extern prelude,
// there is no way it can be written as a `use`.
let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name);
if !extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
continue;
}
// If the extern crate is renamed, then we cannot suggest replacing it with a use as this
// would not insert the new name into the prelude, where other imports in the crate may be
// expecting it.
if extern_crate.orig_name.is_some() {
continue;
}
let id = tcx.hir().local_def_id_to_hir_id(def_id);
// If the extern crate has any attributes, they may have funky
// semantics we can't faithfully represent using `use` (most
// notably `#[macro_use]`). Ignore it.
if !tcx.hir().attrs(id).is_empty() {
continue;
}
let base_replacement = match extern_crate.orig_name {
Some(orig_name) => format!("use {} as {};", orig_name, item.ident.name),
None => format!("use {};", item.ident.name),
};
let vis = tcx.sess.source_map().span_to_snippet(item.vis_span).unwrap_or_default();
let add_vis = |to| if vis.is_empty() { to } else { format!("{} {}", vis, to) };
tcx.emit_spanned_lint(
lint,
id,
extern_crate.span,
ExternCrateNotIdiomatic {
span: extern_crate.span,
msg_code: add_vis("use".to_string()),
suggestion_code: add_vis(base_replacement),
},
);
}
}
struct ExternCrateToLint {
/// `DefId` of the extern crate
def_id: DefId,
/// span from the item
span: Span,
/// if `Some`, then this is renamed (`extern crate orig_name as
/// crate_name`), and -- perhaps surprisingly -- this stores the
/// *original* name (`item.name` will contain the new name)
orig_name: Option<Symbol>,
/// if `false`, the original name started with `_`, so we shouldn't lint
/// about it going unused (but we should still emit idiom lints).
warn_if_unused: bool,
}

View File

@ -5,7 +5,7 @@ use rustc_errors::{
error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, Handler, IntoDiagnostic,
MultiSpan,
};
use rustc_macros::{Diagnostic, LintDiagnostic};
use rustc_macros::Diagnostic;
use rustc_middle::ty::Ty;
use rustc_span::{symbol::Ident, Span, Symbol};
@ -247,26 +247,6 @@ pub struct SubstsOnOverriddenImpl {
pub span: Span,
}
#[derive(LintDiagnostic)]
#[diag(hir_analysis_unused_extern_crate)]
pub struct UnusedExternCrate {
#[suggestion(applicability = "machine-applicable", code = "")]
pub span: Span,
}
#[derive(LintDiagnostic)]
#[diag(hir_analysis_extern_crate_not_idiomatic)]
pub struct ExternCrateNotIdiomatic {
#[suggestion(
style = "short",
applicability = "machine-applicable",
code = "{suggestion_code}"
)]
pub span: Span,
pub msg_code: String,
pub suggestion_code: String,
}
#[derive(Diagnostic)]
#[diag(hir_analysis_const_impl_for_non_const_trait)]
pub struct ConstImplForNonConstTrait {

View File

@ -893,6 +893,23 @@ pub trait LintContext: Sized {
BuiltinLintDiagnostics::ByteSliceInPackedStructWithDerive => {
db.help("consider implementing the trait by hand, or remove the `packed` attribute");
}
BuiltinLintDiagnostics::UnusedExternCrate { removal_span }=> {
db.span_suggestion(
removal_span,
"remove it",
"",
Applicability::MachineApplicable,
);
}
BuiltinLintDiagnostics::ExternCrateNotIdiomatic { vis_span, ident_span }=> {
let suggestion_span = vis_span.between(ident_span);
db.span_suggestion_verbose(
suggestion_span,
"convert it to a `use`",
if vis_span.is_empty() { "use " } else { " use " },
Applicability::MachineApplicable,
);
}
}
// Rewrap `db`, and pass control to the user.
decorate(db)

View File

@ -522,6 +522,13 @@ pub enum BuiltinLintDiagnostics {
is_formatting_arg: bool,
},
ByteSliceInPackedStructWithDerive,
UnusedExternCrate {
removal_span: Span,
},
ExternCrateNotIdiomatic {
vis_span: Span,
ident_span: Span,
},
}
/// Lints that are buffered up early on in the `Session` before the

View File

@ -1830,9 +1830,6 @@ rustc_queries! {
query maybe_unused_trait_imports(_: ()) -> &'tcx FxIndexSet<LocalDefId> {
desc { "fetching potentially unused trait imports" }
}
query maybe_unused_extern_crates(_: ()) -> &'tcx [(LocalDefId, Span)] {
desc { "looking up all possibly unused extern crates" }
}
query names_imported_by_glob_use(def_id: LocalDefId) -> &'tcx FxHashSet<Symbol> {
desc { |tcx| "finding names imported by glob use for `{}`", tcx.def_path_str(def_id.to_def_id()) }
}

View File

@ -2487,8 +2487,6 @@ pub fn provide(providers: &mut ty::query::Providers) {
|tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]);
providers.maybe_unused_trait_imports =
|tcx, ()| &tcx.resolutions(()).maybe_unused_trait_imports;
providers.maybe_unused_extern_crates =
|tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..];
providers.names_imported_by_glob_use = |tcx, id| {
tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default())
};

View File

@ -165,12 +165,8 @@ pub struct ResolverGlobalCtxt {
pub effective_visibilities: EffectiveVisibilities,
pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
pub maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
pub reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
/// Extern prelude entries. The value is `true` if the entry was introduced
/// via `extern crate` item and not `--extern` option or compiler built-in.
pub extern_prelude: FxHashMap<Symbol, bool>,
pub main_def: Option<MainDefinition>,
pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
/// A list of proc macro LocalDefIds, written out in the order in which

View File

@ -29,11 +29,12 @@ use crate::Resolver;
use rustc_ast as ast;
use rustc_ast::visit::{self, Visitor};
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
use rustc_data_structures::unord::UnordSet;
use rustc_errors::{pluralize, MultiSpan};
use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS};
use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES, UNUSED_IMPORTS};
use rustc_session::lint::BuiltinLintDiagnostics;
use rustc_span::symbol::Ident;
use rustc_span::{Span, DUMMY_SP};
struct UnusedImport<'a> {
@ -53,11 +54,28 @@ struct UnusedImportCheckVisitor<'a, 'b, 'tcx> {
r: &'a mut Resolver<'b, 'tcx>,
/// All the (so far) unused imports, grouped path list
unused_imports: FxIndexMap<ast::NodeId, UnusedImport<'a>>,
extern_crate_items: Vec<ExternCrateToLint>,
base_use_tree: Option<&'a ast::UseTree>,
base_id: ast::NodeId,
item_span: Span,
}
struct ExternCrateToLint {
id: ast::NodeId,
/// Span from the item
span: Span,
/// Span to use to suggest complete removal.
span_with_attributes: Span,
/// Span of the visibility, if any.
vis_span: Span,
/// Whether the item has attrs.
has_attrs: bool,
/// Name used to refer to the crate.
ident: Ident,
/// Whether the statement renames the crate `extern crate orig_name as new_name;`.
renames: bool,
}
impl<'a, 'b, 'tcx> UnusedImportCheckVisitor<'a, 'b, 'tcx> {
// We have information about whether `use` (import) items are actually
// used now. If an import is not used at all, we signal a lint error.
@ -96,18 +114,27 @@ impl<'a, 'b, 'tcx> UnusedImportCheckVisitor<'a, 'b, 'tcx> {
impl<'a, 'b, 'tcx> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b, 'tcx> {
fn visit_item(&mut self, item: &'a ast::Item) {
self.item_span = item.span_with_attributes();
// Ignore is_public import statements because there's no way to be sure
// whether they're used or not. Also ignore imports with a dummy span
// because this means that they were generated in some fashion by the
// compiler and we don't need to consider them.
if let ast::ItemKind::Use(..) = item.kind {
if item.vis.kind.is_pub() || item.span.is_dummy() {
return;
match item.kind {
// Ignore is_public import statements because there's no way to be sure
// whether they're used or not. Also ignore imports with a dummy span
// because this means that they were generated in some fashion by the
// compiler and we don't need to consider them.
ast::ItemKind::Use(..) if item.vis.kind.is_pub() || item.span.is_dummy() => return,
ast::ItemKind::ExternCrate(orig_name) => {
self.extern_crate_items.push(ExternCrateToLint {
id: item.id,
span: item.span,
vis_span: item.vis.span,
span_with_attributes: item.span_with_attributes(),
has_attrs: !item.attrs.is_empty(),
ident: item.ident,
renames: orig_name.is_some(),
});
}
_ => {}
}
self.item_span = item.span_with_attributes();
visit::walk_item(self, item);
}
@ -224,6 +251,9 @@ fn calc_unused_spans(
impl Resolver<'_, '_> {
pub(crate) fn check_unused(&mut self, krate: &ast::Crate) {
let tcx = self.tcx;
let mut maybe_unused_extern_crates = FxHashMap::default();
for import in self.potentially_unused_imports.iter() {
match import.kind {
_ if import.used.get()
@ -246,7 +276,14 @@ impl Resolver<'_, '_> {
}
ImportKind::ExternCrate { id, .. } => {
let def_id = self.local_def_id(id);
self.maybe_unused_extern_crates.push((def_id, import.span));
if self.extern_crate_map.get(&def_id).map_or(true, |&cnum| {
!tcx.is_compiler_builtins(cnum)
&& !tcx.is_panic_runtime(cnum)
&& !tcx.has_global_allocator(cnum)
&& !tcx.has_panic_handler(cnum)
}) {
maybe_unused_extern_crates.insert(id, import.span);
}
}
ImportKind::MacroUse => {
let msg = "unused `#[macro_use]` import";
@ -259,6 +296,7 @@ impl Resolver<'_, '_> {
let mut visitor = UnusedImportCheckVisitor {
r: self,
unused_imports: Default::default(),
extern_crate_items: Default::default(),
base_use_tree: None,
base_id: ast::DUMMY_NODE_ID,
item_span: DUMMY_SP,
@ -290,7 +328,7 @@ impl Resolver<'_, '_> {
let ms = MultiSpan::from_spans(spans.clone());
let mut span_snippets = spans
.iter()
.filter_map(|s| match visitor.r.tcx.sess.source_map().span_to_snippet(*s) {
.filter_map(|s| match tcx.sess.source_map().span_to_snippet(*s) {
Ok(s) => Some(format!("`{}`", s)),
_ => None,
})
@ -317,7 +355,7 @@ impl Resolver<'_, '_> {
// If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
// attribute; however, if not, suggest adding the attribute. There is no way to
// retrieve attributes here because we do not have a `TyCtxt` yet.
let test_module_span = if visitor.r.tcx.sess.opts.test {
let test_module_span = if tcx.sess.opts.test {
None
} else {
let parent_module = visitor.r.get_nearest_non_block_module(
@ -346,5 +384,74 @@ impl Resolver<'_, '_> {
BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes, test_module_span),
);
}
for extern_crate in visitor.extern_crate_items {
let warn_if_unused = !extern_crate.ident.name.as_str().starts_with('_');
// If the crate is fully unused, we suggest removing it altogether.
// We do this in any edition.
if warn_if_unused {
if let Some(&span) = maybe_unused_extern_crates.get(&extern_crate.id) {
visitor.r.lint_buffer.buffer_lint_with_diagnostic(
UNUSED_EXTERN_CRATES,
extern_crate.id,
span,
"unused extern crate",
BuiltinLintDiagnostics::UnusedExternCrate {
removal_span: extern_crate.span_with_attributes,
},
);
continue;
}
}
// If we are not in Rust 2018 edition, then we don't make any further
// suggestions.
if !tcx.sess.rust_2018() {
continue;
}
// If the extern crate has any attributes, they may have funky
// semantics we can't faithfully represent using `use` (most
// notably `#[macro_use]`). Ignore it.
if extern_crate.has_attrs {
continue;
}
// If the extern crate is renamed, then we cannot suggest replacing it with a use as this
// would not insert the new name into the prelude, where other imports in the crate may be
// expecting it.
if extern_crate.renames {
continue;
}
// If the extern crate isn't in the extern prelude,
// there is no way it can be written as a `use`.
if !visitor
.r
.extern_prelude
.get(&extern_crate.ident)
.map_or(false, |entry| !entry.introduced_by_item)
{
continue;
}
let vis_span = extern_crate
.vis_span
.find_ancestor_inside(extern_crate.span)
.unwrap_or(extern_crate.vis_span);
let ident_span = extern_crate
.ident
.span
.find_ancestor_inside(extern_crate.span)
.unwrap_or(extern_crate.ident.span);
visitor.r.lint_buffer.buffer_lint_with_diagnostic(
UNUSED_EXTERN_CRATES,
extern_crate.id,
extern_crate.span,
"`extern crate` is not idiomatic in the new edition",
BuiltinLintDiagnostics::ExternCrateNotIdiomatic { vis_span, ident_span },
);
}
}
}

View File

@ -189,7 +189,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}
let container = match parent.kind {
ModuleKind::Def(kind, _, _) => self.tcx.def_kind_descr(kind, parent.def_id()),
// Avoid using TyCtxt::def_kind_descr in the resolver, because it
// indirectly *calls* the resolver, and would cause a query cycle.
ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
ModuleKind::Block => "block",
};
@ -1804,7 +1806,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
found("module")
} else {
match binding.res() {
Res::Def(kind, id) => found(self.tcx.def_kind_descr(kind, id)),
// Avoid using TyCtxt::def_kind_descr in the resolver, because it
// indirectly *calls* the resolver, and would cause a query cycle.
Res::Def(kind, id) => found(kind.descr(id)),
_ => found(ns_to_try.descr()),
}
}

View File

@ -946,7 +946,6 @@ pub struct Resolver<'a, 'tcx> {
has_pub_restricted: bool,
used_imports: FxHashSet<NodeId>,
maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
/// Privacy errors are delayed until the end in order to deduplicate them.
privacy_errors: Vec<PrivacyError<'a>>,
@ -1284,7 +1283,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
has_pub_restricted: false,
used_imports: FxHashSet::default(),
maybe_unused_trait_imports: Default::default(),
maybe_unused_extern_crates: Vec::new(),
privacy_errors: Vec::new(),
ambiguity_errors: Vec::new(),
@ -1400,7 +1398,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let extern_crate_map = self.extern_crate_map;
let reexport_map = self.reexport_map;
let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
let glob_map = self.glob_map;
let main_def = self.main_def;
let confused_type_with_std_module = self.confused_type_with_std_module;
@ -1414,12 +1411,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
reexport_map,
glob_map,
maybe_unused_trait_imports,
maybe_unused_extern_crates,
extern_prelude: self
.extern_prelude
.iter()
.map(|(ident, entry)| (ident.name, entry.introduced_by_item))
.collect(),
main_def,
trait_impls: self.trait_impls,
proc_macros,

View File

@ -124,6 +124,8 @@
#![feature(const_inherent_unchecked_arith)]
#![feature(const_int_unchecked_arith)]
#![feature(const_intrinsic_forget)]
#![feature(const_ipv4)]
#![feature(const_ipv6)]
#![feature(const_likely)]
#![feature(const_maybe_uninit_uninit_array)]
#![feature(const_maybe_uninit_as_mut_ptr)]
@ -179,6 +181,7 @@
#![feature(const_slice_index)]
#![feature(const_is_char_boundary)]
#![feature(const_cstr_methods)]
#![feature(ip)]
#![feature(is_ascii_octdigit)]
//
// Language features:
@ -349,6 +352,7 @@ pub mod cell;
pub mod char;
pub mod ffi;
pub mod iter;
pub mod net;
pub mod option;
pub mod panic;
pub mod panicking;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,24 @@
//! Networking primitives for IP communication.
//!
//! This module provides types for IP and socket addresses.
//!
//! # Organization
//!
//! * [`IpAddr`] represents IP addresses of either IPv4 or IPv6; [`Ipv4Addr`] and
//! [`Ipv6Addr`] are respectively IPv4 and IPv6 addresses
//! * [`SocketAddr`] represents socket addresses of either IPv4 or IPv6; [`SocketAddrV4`]
//! and [`SocketAddrV6`] are respectively IPv4 and IPv6 socket addresses
#![unstable(feature = "ip_in_core", issue = "108443")]
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::ip_addr::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::parser::AddrParseError;
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::socket_addr::{SocketAddr, SocketAddrV4, SocketAddrV6};
mod display_buffer;
mod ip_addr;
mod parser;
mod socket_addr;

View File

@ -3,9 +3,7 @@
//! This module is "publicly exported" through the `FromStr` implementations
//! below.
#[cfg(test)]
mod tests;
use crate::convert::TryInto;
use crate::error::Error;
use crate::fmt;
use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};

View File

@ -0,0 +1,664 @@
use crate::cmp::Ordering;
use crate::fmt::{self, Write};
use crate::hash;
use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use super::display_buffer::DisplayBuffer;
/// An internet socket address, either IPv4 or IPv6.
///
/// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
/// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
/// [`SocketAddrV6`]'s respective documentation for more details.
///
/// The size of a `SocketAddr` instance may vary depending on the target operating
/// system.
///
/// [IP address]: IpAddr
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
///
/// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
/// assert_eq!(socket.port(), 8080);
/// assert_eq!(socket.is_ipv4(), true);
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum SocketAddr {
/// An IPv4 socket address.
#[stable(feature = "rust1", since = "1.0.0")]
V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
/// An IPv6 socket address.
#[stable(feature = "rust1", since = "1.0.0")]
V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
}
/// An IPv4 socket address.
///
/// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
/// stated in [IETF RFC 793].
///
/// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
///
/// The size of a `SocketAddrV4` struct may vary depending on the target operating
/// system. Do not assume that this type has the same memory layout as the underlying
/// system representation.
///
/// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
/// [`IPv4` address]: Ipv4Addr
///
/// # Examples
///
/// ```
/// use std::net::{Ipv4Addr, SocketAddrV4};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
///
/// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
/// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
/// assert_eq!(socket.port(), 8080);
/// ```
#[derive(Copy, Clone, Eq, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SocketAddrV4 {
ip: Ipv4Addr,
port: u16,
}
/// An IPv6 socket address.
///
/// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
/// as fields containing the traffic class, the flow label, and a scope identifier
/// (see [IETF RFC 2553, Section 3.3] for more details).
///
/// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
///
/// The size of a `SocketAddrV6` struct may vary depending on the target operating
/// system. Do not assume that this type has the same memory layout as the underlying
/// system representation.
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
/// [`IPv6` address]: Ipv6Addr
///
/// # Examples
///
/// ```
/// use std::net::{Ipv6Addr, SocketAddrV6};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
///
/// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
/// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
/// assert_eq!(socket.port(), 8080);
/// ```
#[derive(Copy, Clone, Eq, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SocketAddrV6 {
ip: Ipv6Addr,
port: u16,
flowinfo: u32,
scope_id: u32,
}
impl SocketAddr {
/// Creates a new socket address from an [IP address] and a port number.
///
/// [IP address]: IpAddr
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
/// assert_eq!(socket.port(), 8080);
/// ```
#[stable(feature = "ip_addr", since = "1.7.0")]
#[must_use]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn new(ip: IpAddr, port: u16) -> SocketAddr {
match ip {
IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
}
}
/// Returns the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
/// ```
#[must_use]
#[stable(feature = "ip_addr", since = "1.7.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn ip(&self) -> IpAddr {
match *self {
SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
}
}
/// Changes the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
/// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_ip(&mut self, new_ip: IpAddr) {
// `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
match (self, new_ip) {
(&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
(&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
(self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
}
}
/// Returns the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.port(), 8080);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn port(&self) -> u16 {
match *self {
SocketAddr::V4(ref a) => a.port(),
SocketAddr::V6(ref a) => a.port(),
}
}
/// Changes the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// socket.set_port(1025);
/// assert_eq!(socket.port(), 1025);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_port(&mut self, new_port: u16) {
match *self {
SocketAddr::V4(ref mut a) => a.set_port(new_port),
SocketAddr::V6(ref mut a) => a.set_port(new_port),
}
}
/// Returns [`true`] if the [IP address] in this `SocketAddr` is an
/// [`IPv4` address], and [`false`] otherwise.
///
/// [IP address]: IpAddr
/// [`IPv4` address]: IpAddr::V4
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.is_ipv4(), true);
/// assert_eq!(socket.is_ipv6(), false);
/// ```
#[must_use]
#[stable(feature = "sockaddr_checker", since = "1.16.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn is_ipv4(&self) -> bool {
matches!(*self, SocketAddr::V4(_))
}
/// Returns [`true`] if the [IP address] in this `SocketAddr` is an
/// [`IPv6` address], and [`false`] otherwise.
///
/// [IP address]: IpAddr
/// [`IPv6` address]: IpAddr::V6
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
/// assert_eq!(socket.is_ipv4(), false);
/// assert_eq!(socket.is_ipv6(), true);
/// ```
#[must_use]
#[stable(feature = "sockaddr_checker", since = "1.16.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn is_ipv6(&self) -> bool {
matches!(*self, SocketAddr::V6(_))
}
}
impl SocketAddrV4 {
/// Creates a new socket address from an [`IPv4` address] and a port number.
///
/// [`IPv4` address]: Ipv4Addr
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
SocketAddrV4 { ip, port }
}
/// Returns the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn ip(&self) -> &Ipv4Addr {
&self.ip
}
/// Changes the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
/// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
self.ip = new_ip;
}
/// Returns the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// assert_eq!(socket.port(), 8080);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn port(&self) -> u16 {
self.port
}
/// Changes the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// socket.set_port(4242);
/// assert_eq!(socket.port(), 4242);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_port(&mut self, new_port: u16) {
self.port = new_port;
}
}
impl SocketAddrV6 {
/// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
/// and the `flowinfo` and `scope_id` fields.
///
/// For more information on the meaning and layout of the `flowinfo` and `scope_id`
/// parameters, see [IETF RFC 2553, Section 3.3].
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
/// [`IPv6` address]: Ipv6Addr
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
SocketAddrV6 { ip, port, flowinfo, scope_id }
}
/// Returns the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn ip(&self) -> &Ipv6Addr {
&self.ip
}
/// Changes the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
/// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
self.ip = new_ip;
}
/// Returns the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// assert_eq!(socket.port(), 8080);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn port(&self) -> u16 {
self.port
}
/// Changes the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// socket.set_port(4242);
/// assert_eq!(socket.port(), 4242);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_port(&mut self, new_port: u16) {
self.port = new_port;
}
/// Returns the flow information associated with this address.
///
/// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
/// as specified in [IETF RFC 2553, Section 3.3].
/// It combines information about the flow label and the traffic class as specified
/// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
/// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
/// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
/// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
/// assert_eq!(socket.flowinfo(), 10);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn flowinfo(&self) -> u32 {
self.flowinfo
}
/// Changes the flow information associated with this socket address.
///
/// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
/// socket.set_flowinfo(56);
/// assert_eq!(socket.flowinfo(), 56);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
self.flowinfo = new_flowinfo;
}
/// Returns the scope ID associated with this address.
///
/// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
/// as specified in [IETF RFC 2553, Section 3.3].
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
/// assert_eq!(socket.scope_id(), 78);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn scope_id(&self) -> u32 {
self.scope_id
}
/// Changes the scope ID associated with this socket address.
///
/// See [`SocketAddrV6::scope_id`]'s documentation for more details.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
/// socket.set_scope_id(42);
/// assert_eq!(socket.scope_id(), 42);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_scope_id(&mut self, new_scope_id: u32) {
self.scope_id = new_scope_id;
}
}
#[stable(feature = "ip_from_ip", since = "1.16.0")]
impl From<SocketAddrV4> for SocketAddr {
/// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
fn from(sock4: SocketAddrV4) -> SocketAddr {
SocketAddr::V4(sock4)
}
}
#[stable(feature = "ip_from_ip", since = "1.16.0")]
impl From<SocketAddrV6> for SocketAddr {
/// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
fn from(sock6: SocketAddrV6) -> SocketAddr {
SocketAddr::V6(sock6)
}
}
#[stable(feature = "addr_from_into_ip", since = "1.17.0")]
impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
/// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
///
/// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`]
/// and creates a [`SocketAddr::V6`] for an [`IpAddr::V6`].
///
/// `u16` is treated as port of the newly created [`SocketAddr`].
fn from(pieces: (I, u16)) -> SocketAddr {
SocketAddr::new(pieces.0.into(), pieces.1)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for SocketAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
SocketAddr::V4(ref a) => a.fmt(f),
SocketAddr::V6(ref a) => a.fmt(f),
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for SocketAddr {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for SocketAddrV4 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// If there are no alignment requirements, write the socket address directly to `f`.
// Otherwise, write it to a local buffer and then use `f.pad`.
if f.precision().is_none() && f.width().is_none() {
write!(f, "{}:{}", self.ip(), self.port())
} else {
const LONGEST_IPV4_SOCKET_ADDR: &str = "255.255.255.255:65536";
let mut buf = DisplayBuffer::<{ LONGEST_IPV4_SOCKET_ADDR.len() }>::new();
// Buffer is long enough for the longest possible IPv4 socket address, so this should never fail.
write!(buf, "{}:{}", self.ip(), self.port()).unwrap();
f.pad(buf.as_str())
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for SocketAddrV4 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for SocketAddrV6 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// If there are no alignment requirements, write the socket address directly to `f`.
// Otherwise, write it to a local buffer and then use `f.pad`.
if f.precision().is_none() && f.width().is_none() {
match self.scope_id() {
0 => write!(f, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
} else {
const LONGEST_IPV6_SOCKET_ADDR: &str =
"[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%4294967296]:65536";
let mut buf = DisplayBuffer::<{ LONGEST_IPV6_SOCKET_ADDR.len() }>::new();
match self.scope_id() {
0 => write!(buf, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(buf, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
// Buffer is long enough for the longest possible IPv6 socket address, so this should never fail.
.unwrap();
f.pad(buf.as_str())
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for SocketAddrV6 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl PartialOrd for SocketAddrV4 {
fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl PartialOrd for SocketAddrV6 {
fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl Ord for SocketAddrV4 {
fn cmp(&self, other: &SocketAddrV4) -> Ordering {
self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl Ord for SocketAddrV6 {
fn cmp(&self, other: &SocketAddrV6) -> Ordering {
self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for SocketAddrV4 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.port, self.ip).hash(s)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for SocketAddrV6 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.port, &self.ip, self.flowinfo, self.scope_id).hash(s)
}
}

View File

@ -66,6 +66,7 @@
#![feature(try_trait_v2)]
#![feature(slice_internals)]
#![feature(slice_partition_dedup)]
#![feature(ip)]
#![feature(iter_advance_by)]
#![feature(iter_array_chunks)]
#![feature(iter_collect_into)]
@ -77,6 +78,9 @@
#![feature(iter_repeat_n)]
#![feature(iterator_try_collect)]
#![feature(iterator_try_reduce)]
#![feature(const_ip)]
#![feature(const_ipv4)]
#![feature(const_ipv6)]
#![feature(const_mut_refs)]
#![feature(const_pin)]
#![feature(const_waker)]
@ -135,6 +139,7 @@ mod lazy;
mod macros;
mod manually_drop;
mod mem;
mod net;
mod nonzero;
mod num;
mod ops;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
use core::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
mod ip_addr;
mod parser;
mod socket_addr;
pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr {
SocketAddr::V4(SocketAddrV4::new(a, p))
}
pub fn sa6(a: Ipv6Addr, p: u16) -> SocketAddr {
SocketAddr::V6(SocketAddrV6::new(a, p, 0, 0))
}

View File

@ -1,6 +1,6 @@
// FIXME: These tests are all excellent candidates for AFL fuzz testing
use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use crate::str::FromStr;
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use core::str::FromStr;
const PORT: u16 = 8080;
const SCOPE_ID: u32 = 1337;

View File

@ -0,0 +1,233 @@
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
#[test]
fn ipv4_socket_addr_to_string() {
// Shortest possible IPv4 length.
assert_eq!(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0).to_string(), "0.0.0.0:0");
// Longest possible IPv4 length.
assert_eq!(
SocketAddrV4::new(Ipv4Addr::new(255, 255, 255, 255), u16::MAX).to_string(),
"255.255.255.255:65535"
);
// Test padding.
assert_eq!(
&format!("{:16}", SocketAddrV4::new(Ipv4Addr::new(1, 1, 1, 1), 53)),
"1.1.1.1:53 "
);
assert_eq!(
&format!("{:>16}", SocketAddrV4::new(Ipv4Addr::new(1, 1, 1, 1), 53)),
" 1.1.1.1:53"
);
}
#[test]
fn ipv6_socket_addr_to_string() {
// IPv4-mapped address.
assert_eq!(
SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280), 8080, 0, 0)
.to_string(),
"[::ffff:192.0.2.128]:8080"
);
// IPv4-compatible address.
assert_eq!(
SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x280), 8080, 0, 0).to_string(),
"[::192.0.2.128]:8080"
);
// IPv6 address with no zero segments.
assert_eq!(
SocketAddrV6::new(Ipv6Addr::new(8, 9, 10, 11, 12, 13, 14, 15), 80, 0, 0).to_string(),
"[8:9:a:b:c:d:e:f]:80"
);
// Shortest possible IPv6 length.
assert_eq!(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0).to_string(), "[::]:0");
// Longest possible IPv6 length.
assert_eq!(
SocketAddrV6::new(
Ipv6Addr::new(0x1111, 0x2222, 0x3333, 0x4444, 0x5555, 0x6666, 0x7777, 0x8888),
u16::MAX,
u32::MAX,
u32::MAX,
)
.to_string(),
"[1111:2222:3333:4444:5555:6666:7777:8888%4294967295]:65535"
);
// Test padding.
assert_eq!(
&format!("{:22}", SocketAddrV6::new(Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8), 9, 0, 0)),
"[1:2:3:4:5:6:7:8]:9 "
);
assert_eq!(
&format!("{:>22}", SocketAddrV6::new(Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8), 9, 0, 0)),
" [1:2:3:4:5:6:7:8]:9"
);
}
#[test]
fn set_ip() {
fn ip4(low: u8) -> Ipv4Addr {
Ipv4Addr::new(77, 88, 21, low)
}
fn ip6(low: u16) -> Ipv6Addr {
Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low)
}
let mut v4 = SocketAddrV4::new(ip4(11), 80);
assert_eq!(v4.ip(), &ip4(11));
v4.set_ip(ip4(12));
assert_eq!(v4.ip(), &ip4(12));
let mut addr = SocketAddr::V4(v4);
assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
addr.set_ip(IpAddr::V4(ip4(13)));
assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
addr.set_ip(IpAddr::V6(ip6(14)));
assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
assert_eq!(v6.ip(), &ip6(1));
v6.set_ip(ip6(2));
assert_eq!(v6.ip(), &ip6(2));
let mut addr = SocketAddr::V6(v6);
assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
addr.set_ip(IpAddr::V6(ip6(3)));
assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
addr.set_ip(IpAddr::V4(ip4(4)));
assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
}
#[test]
fn set_port() {
let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
assert_eq!(v4.port(), 80);
v4.set_port(443);
assert_eq!(v4.port(), 443);
let mut addr = SocketAddr::V4(v4);
assert_eq!(addr.port(), 443);
addr.set_port(8080);
assert_eq!(addr.port(), 8080);
let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
assert_eq!(v6.port(), 80);
v6.set_port(443);
assert_eq!(v6.port(), 443);
let mut addr = SocketAddr::V6(v6);
assert_eq!(addr.port(), 443);
addr.set_port(8080);
assert_eq!(addr.port(), 8080);
}
#[test]
fn set_flowinfo() {
let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
assert_eq!(v6.flowinfo(), 10);
v6.set_flowinfo(20);
assert_eq!(v6.flowinfo(), 20);
}
#[test]
fn set_scope_id() {
let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
assert_eq!(v6.scope_id(), 10);
v6.set_scope_id(20);
assert_eq!(v6.scope_id(), 20);
}
#[test]
fn is_v4() {
let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
assert!(v4.is_ipv4());
assert!(!v4.is_ipv6());
}
#[test]
fn is_v6() {
let v6 = SocketAddr::V6(SocketAddrV6::new(
Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1),
80,
10,
0,
));
assert!(!v6.is_ipv4());
assert!(v6.is_ipv6());
}
#[test]
fn socket_v4_to_str() {
let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080);
assert_eq!(format!("{socket}"), "192.168.0.1:8080");
assert_eq!(format!("{socket:<20}"), "192.168.0.1:8080 ");
assert_eq!(format!("{socket:>20}"), " 192.168.0.1:8080");
assert_eq!(format!("{socket:^20}"), " 192.168.0.1:8080 ");
assert_eq!(format!("{socket:.10}"), "192.168.0.");
}
#[test]
fn socket_v6_to_str() {
let mut socket = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0);
assert_eq!(format!("{socket}"), "[2a02:6b8:0:1::1]:53");
assert_eq!(format!("{socket:<24}"), "[2a02:6b8:0:1::1]:53 ");
assert_eq!(format!("{socket:>24}"), " [2a02:6b8:0:1::1]:53");
assert_eq!(format!("{socket:^24}"), " [2a02:6b8:0:1::1]:53 ");
assert_eq!(format!("{socket:.15}"), "[2a02:6b8:0:1::");
socket.set_scope_id(5);
assert_eq!(format!("{socket}"), "[2a02:6b8:0:1::1%5]:53");
assert_eq!(format!("{socket:<24}"), "[2a02:6b8:0:1::1%5]:53 ");
assert_eq!(format!("{socket:>24}"), " [2a02:6b8:0:1::1%5]:53");
assert_eq!(format!("{socket:^24}"), " [2a02:6b8:0:1::1%5]:53 ");
assert_eq!(format!("{socket:.18}"), "[2a02:6b8:0:1::1%5");
}
#[test]
fn compare() {
let v4_1 = "224.120.45.1:23456".parse::<SocketAddrV4>().unwrap();
let v4_2 = "224.210.103.5:12345".parse::<SocketAddrV4>().unwrap();
let v4_3 = "224.210.103.5:23456".parse::<SocketAddrV4>().unwrap();
let v6_1 = "[2001:db8:f00::1002]:23456".parse::<SocketAddrV6>().unwrap();
let v6_2 = "[2001:db8:f00::2001]:12345".parse::<SocketAddrV6>().unwrap();
let v6_3 = "[2001:db8:f00::2001]:23456".parse::<SocketAddrV6>().unwrap();
// equality
assert_eq!(v4_1, v4_1);
assert_eq!(v6_1, v6_1);
assert_eq!(SocketAddr::V4(v4_1), SocketAddr::V4(v4_1));
assert_eq!(SocketAddr::V6(v6_1), SocketAddr::V6(v6_1));
assert!(v4_1 != v4_2);
assert!(v6_1 != v6_2);
// compare different addresses
assert!(v4_1 < v4_2);
assert!(v6_1 < v6_2);
assert!(v4_2 > v4_1);
assert!(v6_2 > v6_1);
// compare the same address with different ports
assert!(v4_2 < v4_3);
assert!(v6_2 < v6_3);
assert!(v4_3 > v4_2);
assert!(v6_3 > v6_2);
// compare different addresses with the same port
assert!(v4_1 < v4_3);
assert!(v6_1 < v6_3);
assert!(v4_3 > v4_1);
assert!(v6_3 > v6_1);
// compare with an inferred right-hand side
assert_eq!(v4_1, "224.120.45.1:23456".parse().unwrap());
assert_eq!(v6_1, "[2001:db8:f00::1002]:23456".parse().unwrap());
assert_eq!(SocketAddr::V4(v4_1), "224.120.45.1:23456".parse().unwrap());
}

View File

@ -232,6 +232,7 @@
all(target_vendor = "fortanix", target_env = "sgx"),
feature(slice_index_methods, coerce_unsized, sgx_platform)
)]
#![cfg_attr(windows, feature(round_char_boundary))]
//
// Language features:
#![feature(alloc_error_handler)]
@ -287,6 +288,8 @@
#![feature(float_next_up_down)]
#![feature(hasher_prefixfree_extras)]
#![feature(hashmap_internals)]
#![feature(ip)]
#![feature(ip_in_core)]
#![feature(is_some_and)]
#![feature(maybe_uninit_slice)]
#![feature(maybe_uninit_write_slice)]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -26,8 +26,6 @@ use crate::io::{self, ErrorKind};
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::ip_addr::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::parser::AddrParseError;
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::socket_addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
#[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
pub use self::tcp::IntoIncoming;
@ -35,10 +33,10 @@ pub use self::tcp::IntoIncoming;
pub use self::tcp::{Incoming, TcpListener, TcpStream};
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::udp::UdpSocket;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::net::AddrParseError;
mod display_buffer;
mod ip_addr;
mod parser;
mod socket_addr;
mod tcp;
#[cfg(test)]

View File

@ -1,9 +1,7 @@
// Tests for this module
#[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cmp::Ordering;
use crate::fmt::{self, Write};
use crate::hash;
use crate::io;
use crate::iter;
use crate::mem;
@ -15,533 +13,23 @@ use crate::sys_common::net::LookupHost;
use crate::sys_common::{FromInner, IntoInner};
use crate::vec;
use super::display_buffer::DisplayBuffer;
/// An internet socket address, either IPv4 or IPv6.
///
/// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
/// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
/// [`SocketAddrV6`]'s respective documentation for more details.
///
/// The size of a `SocketAddr` instance may vary depending on the target operating
/// system.
///
/// [IP address]: IpAddr
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
///
/// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
/// assert_eq!(socket.port(), 8080);
/// assert_eq!(socket.is_ipv4(), true);
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum SocketAddr {
/// An IPv4 socket address.
#[stable(feature = "rust1", since = "1.0.0")]
V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
/// An IPv6 socket address.
#[stable(feature = "rust1", since = "1.0.0")]
V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
}
/// An IPv4 socket address.
///
/// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
/// stated in [IETF RFC 793].
///
/// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
///
/// The size of a `SocketAddrV4` struct may vary depending on the target operating
/// system. Do not assume that this type has the same memory layout as the underlying
/// system representation.
///
/// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
/// [`IPv4` address]: Ipv4Addr
///
/// # Examples
///
/// ```
/// use std::net::{Ipv4Addr, SocketAddrV4};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
///
/// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
/// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
/// assert_eq!(socket.port(), 8080);
/// ```
#[derive(Copy, Clone, Eq, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SocketAddrV4 {
ip: Ipv4Addr,
port: u16,
}
/// An IPv6 socket address.
///
/// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
/// as fields containing the traffic class, the flow label, and a scope identifier
/// (see [IETF RFC 2553, Section 3.3] for more details).
///
/// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
///
/// The size of a `SocketAddrV6` struct may vary depending on the target operating
/// system. Do not assume that this type has the same memory layout as the underlying
/// system representation.
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
/// [`IPv6` address]: Ipv6Addr
///
/// # Examples
///
/// ```
/// use std::net::{Ipv6Addr, SocketAddrV6};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
///
/// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
/// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
/// assert_eq!(socket.port(), 8080);
/// ```
#[derive(Copy, Clone, Eq, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SocketAddrV6 {
ip: Ipv6Addr,
port: u16,
flowinfo: u32,
scope_id: u32,
}
impl SocketAddr {
/// Creates a new socket address from an [IP address] and a port number.
///
/// [IP address]: IpAddr
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
/// assert_eq!(socket.port(), 8080);
/// ```
#[stable(feature = "ip_addr", since = "1.7.0")]
#[must_use]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn new(ip: IpAddr, port: u16) -> SocketAddr {
match ip {
IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
}
}
/// Returns the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
/// ```
#[must_use]
#[stable(feature = "ip_addr", since = "1.7.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn ip(&self) -> IpAddr {
match *self {
SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
}
}
/// Changes the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
/// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_ip(&mut self, new_ip: IpAddr) {
// `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
match (self, new_ip) {
(&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
(&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
(self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
}
}
/// Returns the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.port(), 8080);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn port(&self) -> u16 {
match *self {
SocketAddr::V4(ref a) => a.port(),
SocketAddr::V6(ref a) => a.port(),
}
}
/// Changes the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// socket.set_port(1025);
/// assert_eq!(socket.port(), 1025);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_port(&mut self, new_port: u16) {
match *self {
SocketAddr::V4(ref mut a) => a.set_port(new_port),
SocketAddr::V6(ref mut a) => a.set_port(new_port),
}
}
/// Returns [`true`] if the [IP address] in this `SocketAddr` is an
/// [`IPv4` address], and [`false`] otherwise.
///
/// [IP address]: IpAddr
/// [`IPv4` address]: IpAddr::V4
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// assert_eq!(socket.is_ipv4(), true);
/// assert_eq!(socket.is_ipv6(), false);
/// ```
#[must_use]
#[stable(feature = "sockaddr_checker", since = "1.16.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn is_ipv4(&self) -> bool {
matches!(*self, SocketAddr::V4(_))
}
/// Returns [`true`] if the [IP address] in this `SocketAddr` is an
/// [`IPv6` address], and [`false`] otherwise.
///
/// [IP address]: IpAddr
/// [`IPv6` address]: IpAddr::V6
///
/// # Examples
///
/// ```
/// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
///
/// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
/// assert_eq!(socket.is_ipv4(), false);
/// assert_eq!(socket.is_ipv6(), true);
/// ```
#[must_use]
#[stable(feature = "sockaddr_checker", since = "1.16.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn is_ipv6(&self) -> bool {
matches!(*self, SocketAddr::V6(_))
}
}
impl SocketAddrV4 {
/// Creates a new socket address from an [`IPv4` address] and a port number.
///
/// [`IPv4` address]: Ipv4Addr
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
SocketAddrV4 { ip, port }
}
/// Returns the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn ip(&self) -> &Ipv4Addr {
&self.ip
}
/// Changes the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
/// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
self.ip = new_ip;
}
/// Returns the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// assert_eq!(socket.port(), 8080);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn port(&self) -> u16 {
self.port
}
/// Changes the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV4, Ipv4Addr};
///
/// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// socket.set_port(4242);
/// assert_eq!(socket.port(), 4242);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_port(&mut self, new_port: u16) {
self.port = new_port;
}
}
impl SocketAddrV6 {
/// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
/// and the `flowinfo` and `scope_id` fields.
///
/// For more information on the meaning and layout of the `flowinfo` and `scope_id`
/// parameters, see [IETF RFC 2553, Section 3.3].
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
/// [`IPv6` address]: Ipv6Addr
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
SocketAddrV6 { ip, port, flowinfo, scope_id }
}
/// Returns the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn ip(&self) -> &Ipv6Addr {
&self.ip
}
/// Changes the IP address associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
/// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
self.ip = new_ip;
}
/// Returns the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// assert_eq!(socket.port(), 8080);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn port(&self) -> u16 {
self.port
}
/// Changes the port number associated with this socket address.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
/// socket.set_port(4242);
/// assert_eq!(socket.port(), 4242);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_port(&mut self, new_port: u16) {
self.port = new_port;
}
/// Returns the flow information associated with this address.
///
/// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
/// as specified in [IETF RFC 2553, Section 3.3].
/// It combines information about the flow label and the traffic class as specified
/// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
/// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
/// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
/// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
/// assert_eq!(socket.flowinfo(), 10);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn flowinfo(&self) -> u32 {
self.flowinfo
}
/// Changes the flow information associated with this socket address.
///
/// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
/// socket.set_flowinfo(56);
/// assert_eq!(socket.flowinfo(), 56);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
self.flowinfo = new_flowinfo;
}
/// Returns the scope ID associated with this address.
///
/// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
/// as specified in [IETF RFC 2553, Section 3.3].
///
/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
/// assert_eq!(socket.scope_id(), 78);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_socketaddr", since = "CURRENT_RUSTC_VERSION")]
pub const fn scope_id(&self) -> u32 {
self.scope_id
}
/// Changes the scope ID associated with this socket address.
///
/// See [`SocketAddrV6::scope_id`]'s documentation for more details.
///
/// # Examples
///
/// ```
/// use std::net::{SocketAddrV6, Ipv6Addr};
///
/// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
/// socket.set_scope_id(42);
/// assert_eq!(socket.scope_id(), 42);
/// ```
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_scope_id(&mut self, new_scope_id: u32) {
self.scope_id = new_scope_id;
}
}
pub use core::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
impl FromInner<c::sockaddr_in> for SocketAddrV4 {
fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
SocketAddrV4 { ip: Ipv4Addr::from_inner(addr.sin_addr), port: u16::from_be(addr.sin_port) }
SocketAddrV4::new(Ipv4Addr::from_inner(addr.sin_addr), u16::from_be(addr.sin_port))
}
}
impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
SocketAddrV6 {
ip: Ipv6Addr::from_inner(addr.sin6_addr),
port: u16::from_be(addr.sin6_port),
flowinfo: addr.sin6_flowinfo,
scope_id: addr.sin6_scope_id,
}
SocketAddrV6::new(
Ipv6Addr::from_inner(addr.sin6_addr),
u16::from_be(addr.sin6_port),
addr.sin6_flowinfo,
addr.sin6_scope_id,
)
}
}
@ -549,8 +37,8 @@ impl IntoInner<c::sockaddr_in> for SocketAddrV4 {
fn into_inner(self) -> c::sockaddr_in {
c::sockaddr_in {
sin_family: c::AF_INET as c::sa_family_t,
sin_port: self.port.to_be(),
sin_addr: self.ip.into_inner(),
sin_port: self.port().to_be(),
sin_addr: self.ip().into_inner(),
..unsafe { mem::zeroed() }
}
}
@ -560,162 +48,15 @@ impl IntoInner<c::sockaddr_in6> for SocketAddrV6 {
fn into_inner(self) -> c::sockaddr_in6 {
c::sockaddr_in6 {
sin6_family: c::AF_INET6 as c::sa_family_t,
sin6_port: self.port.to_be(),
sin6_addr: self.ip.into_inner(),
sin6_flowinfo: self.flowinfo,
sin6_scope_id: self.scope_id,
sin6_port: self.port().to_be(),
sin6_addr: self.ip().into_inner(),
sin6_flowinfo: self.flowinfo(),
sin6_scope_id: self.scope_id(),
..unsafe { mem::zeroed() }
}
}
}
#[stable(feature = "ip_from_ip", since = "1.16.0")]
impl From<SocketAddrV4> for SocketAddr {
/// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
fn from(sock4: SocketAddrV4) -> SocketAddr {
SocketAddr::V4(sock4)
}
}
#[stable(feature = "ip_from_ip", since = "1.16.0")]
impl From<SocketAddrV6> for SocketAddr {
/// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
fn from(sock6: SocketAddrV6) -> SocketAddr {
SocketAddr::V6(sock6)
}
}
#[stable(feature = "addr_from_into_ip", since = "1.17.0")]
impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
/// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
///
/// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`]
/// and creates a [`SocketAddr::V6`] for an [`IpAddr::V6`].
///
/// `u16` is treated as port of the newly created [`SocketAddr`].
fn from(pieces: (I, u16)) -> SocketAddr {
SocketAddr::new(pieces.0.into(), pieces.1)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for SocketAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
SocketAddr::V4(ref a) => a.fmt(f),
SocketAddr::V6(ref a) => a.fmt(f),
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for SocketAddr {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for SocketAddrV4 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// If there are no alignment requirements, write the socket address directly to `f`.
// Otherwise, write it to a local buffer and then use `f.pad`.
if f.precision().is_none() && f.width().is_none() {
write!(f, "{}:{}", self.ip(), self.port())
} else {
const LONGEST_IPV4_SOCKET_ADDR: &str = "255.255.255.255:65536";
let mut buf = DisplayBuffer::<{ LONGEST_IPV4_SOCKET_ADDR.len() }>::new();
// Buffer is long enough for the longest possible IPv4 socket address, so this should never fail.
write!(buf, "{}:{}", self.ip(), self.port()).unwrap();
f.pad(buf.as_str())
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for SocketAddrV4 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for SocketAddrV6 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// If there are no alignment requirements, write the socket address directly to `f`.
// Otherwise, write it to a local buffer and then use `f.pad`.
if f.precision().is_none() && f.width().is_none() {
match self.scope_id() {
0 => write!(f, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
} else {
const LONGEST_IPV6_SOCKET_ADDR: &str =
"[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%4294967296]:65536";
let mut buf = DisplayBuffer::<{ LONGEST_IPV6_SOCKET_ADDR.len() }>::new();
match self.scope_id() {
0 => write!(buf, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(buf, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
// Buffer is long enough for the longest possible IPv6 socket address, so this should never fail.
.unwrap();
f.pad(buf.as_str())
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for SocketAddrV6 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl PartialOrd for SocketAddrV4 {
fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl PartialOrd for SocketAddrV6 {
fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl Ord for SocketAddrV4 {
fn cmp(&self, other: &SocketAddrV4) -> Ordering {
self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
}
}
#[stable(feature = "socketaddr_ordering", since = "1.45.0")]
impl Ord for SocketAddrV6 {
fn cmp(&self, other: &SocketAddrV6) -> Ordering {
self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for SocketAddrV4 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.port, self.ip).hash(s)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl hash::Hash for SocketAddrV6 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.port, &self.ip, self.flowinfo, self.scope_id).hash(s)
}
}
/// A trait for objects which can be converted or resolved to one or more
/// [`SocketAddr`] values.
///

View File

@ -6,13 +6,15 @@
use crate::ffi::CStr;
use crate::mem;
use crate::os::raw::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ushort};
use crate::os::raw::{c_char, c_long, c_longlong, c_uint, c_ulong, c_ushort};
use crate::os::windows::io::{BorrowedHandle, HandleOrInvalid, HandleOrNull};
use crate::ptr;
use core::ffi::NonZero_c_ulong;
use libc::{c_void, size_t, wchar_t};
pub use crate::os::raw::c_int;
#[path = "c/errors.rs"] // c.rs is included from two places so we need to specify this
mod errors;
pub use errors::*;
@ -47,16 +49,19 @@ pub type ACCESS_MASK = DWORD;
pub type LPBOOL = *mut BOOL;
pub type LPBYTE = *mut BYTE;
pub type LPCCH = *const CHAR;
pub type LPCSTR = *const CHAR;
pub type LPCWCH = *const WCHAR;
pub type LPCWSTR = *const WCHAR;
pub type LPCVOID = *const c_void;
pub type LPDWORD = *mut DWORD;
pub type LPHANDLE = *mut HANDLE;
pub type LPOVERLAPPED = *mut OVERLAPPED;
pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION;
pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES;
pub type LPSTARTUPINFO = *mut STARTUPINFO;
pub type LPSTR = *mut CHAR;
pub type LPVOID = *mut c_void;
pub type LPCVOID = *const c_void;
pub type LPWCH = *mut WCHAR;
pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW;
pub type LPWSADATA = *mut WSADATA;
@ -132,6 +137,10 @@ pub const MAX_PATH: usize = 260;
pub const FILE_TYPE_PIPE: u32 = 3;
pub const CP_UTF8: DWORD = 65001;
pub const MB_ERR_INVALID_CHARS: DWORD = 0x08;
pub const WC_ERR_INVALID_CHARS: DWORD = 0x80;
#[repr(C)]
#[derive(Copy)]
pub struct WIN32_FIND_DATAW {
@ -1147,6 +1156,25 @@ extern "system" {
lpFilePart: *mut LPWSTR,
) -> DWORD;
pub fn GetFileAttributesW(lpFileName: LPCWSTR) -> DWORD;
pub fn MultiByteToWideChar(
CodePage: UINT,
dwFlags: DWORD,
lpMultiByteStr: LPCCH,
cbMultiByte: c_int,
lpWideCharStr: LPWSTR,
cchWideChar: c_int,
) -> c_int;
pub fn WideCharToMultiByte(
CodePage: UINT,
dwFlags: DWORD,
lpWideCharStr: LPCWCH,
cchWideChar: c_int,
lpMultiByteStr: LPSTR,
cbMultiByte: c_int,
lpDefaultChar: LPCCH,
lpUsedDefaultChar: LPBOOL,
) -> c_int;
}
#[link(name = "ws2_32")]

View File

@ -169,14 +169,27 @@ fn write(
}
fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usize> {
debug_assert!(!utf8.is_empty());
let mut utf16 = [MaybeUninit::<u16>::uninit(); MAX_BUFFER_SIZE / 2];
let mut len_utf16 = 0;
for (chr, dest) in utf8.encode_utf16().zip(utf16.iter_mut()) {
*dest = MaybeUninit::new(chr);
len_utf16 += 1;
}
// Safety: We've initialized `len_utf16` values.
let utf16: &[u16] = unsafe { MaybeUninit::slice_assume_init_ref(&utf16[..len_utf16]) };
let utf8 = &utf8[..utf8.floor_char_boundary(utf16.len())];
let utf16: &[u16] = unsafe {
// Note that this theoretically checks validity twice in the (most common) case
// where the underlying byte sequence is valid utf-8 (given the check in `write()`).
let result = c::MultiByteToWideChar(
c::CP_UTF8, // CodePage
c::MB_ERR_INVALID_CHARS, // dwFlags
utf8.as_ptr() as c::LPCCH, // lpMultiByteStr
utf8.len() as c::c_int, // cbMultiByte
utf16.as_mut_ptr() as c::LPWSTR, // lpWideCharStr
utf16.len() as c::c_int, // cchWideChar
);
assert!(result != 0, "Unexpected error in MultiByteToWideChar");
// Safety: MultiByteToWideChar initializes `result` values.
MaybeUninit::slice_assume_init_ref(&utf16[..result as usize])
};
let mut written = write_u16s(handle, &utf16)?;
@ -189,8 +202,8 @@ fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usiz
// a missing surrogate can be produced (and also because of the UTF-8 validation above),
// write the missing surrogate out now.
// Buffering it would mean we have to lie about the number of bytes written.
let first_char_remaining = utf16[written];
if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF {
let first_code_unit_remaining = utf16[written];
if first_code_unit_remaining >= 0xDCEE && first_code_unit_remaining <= 0xDFFF {
// low surrogate
// We just hope this works, and give up otherwise
let _ = write_u16s(handle, &utf16[written..written + 1]);
@ -212,6 +225,7 @@ fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usiz
}
fn write_u16s(handle: c::HANDLE, data: &[u16]) -> io::Result<usize> {
debug_assert!(data.len() < u32::MAX as usize);
let mut written = 0;
cvt(unsafe {
c::WriteConsoleW(
@ -365,26 +379,32 @@ fn read_u16s(handle: c::HANDLE, buf: &mut [MaybeUninit<u16>]) -> io::Result<usiz
Ok(amount as usize)
}
#[allow(unused)]
fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> {
let mut written = 0;
for chr in char::decode_utf16(utf16.iter().cloned()) {
match chr {
Ok(chr) => {
chr.encode_utf8(&mut utf8[written..]);
written += chr.len_utf8();
}
Err(_) => {
// We can't really do any better than forget all data and return an error.
return Err(io::const_io_error!(
io::ErrorKind::InvalidData,
"Windows stdin in console mode does not support non-UTF-16 input; \
encountered unpaired surrogate",
));
}
}
debug_assert!(utf16.len() <= c::c_int::MAX as usize);
debug_assert!(utf8.len() <= c::c_int::MAX as usize);
let result = unsafe {
c::WideCharToMultiByte(
c::CP_UTF8, // CodePage
c::WC_ERR_INVALID_CHARS, // dwFlags
utf16.as_ptr(), // lpWideCharStr
utf16.len() as c::c_int, // cchWideChar
utf8.as_mut_ptr() as c::LPSTR, // lpMultiByteStr
utf8.len() as c::c_int, // cbMultiByte
ptr::null(), // lpDefaultChar
ptr::null_mut(), // lpUsedDefaultChar
)
};
if result == 0 {
// We can't really do any better than forget all data and return an error.
Err(io::const_io_error!(
io::ErrorKind::InvalidData,
"Windows stdin in console mode does not support non-UTF-16 input; \
encountered unpaired surrogate",
))
} else {
Ok(result as usize)
}
Ok(written)
}
impl IncompleteUtf8 {

View File

@ -50,6 +50,7 @@ dependencies = [
"opener",
"pretty_assertions",
"serde",
"serde_derive",
"serde_json",
"sha2",
"sysinfo",
@ -564,9 +565,6 @@ name = "serde"
version = "1.0.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"

View File

@ -39,7 +39,10 @@ cc = "1.0.69"
libc = "0.2"
hex = "0.4"
object = { version = "0.29.0", default-features = false, features = ["archive", "coff", "read_core", "unaligned"] }
serde = { version = "1.0.8", features = ["derive"] }
serde = "1.0.137"
# Directly use serde_derive rather than through the derive feature of serde to allow building both
# in parallel and to allow serde_json and toml to start building as soon as serde has been built.
serde_derive = "1.0.137"
serde_json = "1.0.2"
sha2 = "0.10"
tar = "0.4"

View File

@ -16,7 +16,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str;
use serde::Deserialize;
use serde_derive::Deserialize;
use crate::builder::crate_description;
use crate::builder::Cargo;

View File

@ -25,6 +25,7 @@ use crate::flags::{Color, Flags};
use crate::util::{exe, output, t};
use once_cell::sync::OnceCell;
use serde::{Deserialize, Deserializer};
use serde_derive::Deserialize;
macro_rules! check_ci_llvm {
($name:expr) => {

View File

@ -87,7 +87,7 @@ fn get_modified_rs_files(build: &Builder<'_>) -> Result<Option<Vec<String>>, Str
get_git_modified_files(Some(&build.config.src), &vec!["rs"])
}
#[derive(serde::Deserialize)]
#[derive(serde_derive::Deserialize)]
struct RustfmtConfig {
ignore: Vec<String>,
}

View File

@ -1,7 +1,7 @@
use std::path::PathBuf;
use std::process::Command;
use serde::Deserialize;
use serde_derive::Deserialize;
use crate::cache::INTERNER;
use crate::util::output;

View File

@ -7,7 +7,7 @@
use crate::builder::Step;
use crate::util::t;
use crate::Build;
use serde::{Deserialize, Serialize};
use serde_derive::{Deserialize, Serialize};
use std::cell::RefCell;
use std::fs::File;
use std::io::BufWriter;

View File

@ -1,6 +1,6 @@
use crate::builder::{Builder, RunConfig, ShouldRun, Step};
use crate::util::t;
use serde::{Deserialize, Serialize};
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fmt;

View File

@ -0,0 +1,8 @@
#![allow(nonstandard_style)]
use f::f::f; //~ ERROR
trait f {
extern "C" fn f();
}
fn main() {}

View File

@ -0,0 +1,9 @@
error[E0432]: unresolved import `f::f`
--> $DIR/issue-108529.rs:2:8
|
LL | use f::f::f;
| ^ expected type, found associated function `f` in `f`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0432`.

View File

@ -23,6 +23,7 @@ extern crate alloc;
fn main() {
another_name::mem::drop(3);
another::foo();
with_visibility::foo();
remove_extern_crate::foo!();
bar!();
alloc::vec![5];
@ -37,3 +38,12 @@ mod another {
remove_extern_crate::foo!();
}
}
mod with_visibility {
pub use core; //~ WARNING `extern crate` is not idiomatic
pub fn foo() {
core::mem::drop(4);
remove_extern_crate::foo!();
}
}

View File

@ -23,6 +23,7 @@ extern crate alloc;
fn main() {
another_name::mem::drop(3);
another::foo();
with_visibility::foo();
remove_extern_crate::foo!();
bar!();
alloc::vec![5];
@ -37,3 +38,12 @@ mod another {
remove_extern_crate::foo!();
}
}
mod with_visibility {
pub extern crate core; //~ WARNING `extern crate` is not idiomatic
pub fn foo() {
core::mem::drop(4);
remove_extern_crate::foo!();
}
}

View File

@ -12,10 +12,26 @@ LL | #![warn(rust_2018_idioms)]
= note: `#[warn(unused_extern_crates)]` implied by `#[warn(rust_2018_idioms)]`
warning: `extern crate` is not idiomatic in the new edition
--> $DIR/remove-extern-crate.rs:32:5
--> $DIR/remove-extern-crate.rs:33:5
|
LL | extern crate core;
| ^^^^^^^^^^^^^^^^^^ help: convert it to a `use`
| ^^^^^^^^^^^^^^^^^^
|
help: convert it to a `use`
|
LL | use core;
| ~~~
warning: 2 warnings emitted
warning: `extern crate` is not idiomatic in the new edition
--> $DIR/remove-extern-crate.rs:43:5
|
LL | pub extern crate core;
| ^^^^^^^^^^^^^^^^^^^^^^
|
help: convert it to a `use`
|
LL | pub use core;
| ~~~
warning: 3 warnings emitted

View File

@ -43,7 +43,7 @@ LL | let ips: Vec<_> = (0..100_000).map(|_| u32::from(0u32.into())).collect(
| |
| required by a bound introduced by this call
|
= note: multiple `impl`s satisfying `u32: From<_>` found in the following crates: `core`, `std`:
= note: multiple `impl`s satisfying `u32: From<_>` found in the `core` crate:
- impl From<Ipv4Addr> for u32;
- impl From<NonZeroU32> for u32;
- impl From<bool> for u32;

View File

@ -0,0 +1,28 @@
// check-pass
// compile-flags: -Ztrait-solver=next
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let x: i32 = parse()?;
Ok(())
}
trait Parse {}
impl Parse for i32 {}
#[derive(Debug)]
struct ParseError;
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ParseError")
}
}
impl Error for ParseError {}
fn parse<T: Parse>() -> Result<T, ParseError> {
todo!()
}

View File

@ -0,0 +1,24 @@
// compile-flags: -Ztrait-solver=next
// known-bug: unknown
trait Test {
type Assoc;
}
fn transform<T: Test>(x: T) -> T::Assoc {
todo!()
}
impl Test for i32 {
type Assoc = i32;
}
impl Test for String {
type Assoc = String;
}
fn main() {
let mut x = Default::default();
x = transform(x);
x = 1i32;
}

View File

@ -0,0 +1,14 @@
error[E0308]: mismatched types
--> $DIR/equating-projection-cyclically.rs:22:19
|
LL | x = transform(x);
| ^ expected inferred type, found associated type
|
= note: expected type `_`
found associated type `<_ as Test>::Assoc`
= help: consider constraining the associated type `<_ as Test>::Assoc` to `_`
= note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.