Monday, August 29, 2022
Packed structs in Zig make bit/flag sets trivial
As we’ve been building Mach engine, we’ve been using a neat little pattern in Zig that enables writing flag sets more nicely in Zig than in other languages.
What is a flag set?
We’ve been rewriting mach/gpu (WebGPU bindings for Zig) from scratch recently, so let’s take a flag set from the WebGPU C API:
typedef uint32_t WGPUFlags;
typedef WGPUFlags WGPUColorWriteMaskFlags;
Effectively, WGPUColorWriteMaskFlags here is a 32-bit unsigned integer where you can set specific bits in it to represent whether or not to write certain colors:
typedef enum WGPUColorWriteMask {
WGPUColorWriteMask_None = 0x00000000,
WGPUColorWriteMask_Red = 0x00000001,
WGPUColorWriteMask_Green = 0x00000002,
WGPUColorWriteMask_Blue = 0x00000004,
WGPUColorWriteMask_Alpha = 0x00000008,
WGPUColorWriteMask_All = 0x0000000F,
WGPUColorWriteMask_Force32 = 0x7FFFFFFF
} WGPUColorWriteMask;
Then to use it you’d use the various bit operations with those masks, e.g.:
WGPUColorWriteMaskFlags mask = WGPUColorWriteMask_Red | WGPUColorWriteMask_Green;
mask |= WGPUColorWriteMask_Blue; // set blue bit
This all works, people have been doing it for years in C, C++, Java, Rust, and more. In Zig, we can do better.
Zig packed structs

