Received: from list by lists.gnu.org with archive (Exim 4.90_1) id 1tKd59-0007kl-Ar for mharc-qemu-rust@gnu.org; Mon, 09 Dec 2024 07:41:57 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tKd25-0004ZB-5C for qemu-rust@nongnu.org; Mon, 09 Dec 2024 07:38:47 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1tKd1w-0007au-GE for qemu-rust@nongnu.org; Mon, 09 Dec 2024 07:38:34 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1733747906; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=T6KMN/KKwz/drY0m0B/GAzuPFwO/9IuBICqSOgF3wlY=; b=BhZFCTXPSb+qr1zmMB/DgzBywPzEJ6/0egoXGpqAdcSsL1UYZj9JFCYEv3dpTnj79y5vi2 rxj/KGKGcmvbEDQjW/La7shnblsYc1PR4AfZjdN5DgbOVHkemJOJritt1WGPh6qBJuy94S AmN3baSjKUFhycXAHM2kwU8NYysqkAk= Received: from mail-wm1-f69.google.com (mail-wm1-f69.google.com [209.85.128.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-288-qEhWac2XMKmKJbpz7RXTjg-1; Mon, 09 Dec 2024 07:38:25 -0500 X-MC-Unique: qEhWac2XMKmKJbpz7RXTjg-1 X-Mimecast-MFC-AGG-ID: qEhWac2XMKmKJbpz7RXTjg Received: by mail-wm1-f69.google.com with SMTP id 5b1f17b1804b1-434edbbc3a7so14750055e9.3 for ; Mon, 09 Dec 2024 04:38:25 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1733747903; x=1734352703; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=T6KMN/KKwz/drY0m0B/GAzuPFwO/9IuBICqSOgF3wlY=; b=GA9vnejKQWIECY6X+7VtFmjGquYAnuOcWPyCYwibKKBkz8o42LCng1fIOrmkOBnqph Rqzs2Xc/9t+xFFmN7OSNyh2c7051vbD+aULCV8yHwike47cIssFBVpQ3owDKQ9rP3EpY Qfz0xfpU9PsbSVaWphSOcDui4b+aFG57ePrXmUXThsCKylGNzhf8N7nPAZszJbCJt2nd jcqtfDo+LvMhYsGe3WPjtK2JnDpM6hCVaMfXUn08MjamHVB2shO7LULM+04r2tX8Eins rFr/ZPtpXwiz2h7gKXcA/yJ7diErymJpH5lu3ydRyKh9AB/80yINngRidm8Ji0BBDeKU kEUA== X-Gm-Message-State: AOJu0YzqVlprUXnawAYlUMN7eVTQbb4WMx4bBgH7Si40cAF4GukKfNL9 usOS2IaBsJvgKbdC56YBho4OfVCcIcxTtVSHVC10LZ2I4RXRyIpw3Z6MAuos1sLU34YC26DQhmW 5bAbuWoFYaWpKNWSrIxXw0FOPd4Gx6hTxfHDZnDzi7YjReNYUCYzBIoiPMNw= X-Gm-Gg: ASbGncvC5ovKCrUnuAaenY3yktQJTfaRuB5Swzg79Fvtf5l+JTGfqgbwq9qUxURL+pT O6bp1U0/8dUEywruMJfI9kWh/UjDImIjSZL1f37SotcjT4E5D5Ta43SaiNXi1VnYirPlCJYkJ5v gF0vYYC5/mo5tCP8JaH6Kl11dHdNT+lpiLcfWAVa1cX6PBdr1QiNcinphJiRXD6EctzqcZ9WIvM yVEWEy7H75tuVjH3i5tJXwG3Y0XZYbsMrcUxE2QRXqfTqF32Ptm8A== X-Received: by 2002:a05:6000:4715:b0:385:fb34:d585 with SMTP id ffacd0b85a97d-3862b37f1fcmr9529693f8f.34.1733747903455; Mon, 09 Dec 2024 04:38:23 -0800 (PST) X-Google-Smtp-Source: AGHT+IHNIjYvCBUUw5SuI6EdubzMkYBb+V9p2OLC1S6N1gh//MaK5456gKjpwFzm1ivquRIqCgHGWg== X-Received: by 2002:a05:6000:4715:b0:385:fb34:d585 with SMTP id ffacd0b85a97d-3862b37f1fcmr9529680f8f.34.1733747903085; Mon, 09 Dec 2024 04:38:23 -0800 (PST) Received: from [192.168.10.47] ([151.81.118.45]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-434f0d6a825sm71952995e9.20.2024.12.09.04.38.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Dec 2024 04:38:21 -0800 (PST) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: qemu-rust@nongnu.org, Zhao Liu , Junjie Mao Subject: [PATCH 26/26] rust: callbacks: allow passing optional callbacks as () Date: Mon, 9 Dec 2024 13:37:17 +0100 Message-ID: <20241209123717.99077-27-pbonzini@redhat.com> X-Mailer: git-send-email 2.47.1 In-Reply-To: <20241209123717.99077-1-pbonzini@redhat.com> References: <20241209123717.99077-1-pbonzini@redhat.com> MIME-Version: 1.0 X-Mimecast-Spam-Score: 0 X-Mimecast-MFC-PROC-ID: XXxE4_x6YKQxpJHrClh_DU-QeIAYCgboTskWnpVn2k4_1733747904 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: 8bit content-type: text/plain; charset="US-ASCII"; x-default=true Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -25 X-Spam_score: -2.6 X-Spam_bar: -- X-Spam_report: (-2.6 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.489, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, T_SPF_TEMPERROR=0.01 autolearn=unavailable autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-rust@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: QEMU Rust-related patches and discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 09 Dec 2024 12:38:58 -0000 X-List-Received-Date: Mon, 09 Dec 2024 12:38:58 -0000 In some cases, callbacks are optional. Using "Some(function)" and "None" does not work well, because when someone writes "None" the compiler does not know what to use for "F" in "Option". Therefore, adopt () to mean a "null" callback. It is possible to enforce that a callback is valid by adding a "let _: () = F::ASSERT_IS_SOME" before the invocation of F::call. Signed-off-by: Paolo Bonzini --- rust/qemu-api/src/callbacks.rs | 97 ++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/rust/qemu-api/src/callbacks.rs b/rust/qemu-api/src/callbacks.rs index 6401d807198..83c681d6478 100644 --- a/rust/qemu-api/src/callbacks.rs +++ b/rust/qemu-api/src/callbacks.rs @@ -76,6 +76,31 @@ /// call_it(&move |_| String::from(x), "hello workd"); /// ``` /// +/// `()` can be used to indicate "no function": +/// +/// ``` +/// # use qemu_api::callbacks::FnCall; +/// fn optional FnCall<(&'a str,), String>>(_f: &F, s: &str) -> Option { +/// if F::IS_SOME { +/// Some(F::call((s,))) +/// } else { +/// None +/// } +/// } +/// +/// assert!(optional(&(), "hello world").is_none()); +/// ``` +/// +/// Invoking `F::call` will then be a run-time error. +/// +/// ```should_panic +/// # use qemu_api::callbacks::FnCall; +/// # fn call_it FnCall<(&'a str,), String>>(_f: &F, s: &str) -> String { +/// # F::call((s,)) +/// # } +/// let s: String = call_it(&(), "hello world"); // panics +/// ``` +/// /// # Safety /// /// Because `Self` is a zero-sized type, all instances of the type are @@ -90,10 +115,70 @@ pub unsafe trait FnCall: 'static + Sync + Sized { /// Rust 1.79.0+. const ASSERT_ZERO_SIZED: () = { assert!(mem::size_of::() == 0) }; + /// Referring to this constant asserts that the `Self` type is an actual + /// function type, which can be used to catch incorrect use of `()` + /// at compile time. + /// + /// # Examples + /// + /// ```compile_fail + /// # use qemu_api::callbacks::FnCall; + /// fn call_it FnCall<(&'a str,), String>>(_f: &F, s: &str) -> String { + /// let _: () = F::ASSERT_IS_SOME; + /// F::call((s,)) + /// } + /// + /// let s: String = call_it((), "hello world"); // does not compile + /// ``` + /// + /// Note that this use more simply `const { assert!(F::IS_SOME) }` in + /// Rust 1.79.0 or newer. + const ASSERT_IS_SOME: () = { assert!(Self::IS_SOME) }; + + /// `true` if `Self` is an actual function type and not `()`. + /// + /// # Examples + /// + /// You can use `IS_SOME` to catch this at compile time: + /// + /// ```compile_fail + /// # use qemu_api::callbacks::FnCall; + /// fn call_it FnCall<(&'a str,), String>>(_f: &F, s: &str) -> String { + /// const { assert!(F::IS_SOME) } + /// F::call((s,)) + /// } + /// + /// let s: String = call_it((), "hello world"); // does not compile + /// ``` + const IS_SOME: bool; + + /// `false` if `Self` is an actual function type, `true` if it is `()`. + fn is_none() -> bool { + !Self::IS_SOME + } + + /// `true` if `Self` is an actual function type, `false` if it is `()`. + fn is_some() -> bool { + Self::IS_SOME + } + /// Call the function with the arguments in args. fn call(a: Args) -> R; } +/// `()` acts as a "null" callback. Using `()` and `function` is nicer +/// than `None` and `Some(function)`, because the compiler is unable to +/// infer the type of just `None`. Therefore, the trait itself acts as the +/// option type, with functions [`FnCall::is_some`] and [`FnCall::is_none`]. +unsafe impl FnCall for () { + const IS_SOME: bool = false; + + /// Call the function with the arguments in args. + fn call(_a: Args) -> R { + panic!("callback not specified") + } +} + macro_rules! impl_call { ($($args:ident,)* ) => ( // SAFETY: because each function is treated as a separate type, @@ -103,6 +188,8 @@ unsafe impl FnCall<($($args,)*), R> for F where F: 'static + Sync + Sized + Fn($($args, )*) -> R, { + const IS_SOME: bool = true; + #[inline(always)] fn call(a: ($($args,)*)) -> R { let _: () = Self::ASSERT_ZERO_SIZED; @@ -138,4 +225,14 @@ fn do_test_call<'a, F: FnCall<(&'a str,), String>>(_f: &F) -> String { fn test_call() { assert_eq!(do_test_call(&str::to_owned), "hello world") } + + // The `_f` parameter is unused but it helps the compiler infer `F`. + fn do_test_is_some<'a, F: FnCall<(&'a str,), String>>(_f: &F) { + assert_eq!(F::is_some(), true); + } + + #[test] + fn test_is_some() { + do_test_is_some(&str::to_owned); + } } -- 2.47.1