Connect with us

FACEBOOK

Rust Nibbles – Gazebo: Casts and transmute

Published

on

This article was written in collaboration with Neil Mitchell, a Software Engineer in the Developer Infrastructure organization at Facebook.

The Rust library Gazebo contains a collection of well-tested Rust utilities in the form of standalone modules. In this series of blog posts, we will cover some of the modules that make up the Gazebo library. In today’s blog, we will cover the module Cast. This blog is a part of our Rust Nibbles series, where we go over the various Rust libraries we have open-sourced to learn more about what motivated their creation and how one can use them.

One of the appeals of Rust is that it tries its best to help you avoid dangerous mistakes – but there are still unsafe functions available. Rust has a function called transmute, which converts one type to another. For example, you can write:

let y = unsafe { transmute(x) }; 

This fragment converts from a u64 to a [u8; 8]; or from a String to a Vec<u8>; or from a &str to an &(). Alternatively stated, the above code might do anything, and for a function like transmute, you probably really care about precisely what it does. This realisation led us to introduce the Gazebo cast module, which provides more restrictive alternatives.

The first entry in the cast module is the transmute! macro. Morally, transmute is a function from an input type to an output type, which takes a value of the input type. While usually Rust inferring types for us is useful, for transmute it is often harmful. With transmute! as a macro we can take 3 arguments, two of them types, so can write:

Advertisement
free widgets for website
let y = unsafe { transmute!(u64, [u8; 8], x) }; 

It’s no less unsafe, but it’s much more explicit. Alternatively, using the existing transmute function you can write:

let y = unsafe { transmute::<u64, [u8; 8]>(x) }; 

And we are hopeful that one day Clippy can be extended to suggest giving the types explicitly.

See also  China disrupted Facebook around the world for political and intelligence reasons? - Modern ...

Specific casts

While transmute can do many conversions, in some cases there are preferred ways of converting between types. For example, if you try using transmute to convert from &Foo to &Bar, clippy will suggest &*(x as *const Foo as *const Bar). That’s quite verbose. But more importantly, it obscures what you are trying to do. Therefore, Gazebo provides cast::ptr(x) which wraps up this conversion for you. The cast module provides 5 specific conversions we’ve found useful:

pub fn ptr_to_usize<T: ?Sized>(x: &T) -> usize;
pub unsafe fn usize_to_ptr<'a, T>(x: usize) -> &'a T;
pub unsafe fn ptr<From, To>(x: &From) -> &To;
pub unsafe fn ptr_mut<From, To>(x: &mut From) -> &mut To;
pub unsafe fn ptr_lifetime<'a, 'b, T: ?Sized>(x: &'a T) -> &'b T; 

These are unsafe, all could be implemented as transmute, but are implemented as pointer conversions as that is the recommended form. The hope is these conversions make the intent clearer.

Unchecked transmute

The transmute function can be used to do lots of unsafe things. But sometimes, after a long day coding, do you wonder if transmute is a little too safe? In particular, transmute checks that the input and output types have the same size. That’s great for concrete type parameters, but means that you can’t convert a Vec<T> to a String without having the T specified at compile time. That restriction, while usually a very good thing, can sometimes be harmful – so we provide transmute_unchecked for those cases. It’s exactly like transmute, but without a compile-time check of equal sizes. If the sizes aren’t equal things are highly likely to segfault, and in fact, if any of the other transmute invariants don’t hold it is undefined behaviour. But having that more powerful function is sometimes necessary.

Advertisement
free widgets for website

We hope that this blog helps you understand the Cast module, how to use it and gives you good insight into what it does. Look out for our next blog in this series, where we discuss all the remaining little bits of Gazebo.

See also  This is what major analysts are saying about Facebook's first-quarter earnings

Be sure to check out our previous blogs in the Gazebo series to learn more about the various features the Gazebo library has to offer –
Gazebo – Prelude
Gazebo – Dupe
Gazebo – Variants
Gazebo – AnyLifetime
Gazebo – Comparisons

About the Rust Nibbles series

We at Facebook believe that Rust is an outstanding language that shines in critical issues such as memory safety, performance and reliability. We joined the Rust Foundation to help contribute towards the growth, advancement and adoption of Rust, and towards sustainable development of open source technologies and developer communities across the world.

This blog is a part of our Rust Nibbles series, where we go over the various Rust libraries we have open-sourced to learn more about what motivated their creation and how one can use them. We hope that this series helps you create amazing projects by using these libraries and encourages you to try them out.

To learn more about Facebook Open Source, visit our open source site, subscribe to our YouTube channel, or follow us on Twitter and Facebook.

Advertisement
free widgets for website

Facebook Developers

Continue Reading
Advertisement free widgets for website

FACEBOOK

Facebook-Meta Earns the ‘Worst Company of 2021’ Title in This Survey

Published

on

By

facebook-meta-earns-the-‘worst-company-of-2021’-title-in-this-survey-–-news18
Facebook has had its share of controversies this year. The company was under more scrutiny after whistleblower Frances Haugen leaked a series of internal documents.

Facebook parent Meta has been named the Worst Company of the Year (2021) by Yahoo Finance respondents. According to the publication, an “open-ended” survey was published on Yahoo Finance on December 4 and 5, where 1,541 respondents participated. Facebook received 8 percent of the write-in vote, but respondents were seemingly mad about the Robinhood trading app as well. Electric truck startup Nikola, which was named last year’s worst company by the same publication also faced respondents ire.

Yahoo Finance notes, “Facebook has had its share of controversies this year.” Starting in January, Meta-owned WhatsApp got caught up in a huge controversy after the messaging app announced a new privacy policy (Terms of Service). WhatsApp said it would collect user information and share it with third-party apps for a better user experience. However, the app gave users no choice but later made modifications to the policy under pressure. Similarly, the company was under more scrutiny after whistleblower and former Facebook employee Frances Haugen leaked a series of internal documents showing the company’s problematic practices. It was revealed that Meta-owned Instagram had a negative impact on teenage girls, but the company did almost nothing to rectify the problem.

Yahoo Finance even highlights, “At the same time, some critics, including conservatives, say Facebook over-policed the platform’s speech and stifled their voices.” Critics also blame Facebook and other social media platforms for not curbing hate speech that led to Capitol Building riots.

See also  Rust Nibbles - Gazebo: Prelude

However, around 30 percent of Yahoo Finance readers said that Facebook or Meta could redeem itself. One respondent suggested that the company could issue a formal apology for negligence and donate a sizable amount of its profits to a foundation to help reverse its harm.

On the other hand, respondents chose Microsoft as the Company of the Year (2021). The Satya Nadella-led company touched the trillion-mark this year and introduced notable upgrades. The most notable is the Windows 11 OS update that succeeds Windows 10.

Advertisement
free widgets for website
Continue Reading

FACEBOOK

Facebook pays 1.7 Cr fine to Russia after failing to delete content Moscow deems illegal

Published

on

By

facebook-pays-1.7-cr-fine-to-russia-after-failing-to-delete-content-moscow-deems-illegal

In the latest legal tussle with Russia over controversial social media regulation laws, Facebook paid 17 million roubles (Rs 1.7 Crore) for failing to remove content deemed illegal by Moscow. With a threat of potential larger fines looming, Facebook parent company Meta, owned by Mark Zuckerberg, is scheduled to face court next week over repeated violations of Russian legislation on content, Interfax News Agency reported. As per the latest updates, the social media giant could be fined a percentage of its annual revenue.

In October, Moscow sent state bailiffs to enforce the collection of 17 million roubles. Meanwhile, as per Interfax report citing a federal bailiffs’ database, on Sunday, there were more enforcement proceedings against the company. Apart from the popular social media app, Telegram has also paid 15 million roubles in fines for failing to comply with the Russian social media legislations that came into force in 2016.

Facebook pays $53k to Russia for refusing controversial social media laws

It is pertinent to mention that Facebook has locked horns with Moscow earlier in November, resulting in it paying 4 million roubles ($53,000) over its refusal to adhere to Russian data localisation laws, the Moscow Times reported. The Moscow court on November 25 had said that Facebook paid the fine levied in February, following which all proceedings against the US-based social media giant. The payment comes against the litigation filed against the company in 2018, alongside Twitter. The tech companies were also forced to pay an additional 3000 rubles ($40) for failing to comply with user data sharing rules as per the law. The Russian authorities have also previously blocked LinkedIn, owned by Microsoft, for failing to abide by the laws.

See also  This is what major analysts are saying about Facebook's first-quarter earnings

Russian social media laws

As per Moscow Times, under the Russian social media regulation laws, all foreign technology companies are required to store data related to Russian customers and users on servers located in Russia. Additionally, the Russian tech companies will also have to share encryption data with the federal authorities as well as record user calls, messages and civil society group conversation records. The apparatus is said to be a severe breach of privacy rights and unfettered back-door access to personal data that could be used to harass Kremlin critics.

Continue Reading

FACEBOOK

Facebook Messenger Is Launching a Split Payments Feature for Users to Quickly Share Expenses

Published

on

By

Facebook Messenger Is Launching a Split Payments Feature for Users to Quickly Share Expenses

Meta has announced the arrival of a new Split Payments feature in Facebook Messenger. This feature, as the name suggests, will let you calculate and split expenses with others right from Facebook Messenger. This feature essentially looks to bring an easier method to share the cost of bills and expenses — for example, splitting a dinner bill with friends. Using this new Split Payment feature, Facebook Messenger users will be able to split bills evenly or modify the contribution for each individual, including their own.

The company took to its blog post to announce the new Split Payment feature in Facebook Messenger. 9to5Mac reports that this new bill splitting feature is still in beta and will be exclusive to US users at first. The rollout will begin early next week. As mentioned, it will help users share the cost of bills, expenses, and payments. This feature is especially useful for those who share an apartment and need to split the monthly rent and other expenses with their mates. It could also come handy at a group dinner with many people.

With Split Payments, users can add the number of people the expense needs to be divided with and, by default, the amount entered will be divided in equal parts. A user can also modify each person’s contribution including their own. To use Split Payments, click the Get Started button in a group chat or the Payments Hub in Messenger. Users can modify the contribution in the Split Payments option and send a notification to all the users who need to make payments. After entering a personalised message and confirming your Facebook Pay details, the request will be sent and viewable in the group chat thread.

See also  China disrupted Facebook around the world for political and intelligence reasons? - Modern ...

Once someone has made the payment, you can mark their transaction as ‘completed’. The Split Payment feature will automatically take into account your share as well and calculate the amount owed accordingly.


For the latest tech news and reviews, follow Gadgets 360 on Twitter, Facebook, and Google News. For the latest videos on gadgets and tech, subscribe to our YouTube channel.

Advertisement
free widgets for website

Tasneem Akolawala is a Senior Reporter for Gadgets 360. Her reporting expertise encompasses smartphones, wearables, apps, social media, and the overall tech industry. She reports out of Mumbai, and also writes about the ups and downs in the Indian telecom sector. Tasneem can be reached on Twitter at @MuteRiot, and leads, tips, and releases can be sent to tasneema@ndtv.com.

Continue Reading

Trending