Zig has packed structs: these let us pack memory tightly, where a bool is actually a single bit (in most other languages, this is not true.) Zig also has arbitrary bit-width integers, like u28, u1 and so on.
We can write WGPUColorWriteMaskFlags from earlier in Zig using:
pub const ColorWriteMaskFlags = packed struct {
red: bool = false,
green: bool = false,
blue: bool = false,
alpha: bool = false,
_padding: u28 = 0,
};
This is still just 32 bits of memory, and so can be passed to the same C APIs that expect a WGPUColorWriteMaskFlags - but interacting with it is much nicer:
var mask = ColorWriteMaskFlags{.red = true, .green = true};
mask.blue = true; // set blue bit
In C you would need to write code like this:
if (mask & WGPUColorWriteMask_Alpha) {
// alpha is set..
}
if (mask & (WGPUColorWriteMask_Alpha|WGPUColorWriteMask_Blue)) {
// alpha and blue are set..
}
if ((mask & WGPUColorWriteMask_Green) == 0) {
// green not set
}
In Zig it’s just:
if (mask.alpha) {
// alpha is set..
}
if (mask.alpha and mask.blue) {
// alpha is set..
}
if (!mask.green) {
// green not set
}
Comptime validation
Making sure that our ColorWriteMaskFlags ends up being the same size could be a bit tricky: what if we count the number of bool wrong? Or what if we accidently get the padding size wrong? Then it might not be the same size as a uint32 anymore.
Luckily, we can verify our expectations at comptime:
pub const ColorWriteMaskFlags = packed struct {
red: bool = false,
green: bool = false,
blue: bool = false,
alpha: bool = false,
_padding: u28 = 0,
comptime {
std.debug.assert(@sizeOf(@This()) == @sizeOf(u32));
std.debug.assert(@bitSizeOf(@This()) == @bitSizeOf(u32));
}
}
The Zig compiler will take care of running the comptime code block here for us when building, and it will verify that the byte size of @This() (the type we’re inside of, the ColorWriteMaskFlags struct in this case) matches the @sizeOf(u32).
Similarly we could check the @bitSizeOf both types if we like.
Note that @sizeOf may include the size of padding for more complex types, while @bitSizeOf returns the number of bits it takes to store T in memory if the type were a field in a packed struct/union. For flag sets like this, it doesn’t matter and either will do. For more complex types, be sure to recall this.
Thanks for reading
Be sure to join the new Mach engine Discord server where we’re building the future of Zig game development.
You can also sponsor my work if you like what I’m doing! :)
from Hacker News https://ift.tt/gMu6Ta1
Giant Keyboard Is Just Our Type
We like big keyboards and we cannot lie, and we’ve seen some pretty big keyboards over the years. But this one — this one is probably the biggest working board that anyone has ever seen. [RKade] and [Kristine] set out to make the world’s largest keyboard by Guinness standards – and at 16 feet long, you would think they would be a shoe-in for the world record. More on that later.
As you might have figured out, what’s happening here is that each giant key actuates what we hope is a Cherry-brand lever switch that is wired to the pads of a normal-sized keyboard PCB. Once they designed the layout, they determined that there were absolutely no existing commercial containers that, when inverted, would fit the desired dimensions, so they figured out that it would take 350 pieces of cardboard to make 70 5-sided keycaps and got to work.
Aside from the general awesomeness of this thing, we really like the custom buttons, which are mostly made of PVC components, 3D printed parts, and a bungee cord for the return spring.
[RKade] encountered a few problems with the frame build — mostly warped boards and shrunken holes where each of the 70 keys mount. After the thing was all wired up (cleverly, we might add, with Ethernet cable pairs), [RKade] rebuilt the entire frame out of three-layers of particle board.
By the way, Guinness rejected the application, citing that it must be an exact replica of an existing keyboard, and it must be built to commercial/professional standards. They also contradict themselves, returning no search results for biggest keyboard, but offer upon starting a world record application that there is a record-holding keyboard on file after all, and it is 8 ft (2.4 m) long. It’s not the concrete Russian keyboard, which is non-functional, but we wonder if it might be the Razer from CES 2018 that uses Kailh Big Switches.
Once the keyboard was up and running, [RKade] and [Kristine] duke it out over a game of Typing Attack, where the loser has to type all the lyrics to “Never Gonna Give You Up” on the giant keyboard. Check it out after the break.
Via KBD #92
from Hacker News https://ift.tt/EzDoqHr
New Zealand's plan to prepare for inevitable climate change impacts
Opinion - New Zealand's first climate adaptation plan, launched his week, provides a robust foundation for urgent nation-wide action.
Its goals are utterly compelling: reduce vulnerability, build adaptive capacity and and strengthen resilience.
Recent reports by the Intergovernmental Panel on Climate Change (IPCC) have underscored the need for effective and transformative efforts to cut emissions urgently while also adapting and preparing for inevitable impacts of climate change.
But this national adaptation plan is just the beginning. The hard work is yet to come in its implementation. It is regrettable that proposed new law that would provide the institutional architecture for climate adaptation has been delayed until the end of next year.
Based on my experience as an IPCC author and working with communities around Aotearoa New Zealand and overseas, there are five key areas that need sharper focus as we begin to translate the intentions of the plan into practical reality.
Reducing risk for people on the 'frontline' of impacts
First, climate change will affect every aspect of life. These impacts will often be the result of climate-compounded extreme events that are already becoming more frequent and intense.
The people hardest hit are invariably those who are more vulnerable. We need to pay more focused attention to the root causes and drivers of vulnerability - and actions to reduce vulnerability and, ultimately, climate risk.
This means addressing poverty, marginalisation, inequity and other structural causes of vulnerability. Historically, much risk-based work has centred on calculations based on a formula that considers risk as a product of hazard and vulnerability. This approach is too technical.
We need to focus on reducing social vulnerability to climate change impacts, especially for those on the "frontline" of exposure to climate impacts, such as coastal communities facing rising sea level. Every region and locality needs to be able to identify and prioritise who is most exposed and vulnerable and catalyse proactive actions to reduce this vulnerability.
A climate-resilient future
Second, the plan clearly recognises the vital role of all governance actors in implementing it. However, in practice, local government will carry an especially significant responsibility in translating this plan into action.
There does not appear to be sufficient attention focused on how the adaptive capacity of local government will be built in this first stage of implementation. Local government will be the fulcrum for enabling - or hampering - adaptation at the local level.
Transformational capability building, from the political to operational level of local government, is imperative and needs to happen in partnership with tangata whenua, central government, the private sector (which receives scant attention in this plan) and civil society.
Third, introducing the concept of climate-resilient development is a welcome framing. This is an emerging concept, highlighted in a chapter of the IPCC report on adaptation. Climate-resilient development recognises the inherent intertwining of mitigation and adaptation efforts to advance sustainable development.
The plan limits the concept to climate-resilient "property development". There is work to be done to deepen and extend this framing along the lines of the IPCC work.
Who should pay if people have to move?
Fourth, managed retreat looms large with so many New Zealanders living along rivers and the shoreline. We can only enable proactive retreat from imminent danger if the government determines who should pay.
At present, the trigger for retreat is usually an extreme event, often at huge cost to those impacted. In many cases, those in harm's way cannot afford to retreat without government support. Often they are in localities approved by governing authorities.
Who should contribute to measures that reduce risk and enable retreat from climate-compounded hazards? What proportion of costs should be borne by those exposed or impacted and what proportion should be contributed by local and central government? And who makes the call for managed retreat and whether it should be voluntary or compulsory?
The "who pays" question is a tough call. The plan doesn't provide an answer but we can't avoid it if it is to be implemented.
Fifth, it is inevitable there will be "winners" and "losers" in the ongoing struggle to adapt to a changing climate. Values and interests will collide and contestation will escalate as climate impacts become more intense and frequent.
We'll need to find more constructive ways to resolve climate-compounded conflict. At times government will be only one of several parties involved and won't be in a position to enable or guide conflict resolution. For this, we'll have to develop institutional processes and capabilities to facilitate independent mediated negotiation solutions for escalating climate conflicts.
* Bruce Glavovic is Professor in Natural Hazards Planning and Resilience at Massey University. He receives funding from MBIE.
This story first appeared in The Conversation.
from Hacker News https://ift.tt/sFvWNjK
Project Highwater
Project Highwater was an experiment carried out as part of two of the test flights of NASA's Saturn I launch vehicle (using battleship upper stages), successfully launched into a sub-orbital trajectory from Cape Canaveral, Florida. The Highwater experiment sought to determine the effect of a large volume of water suddenly released into the ionosphere.[1][2] The project answered questions about the effect of the diffusion of propellants in the event that a rocket was destroyed at high altitude.[3]
The first flight, SA-2, took place on April 25, 1962. After the flight test of the rocket was complete and first stage shutdown occurred, explosive charges on the dummy upper stages destroyed the rocket and released 23,000 US gallons (87,000 L) of ballast water weighing 95 short tons (86,000 kg) into the upper atmosphere at an altitude of 65 miles (105 km),[4] eventually reaching an apex of 90 miles (145 km).[3]
The second flight, SA-3, launched on November 16, 1962, and involved the same payload. The ballast water was explosively released at the flight's peak altitude of 104 miles (167 km).[5][6] For both of these experiments, the resulting ice clouds expanded to several miles in diameter and lightning-like radio disturbances were recorded.[3][4]
See also[edit]
References[edit]
- ^ von Ofenheim, Bill (January 20, 2004). "Saturn I SA-2 Launch". NASA Scientific and Technical Information Program. Archived from the original on May 17, 2011. Retrieved July 2, 2009.
- ^ Wade, Mark. "Highwater". Astronautix.com. Archived from the original on January 16, 2010. Retrieved December 5, 2009.
- ^ a b c Bilstein, Roger E (1996). Stages to Saturn: A Technological History of the Apollo/Saturn Launch Vehicles. Washington, DC: NASA History Office. ISBN 0-16-048909-1. Archived from the original on 2004-10-15.
- ^ a b "Saturn Aids GSFC Research" (PDF). Goddard News. 2 (10). May 4, 1962. Archived from the original (PDF) on July 21, 2011.
- ^ Ryba, Jeanne (July 8, 2009). "History: Saturn Test Flights". NASA.gov. Retrieved December 5, 2009.
- ^ Wade, Mark. "Cape Canaveral LC34". Astronautix.com. Archived from the original on January 31, 2010. Retrieved December 5, 2009.
Further reading[edit]
- Woodbridge, David D; Lasater, James A; et al. (October 25, 1963). An Analysis of the Second Project High Water Data. NASA. hdl:2060/19790078055. NAS10-841.
from Hacker News https://ift.tt/EGD3RkQ
The Silent Majority in Software
Table of Contents
The “silent majority” was used by President Richard Nixon during his presidency and his campaign against the Vietnam war. He spoke to the people who were not actively voicing their opinions and who were overshadowed by the vocal few who were supporting the war.
We're not talking about politics. This interesting concept of the majority being overshadowed by the vocal few is quite fascinating and holds true in software engineering.
In software development, the silent majority are the engineers who write the code, debug the programs, and solve the complex issues behind the scenes. They do not participate in controversial discussions about Visual Basic or Pascal — they just do their work in those languages without even knowing that there’s so much controversy surrounding their language of choice.
Without this silent majority, many projects would, in fact, grind to a halt. It is often their quiet diligence that keeps a project on track and prevents it from falling apart.
There also seems to be an assumption on HN/Reddit that vocal activity on the internet, in any form — be that videos, blogging, podcasts, etc. — is proportional to activity behind the screen. If you’re constantly seeing stuff about crypto, then you’re probably scrolling Twitter, but if you leave that bubble and go outside — most people don’t care.
Silent Engineers
While browsing HackerNews, I sometimes get the feeling that every developer out there is working for FAANG, as there are always posts from those people doing some hyped stuff. Or you might think that PHP is never used nowadays because whenever it’s mentioned, everyone is hating on it in the comments.
But let’s be straight, that’s like 1% of all of the developers out there — the rest of them are just lurking and coding with their language of choice and being content with it. Be it Fortran, COBOL, Perl, or PHP. I’ve seen so much hate some languages get that I’m surprised anyone still writes code in those languages, but then I remember that everything is subjective, and the articles that I read represent every small subset of developers.
Even HackerNews is not that popular — I know many great engineers who’ve never visited the website. There are so many articles and comments by people whose level of enthusiasm doesn't match their experience. Maybe also my own, but I just like writing, so deal with it.
Usually, the comments on HN/Reddit are polarised by a single group of people who have the same opinion, and then it’s hard to object and present a different perspective, even if you speak with more experience and context than the masses.
It’s also important to understand that we have a generational divide among software engineers. There are thousands of new software developers each year that have been taught differently than the previous generation. This introduces a bias to the particular expertise that gets shared.
Some developers signed so many NDAs over the years it almost looks like they did nothing at all.
I really like that some subset of the silent majority still participates on GitHub with bug fixes to their favorite libraries. Sometimes I’ve seen Pull Requests from empty accounts with a brief explanation of what was implemented. They just submit bug fixes, no drama.
Silent Users
I’m sure you’re aware of the importance of customer feedback. After all, it's essential to know what users think of your product to improve it. However, there are users who never give feedback, either because they're happy with the product as it is or because they don't bother to take the time to fill out surveys and submit bug reports — the silent majority of your customers.
As a result, companies often have a skewed view of their user base and improve the wrong things, thinking that the only people they should optimize for, are the people who fill out their “what did you like about this service” surveys. I never fill out those btw, it’s a waste of time. If I’m using a service, I’m already satisfied with it. Otherwise, I would jump to another one.
You can't rely on silent customers to give you honest feedback, but you can still learn a lot from them. Observing how they use your product is the first thing and setting up proper analytics to get an insight into their needs and expectations is the second.
The problem with silent customers is that while they often demand very little, they will also silently switch providers if they’re not happy.
In defense of being vocal
Being vocal is hard. It might seem easy — you just write an article or make a video — but there’s a reason why only a small percentage do it. It takes huge amounts of time. Even this small newsletter issue took me a few hours on my weekend to write. Not everyone is willing to do the work just to bring their opinions to the masses.
It also takes confidence — whenever you voice an opinion on the internet, there will always be people who have an opposite one, so you need to prepare yourself to read tens of comments that disagree with you. Reading negative comments can be disheartening, but it's important to remember that not everyone will agree with you. And that’s fine, we’re all amateurs, and sometimes we can be wrong.
My thoughts
And now to my final thoughts. When it comes to the software community, there are two schools of thought. Some people believe that it's important to be vocal and share your opinions, while others believe that it's better to stay quiet and let the quality of your work speak for itself. Personally, I believe that being more vocal can only be a good thing.
First of all, when you're vocal, you're more likely to be heard. If you have something valuable to say, then you owe it to yourself and to the community to speak up. Secondly, being more vocal can help to create a more inclusive community. Too often, online conversations are dominated by a small subset of people. By speaking up, we can help to ensure that everyone's voices are heard.
Of course, you can get downvoted, but who cares?
In many cases, fear is what’s holding us back - fear of criticism, or of saying something stupid. But if we want the software community to thrive, we need to get over that fear and start speaking up. It's time for us to be bolder and more vocal. Only then can we hope to create a truly inclusive community where everyone feels welcome and valued.
Other Newsletter Issues:
from Hacker News https://ift.tt/L7Rmtru
A history of the blurb, every author’s best friend
Blurb is such a wonderful word.
It conjures up exactly what it is: a belch of praise for a book, generally found on the dust jacket, to lure the reader to purchase it. I must admit to reading blurbs when deciding whether to buy a book, but I am swayed only by plaudits from publications I trust or authors I greatly admire.
Some blurbs from trade journal Kirkus Reviews, for example, for which authors pay and are often just a rehash of the book’s plot, don’t work for me. Or one from writer Gary Shteyngart, who was formerly known, as Salon magazine put it, as a “blurb-addict.” In a 2014 open letter published in the New Yorker, he revealed that “the volume of requests has exceeded my abilities, and I will be throwing my ‘blurbing pen’ into the Hudson River.”
According to Merriam-Webster, the term “blurb” was coined in 1907 at an annual dinner of the American Booksellers Association by American humorist Gelett Burgess, one of the honored guests.
“It was a custom at these dinners for the guest authors to present to the assembled company souvenir copies of their latest books. Burgess prepared a mock jacket of his latest book featuring a doctored picture of a woman that he had lifted from a dental advertisement.
“The woman was dubbed ‘Miss Belinda Blurb,’ and she was shown in the picture as calling out a ‘blurb,’ indicated by the caption ‘Miss Belinda Blurb in the act of blurbing.’ Self-congratulatory text also adorned the jacket.”
But the practice might be older still. The New York Times reports that on reading the first edition of “Leaves of Grass” in 1855, Ralph Waldo Emerson, already widely esteemed, mailed the relatively unknown Walt Whitman a glowing note. The next year, one line of that letter – “I greet you at the beginning of a great career” — was printed on the spine of the book’s second edition.
Speaking of impressive blurbs, among the blurbers on the back of Samantha Power’s 2019 memoir, “The Education of an Idealist,” are Barack Obama, Doris Kearns Goodwin, Bryan Stevenson and Madeleine Albright. Not too shabby.
Oddly, some of the best-known reclusive writers, among them Thomas Pynchon and J.M. Coetzee, don’t hesitate to blurb. Other famous authors often blurb their former students’ work, notably Joyce Carol Oates on Jonathan Safran Foer and Chinua Achebe on Chimamanda Ngozi Adichie.
Some of the most commonly used blurb phrases:
Laugh-out-loud funny (Really? In my long reading career, very few books have achieved this.)
Like x crossed with y (Don’t use this if the book being reviewed isn’t as good as either of the books mentioned.)
A page-turner (Literally applies to every book.)
A literary tour de force (Does using French words make you sound smarter?)
A roller-coaster ride (Meaning nauseating?)
In one of my favorite over-the-top blurbs ever, Frank McCourt once compared Mitch Albom’s “The Five People You Meet in Heaven” to “The Odyssey.” Whoa!
I shudder to admit I’ve used some of these shopworn expressions in my reviews of books. After all, there are just so many words available. But it’s different when you have the room to expand upon your statements and provide backup evidence.
One of my favorite book titles, which sounds like a blurb and undoubtedly was meant ironically, is Dave Eggers’ memoir (with fictional elements), “A Heartbreaking Work of Staggering Genius.”
Are there any good blurbs? Of course. I loved New York Times critic Dwight Garner’s blurb about Irish author Sally Rooney’s fiction: “In my experience when people who’ve read her meet they tend to peel off into corners to talk.” And Harper’s blurb gracing Orhan Pamuk’s novel “Snow”: “From the Golden Horn, with a wicked grin, the political novel makes a triumphant return.”
Here’s the blurb I want for my own novel (which has been sitting on the shelf for years due to my procrastination over the serious edit it needs): “Undeniably worth the wait. Clearly a mature writer who delayed publication until every word was perfect.”
Editor’s note: This column has been updated since it originally published to correct a statement about Kirkus Reviews.
from Hacker News https://ift.tt/FB3AsUZ
