Connect with us

FACEBOOK

Rust Nibbles – Gazebo: AnyLifetime

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 trait AnyLifetime. 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.

Rust provides the trait Any which serves as its helper for dynamic typing. Using the Any trait you can define:

fn print_if_string(arg: &dyn Any) { if let Some(string) = arg.downcast_ref::<String>() { println!("It's a string({}): '{}'", string.len(), string); } else { println!("Not a string..."); }
} 

Here, we are taking a value arg whose type is not statically known, then testing at runtime whether it is a String or not, and if it is, using it as a String. This code hasn’t turned Rust into a dynamically typed language, and there is nothing unsafe in our code. Under the hood, the Rust compiler generates a distinct TypeId for each type, and if the TypeId values match for any two values, their types are equivalent and Rust can safely convert between the two.

The Any trait works great, but it does impose a constraint that the type contained in the Any is ‘static. Which, in this context, means no lifetimes. In particular, we can’t use Any methods on a type such as:

Advertisement
struct Value<'v> {...} 

This restriction was particularly problematic for our Starlark language implementation, where most types do indeed contain a ‘v lifetime argument. To work around this limitation, we defined AnyLifetime. Very similarly to Any, the AnyLifetime trait is defined in gazebo::any as:

pub unsafe trait AnyLifetime<'a>: 'a { fn static_type_id() -> TypeId where Self: Sized; fn static_type_of(&self) -> TypeId;
} 

Given a value (or just a type), we need to provide the TypeId which uniquely identifies this type. The only tweak here is that we define the trait to produce the TypeId of the equivalent static type, e.g. for Value<‘v> above we can use the TypeId of Value<‘static>:

unsafe impl<'v> AnyLifetime<'v> for Value<'v> { fn static_type_id() -> TypeId { TypeId::of::<Value<'static>>() } fn static_type_of(&self) -> TypeId { TypeId::of::<Value<'static>>() }
} 

Now we have access to the methods we know and love from Any, such as downcast_ref, but without the ‘static constraint. The only downside is that unsafe in the definition of the implementation. And it really is unsafe – if we claim that the TypeId of Value is that of String, we can convert between the two types at runtime, and things will go horribly wrong (with a segfault, most likely).

See also  EU is investigating Facebook's Kustomer buyout over data concern

The solution is a series of increasingly powerful, but increasingly more error prone methods of defining instances. Starting with the simplest, we can define:

#[derive(AnyLifetime)]
struct Value<'v> {...} 

This works for types with no generic types and either zero or one lifetime parameters. Next, if we need to define the instance for any type, even type aliases, we can use the any_lifetime! macro:

Advertisement
any_lifetime!(Value<'v>) 

And finally, if we need ultimate flexibility, we can define the instance head ourselves and just use a macro to define the body:

unsafe impl<'v> AnyLifetime<'v> for Value<'v> { any_lifetime_body!(Value<'static>);
} 

Of these, the final one is unsafe, as you are duty-bound to ensure the implementation type is the same as that in the body, but with static for all lifetime arguments.

The biggest problem with this approach is that while Any is built into the compiler and has a blanket implementation that supplies implementations for every type, AnyLifetime requires specific instances. Furthermore, it’s currently impossible to give an AnyLifetime implementation for Vec<T> given an AnyLifetime for T, because such instances don’t compose structurally (something we’ve failed to implement with a nice API, but may become possible with generic associated types). Despite these limitations, we’ve found AnyLifetime essential in the cases we’ve needed it.

We hope that this blog helps you understand the AnyLifetime trait, 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 the Comparisons in Gazebo, which provides utilities for operations such as comparison chaining.

See also  Zornio: Could regulating Facebook help bring Americans back together? - The Colorado Sun

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

Advertisement

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.

Facebook Developers

Advertisement
Continue Reading
Advertisement

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  Zornio: Could regulating Facebook help bring Americans back together? - The Colorado Sun

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

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

FACEBOOK

Facebook Owner Meta Launches New Platform, Safety Hub to Protect Women in India

Published

on

By

Meta Image

Meta (formerly Facebook) on Thursday announced a slew of steps to protect woman users on its platform, including the launch of StopNCII.org in India that aims to combat the spread of non-consensual intimate images (NCII).

Meta has also launched the Women’s Safety Hub, which will be available in Hindi and 11 other Indian languages, that will enable more women users in India to access information about tools and resources that can help them make the most of their social media experience, while staying safe online.

This initiative by Meta will ensure women do not face a language barrier in accessing information Karuna Nain, director (global safety policy) at Meta Platforms, told reporters here.

“Safety is an integral part of Meta’s commitment to building and offering a safe online experience across the platforms and over the years the company has introduced several industry leading initiatives to protect users online.

“Furthering our effort to bolster the safety of users, we are bringing in a number of initiatives to ensure online safety of women on our platforms,” she added.

Advertisement

StopNCII.org is a platform that aims to combat the spread of non-consensual intimate images (NCII).

“It gives victims control. People can come to this platform proactively, hash their intimate videos and images, share their hashes back with the platform and participating companies,” Nain said.

She explained that the platform doesn’t receive any photos and videos, and instead what they get is the hash or unique digital fingerprint/unique identifier that tells the company that this is a known piece of content that is violating. “We can proactively keep a lookout for that content on our platforms and once it”s uploaded, our review team check what”s really going on and take appropriate action if it violates our policies,” she added.

See also  EU is investigating Facebook's Kustomer buyout over data concern

In partnership with UK Revenge Porn Helpline, StopNCII.org builds on Meta’s NCII Pilot, an emergency programme that allows potential victims to proactively hash their intimate images so they can”t be proliferated on its platforms.

The first-of-its-kind platform, has partnered with global organisations to support the victims of NCII. In India, the platform has partnered with organisations such as Social Media Matters, Centre for Social Research, and Red Dot Foundation.

Advertisement

Nain added that the company is hopeful that this becomes an industrywide initiative, so that victims can just come to this one central place to get help and support and not have to go to each and every tech platform, one by one to get help and support.

Also, Bishakha Datta (executive editor of Point of View) and Jyoti Vadehra from Centre for Social Research are the first Indian members in Meta”s Global Women”s Safety Expert Advisors. The group comprises 12 other non-profit leaders, activists, and academic experts from different parts of the world and consults Meta in the development of new policies, products and programmes to better support women on its apps.

“We are confident that with our ever-growing safety measures, women will be able to enjoy a social experience which will enable them to learn, engage and grow without any challenges.

“India is an important market for us and bringing Bishakha and Jyoti onboard to our Women”s Safety Expert Advisory Group will go a long way in further enhancing our efforts to make our platforms safer for women in India,” Nain said.

See also  Zornio: Could regulating Facebook help bring Americans back together? - The Colorado Sun

Advertisement
Continue Reading

FACEBOOK

Facebook Adds New Trend Insights in Creator Studio, Which Could Help Shape Your Posting Strategy

Published

on

By

facebook-adds-new-trend-insights-in-creator-studio,-which-could-help-shape-your-posting-strategy
en flag
sv flag

Facebook’s looking to provide more content insight within Creator Studio with the rollout of a new ‘Inspiration Hub’ element, which highlights trending content and hashtags within categories related to your business Page.

Facebook Inspiration Hub

As you can see in these screenshots, posted by social media expert Matt Navarra, when it becomes available to you, you’ll be able to access the new Inspiration Hub from the Home tab in Creator Studio.

At the right side of the screen, you can see the first of the new insights, with trending hashtags and videos from the last 24 hours, posted by Pages similar to yours, displayed above a ‘See more’ prompt.

When you tap through to the new hub, you’ll have a range of additional filters to check out trending content from across Facebook, including Page category, content type, region, and more.

Facebook Inspiration Hub

That could be hugely valuable in learning what Facebook users are responding to, and what people within your target market are engaging with in the app.

Advertisement

The Hub also includes insights into trending hashtags, within your chosen timeframe, which may further assist in tapping into trending discussions.

Facebook Inspiration Hub

How valuable hashtags are on Facebook is still up for debate, but you’ll also note that you can filter the displayed results by platform, so you can additionally display Instagram hashtag trends as well, which could be very valuable in maximizing your reach.

Much of this type of info has been available within CrowdTangle, Facebook’s analytics platform for journalists, for some time, but not everyone can access CrowdTangle data, which could make this an even more valuable proposition for many marketers.

See also  Facebook Joins Open Web Docs as Lead Funder

Of course, overall performance really relates to your own creative, and thinking through the action that you want your audience to take when reading your posts. But in terms of detecting new content trends, including hashtag usage, caption length, videos versus image posts, and more, there’s a lot that could be gleaned from these tools and filters.

It’s a significant analytics addition – we’ve asked Facebook for more info on the rollout of the new option, and whether it’s already beyond test mode, etc. We’ll update this post if/when we hear back.

Advertisement
Continue Reading

Trending