Ruby |
Railsタグが付けられた新着投稿 - Qiita |
importmap-railsでvue.jsの開発用ビルドと本番用ビルドの切り替えを行う |
https://qiita.com/dpkawa/items/b39b259156e55bfb9132
|
importmaprails |
2022-10-03 03:09:18 |
海外TECH |
DEV Community |
6 things you can do with the Cow 🐄 in Rust 🦀 |
https://dev.to/kgrech/6-things-you-can-do-with-the-cow-in-rust-4l55
|
things you can do with the Cow in Rust The Cow type is a mystery even for some intermediate level Rust developers Despite being defined as a simple two variant enumpub enum Cow lt a B gt where B a ToOwned Sized Borrowed amp a B Owned lt B as ToOwned gt Owned it challenges the developers to understand the ownership and lifetimes as well yet another mystery Borrow and ToOwned traits As a result programmers avoid using Cow which often leads to extra memory allocations which are not cheap and less efficient software What are the situations when you might consider using Cow Why does it have such a strange name Let s try to find some answers today A function rarely modifying the dataLet s start with the most common and straightforward use case for Cow type It is a good illustration of the situation when most developers including me encounter the Cow for the first time Consider the following function accepting and modifying the borrowed data in this case amp str fn remove whitespaces s amp str gt String s to string replace fn main let value remove whitespaces Hello world println value As you can see it does nothing but removes all white spaces from the string What is wrong with it What if in of calls the string contains no white spaces Or slight modification of the method when spaces should be removed based on some other condition In such cases we could avoid to string call and creation an unnecessary copy of the string However if we are to implement such logic we can use neither String no amp str type the first one forces the memory allocation and the last is immutable This is the moment when Cow plays its role We can return Cow Owned when the string is modified and Cow Borrowed s otherwise use std borrow Cow fn remove whitespaces s amp str gt Cow lt str gt if s contains Cow Owned s to string replace else Cow Borrowed s fn main let value remove whitespaces Hello world println value The nice thing about Cow lt str gt is that it could always be dereferenced into amp str later or converted into String by calling into owned The into owned only allocates the memory if the string was originally borrowed A struct optionally owning the dataWe often need to store references inside the structs If we have no such need you are likely ending up cloning data unnecessarily Considerstruct User lt a gt first name amp a str last name amp a str Would not it be nice to be able to create a user with a static lifetime User lt static gt owning its own data This way we could implement the method do something with user user accepting the same struct regardless of whether the data is cloned or borrowed Unfortunately the only way to create User lt static gt is by using amp static str But what if we have a String We can solve the problem by storing not amp a str but Cow lt a str gt inside the struct use std borrow Cow struct User lt a gt first name Cow lt a str gt last name Cow lt a str gt This way we can construct both owned and borrowed version of the User struct impl lt a gt User lt a gt pub fn new owned first name String last name String gt User lt static gt User first name Cow Owned first name last name Cow Owned last name pub fn new borrowed first name amp a str last name amp a str gt Self Self first name Cow Borrowed first name last name Cow Borrowed last name pub fn first name amp self gt amp str amp self first name pub fn last name amp self gt amp str amp self last name fn main Static lifetime as it owns the data let user User lt static gt User new owned James to owned Bond to owned println Name user first name user last name Static lifetime as it borrows static data let user User lt static gt User new borrowed Felix Leiter println Name user first name user last name let first name Eve to owned let last name Moneypenny to owned Non static lifetime as it borrows the data let user User new borrowed amp first name amp last name println Name user first name user last name A clone on write structThe examples above illustrate only one side of the Cow the ability to represent the data which borrowed or owned status is figured in not in compile time but in runtime But why was it named Cow then Cow stands for copy on write The examples above illustrate only one side of the Cow the ability to represent the data which borrowed or owned status is figured in not in compile time but in runtime The true power of Cow comes with to mut method If the Cow is owned it simply returns the pointer to the underlying data however if it is borrowed the data is first cloned to the owned from It allows you to implement an interface based on the structures lazily storing the references to the data and cloning it only if and for the first time the mutation is required Consider the code which receives the buffer of data in the form of amp u We would like to pass it over some logic conditionally modifying the data e g appending a few bytes and consume the buffer as amp u Similar to the example above we can t keep the buffer as amp u as we won t be able to modify it but converting it to Vec would lead to the copy being made every time We can achieve the required behavior by representing the data as Cow lt u gt use std borrow Cow struct LazyBuffer lt a gt data Cow lt a u gt impl lt a gt LazyBuffer lt a gt pub fn new data amp a u gt Self Self data Cow Borrowed data pub fn data amp self gt amp u amp self data pub fn append amp mut self data amp u self data to mut extend data This way we can pass borrowed data around without cloning up until the moment when and if we need to modify it fn main let data vec u No memory copied yet let mut buffer LazyBuffer new amp data println buffer data The data is cloned buffer append amp println buffer data The data is not cloned on further attempts buffer append amp println buffer data Keep your own type inside itMost likely you would end up using Cow lt str gt or Cow lt u gt but there are cases when you might want to store your own type inside it In order to use the Cow with a user defined type you would need to implemented owned and borrowed version of it The owned and borrowed version must by tied together by the following trait boundaries Owned version should implement the Borrow trait to produced a reference to the borrowed typeThe borrowed version should implement ToOwned trait to produce the owned type Implementation of the the Borrow trait is tricky and often unsafe Indeed in order for the fn borrow amp self gt amp Borrowed function to return a reference to Borrowed typed this reference should either be stored inside amp self or produced unsafely The above often means that the borrowed type is an unsized also know as dynamically sized type Their size is not known at compile time so they can only exist as a pointer or a reference Have you ever wondered why we use amp str everywhere and nearly never use str You can t find the definition of the str type in the standard library it is a primitive type part of the language Since str is a dynamically sized type it can only be instantiated through a pointer type such as amp str Trait object dyn T is another example of the dynamically sized type Imagine you would like to implement your own version of String and str type use std borrow Borrow Cow use std ops Deref derive Debug struct MyString data String derive Debug struct MyStr data str Since str is unsized so is MyStr You can then bound MyString and MyStr same way as String and str are bounded impl Borrow lt MyStr gt for MyString fn borrow amp self gt amp MyStr unsafe amp self data as str as const str as const MyStr impl ToOwned for MyStr type Owned MyString fn to owned amp self gt MyString MyString data self data to owned The unsafe pointer case inside the borrow method has probably drawn your attention While looking scary it is the usual pattern in the standard library have a look at e g Path type implementation Since MyStr is a single field struct it is guarantied to have zero cost compile time representation It means we can safely cast the valid pointer to str to the pointer to MyStr and then convert it to a reference We could also optionally implement the Deref trait for convenience and store MyString and MyStr into cow as well taking all advantages provided impl Deref for MyString type Target MyStr fn deref amp self gt amp Self Target self borrow fn main let data MyString data Hello world to owned let borrowed cow Cow lt MyStr gt Cow Borrowed amp data println borrowed cow let owned cow Cow lt MyStr gt Cow Owned data println owned cow Borrow the type as dyn TraitAs mentioned above the trait object is another example of dynamically sized type Somewhat surprising we can use Cow in a similar manner to implement dynamic dispatch similarly to Box lt dyn Trait gt and Arc lt dyn Trait gt Consider the following trait and struct implementations use std borrow Borrow Cow use std fmt Debug use std ops Deref trait MyTrait Debug fn data amp self gt amp str derive Debug struct MyString data String impl MyTrait for MyString fn data amp self gt amp str amp self data As MyString implements MyTrait we can borrow amp MyString as amp dyn MyTrait impl lt a gt Borrow lt dyn MyTrait a gt for MyString fn borrow amp self gt amp dyn MyTrait a self We can also convert any MyTrait implementation to MyString impl ToOwned for dyn MyTrait type Owned MyString fn to owned amp self gt MyString MyString data self data to owned Since we have defined Borrow and ToOwned we can now put MyString into Cow lt dyn MyTrait gt fn main let data MyString data Hello world to owned let borrowed cow Cow lt dyn MyTrait gt Cow Borrowed amp data println borrowed cow let owned cow Cow lt dyn MyTrait gt Cow Owned data println owned cow The above could be useful to implement e g the mutable vector of the trait objects fn main let data MyString data Hello world to owned let cow Cow lt dyn MyTrait gt Cow Borrowed amp data let data MyString data Hello world to owned let cow Cow lt dyn MyTrait gt Cow Owned data let mut vector Vec lt Cow lt dyn MyTrait gt gt vec cow cow Implement safe wrapper over FFI typeThe above MyString example is exciting but somewhat artificial Let s consider the real life pattern when you would like to store your own type inside the Cow Imagine you are using the C library in your rust project Let s say you receive a buffer of data from the C code in the form of the pointer const u and length usize Say you would like to pass the data around the layer of the rust logic possibly modifying it does it trigger you to think about Cow Finally you might want to access the data modified or not in rust as amp u or pass into another C function as the pointer const u and length usize Here we assume that this C function would not release the memory If this assumption surprises you consider reading ways to pass a string between Rust and C article As we would like to avoid cloning the data unnecessarily we would represent the buffer as the following struct use std borrow Borrow Cow use std fmt Debug Formatter use std ops Deref struct NativeBuffer pub ptr const u pub len usize This struct does not own its data it borrows it from the C pointer with an unknown lifetime For convince only we can implement the traits to access the buffer as amp u slice and print it impl Borrow lt u gt for NativeBuffer fn borrow amp self gt amp u unsafe std slice from raw parts self ptr self len impl Deref for NativeBuffer type Target u fn deref amp self gt amp Self Target self borrow impl Debug for NativeBuffer fn fmt amp self f amp mut Formatter lt gt gt std fmt Result let data amp u self borrow write f NativeBuffer data len data self len In order to store the NativeBuffer in the Cow we first need to define the owning version of it derive Debug struct OwnedBuffer owned data Vec lt u gt native proxy NativeBuffer impl ToOwned for NativeBuffer type Owned OwnedBuffer fn to owned amp self gt OwnedBuffer let slice amp u self borrow let owned data slice to vec let native proxy NativeBuffer ptr owned data as ptr len owned data len OwnedBuffer owned data native proxy The trick is to borrow the data as a slice and convert it to Vec We also need to store the NativeBuffer inside OwnedBuffer It contains a pointer to the data inside the vector and the length of it so we could implement the Borrow trait impl Borrow lt NativeBuffer gt for OwnedBuffer fn borrow amp self gt amp NativeBuffer amp self native proxy We can now define the method to mutate the data impl OwnedBuffer pub fn append amp mut self data amp u self owned data extend data self native proxy NativeBuffer ptr self owned data as ptr len self owned data len It is important to ensure to keep the native buffer pointers up to date We can finally put our borrowed buffer in the Cow and implement the conditional mutation logic for example fn main Simulates the data coming across FFI from C let data vec let ptr data as ptr let len data len let native buffer NativeBuffer ptr len let mut buffer Cow Borrowed amp native buffer NativeBuffer data len println buffer No data cloned assert eq buffer ptr ptr assert eq buffer len len if buffer len gt buffer to mut append amp OwnedBuffer owned data native proxy NativeBuffer data len println buffer Data is cloned assert ne buffer ptr ptr assert eq buffer len len let slice amp u amp buffer println slice The buffer is only cloned if the length of it is bigger than SummaryI sincerely hope that this post helped to demystify the Cow type and increase its adoption among the rust community If you like the article please put your reaction up and consider reading my other posts |
2022-10-02 18:37:02 |
Apple |
AppleInsider - Frontpage News |
Craig Federighi, Alan Dye talk about Dynamic Island's creation |
https://appleinsider.com/articles/22/10/02/craig-federighi-alan-dye-talk-about-dynamic-islands-creation?utm_medium=rss
|
Craig Federighi Alan Dye talk about Dynamic Island x s creationDynamic Island s creation came from thinking about a smaller TrueDepth camera array for the iPhone Pro an interview with SVP of software engineering Craig Federighi and VP of human interface design Alan Dye claims The Dynamic Island of the iPhone Pro and Pro Max has received positive feedback from users since its introduction replacing the often complained about notch In an interview about the software feature Craig Federighi and Alan Dye explain some of what went into its creation It s probably the first major operation change in five years since the iPhone X came out claimed Federighi to Axis following the removal of the Home button That hardware change caused a fundamental review of various iPhone operation methods such as how to unlock the lock screen return to the Home Screen and how to switch apps Read more |
2022-10-02 18:36:53 |
Apple |
AppleInsider - Frontpage News |
OWC Envoy Pro mini review: Enough speed in a small package |
https://appleinsider.com/articles/22/10/02/owc-envoy-pro-mini-review-enough-speed-in-a-small-package?utm_medium=rss
|
OWC Envoy Pro mini review Enough speed in a small packageThe OWC Envoy Pro mini thumb drive s latest version embraces the aluminum clad USB C future providing a nice balance of performance and size for tech professionals on the go External storage for the Mac and iPad Pro can take a few forms including the thumb drive and the full blown external SSD in an enclosure While the former is typically smaller the latter generally offers more in terms of capacity and speed Launched in May the OWC Envoy Pro mini is clearly a double ended flash drive But because of design and engineering choices it approaches the performance of a larger external SSD Read more |
2022-10-02 18:53:37 |
ニュース |
BBC News - Home |
Tory conference: Labour favourites to win power at next election, says John Curtice |
https://www.bbc.co.uk/news/uk-politics-63110539?at_medium=RSS&at_campaign=KARANGA
|
pollster |
2022-10-02 18:39:52 |
ニュース |
BBC News - Home |
After chess, cheating rows rock poker and fishing |
https://www.bbc.co.uk/news/world-us-canada-63108879?at_medium=RSS&at_campaign=KARANGA
|
surprising |
2022-10-02 18:39:50 |
ニュース |
BBC News - Home |
They stayed for the storm - what happens now? |
https://www.bbc.co.uk/news/world-us-canada-63105430?at_medium=RSS&at_campaign=KARANGA
|
hurricane |
2022-10-02 18:54:13 |
ニュース |
BBC News - Home |
England in Pakistan: Dawid Malan guides tourists to Twenty20 series win |
https://www.bbc.co.uk/sport/cricket/63109822?at_medium=RSS&at_campaign=KARANGA
|
pakistan |
2022-10-02 18:28:10 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
世帯年収1000万円の夫婦「私立中学に子ども2人行かせて大丈夫?」FPの答えは - “残念サラリーマン”のお金相談所 |
https://diamond.jp/articles/-/310644
|
世帯年収 |
2022-10-03 04:00:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
JR西日本が奈良線を大改良する理由、壮大な工事の「最大の難所」とは - News&Analysis |
https://diamond.jp/articles/-/310579
|
newsampampanalysisjr |
2022-10-03 03:55:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
宿泊業を救うDXツール「サイトコントローラー」とは?関所ビジネスの驚くべき収益性 - 山田英夫のビジネスモデル・ラボ |
https://diamond.jp/articles/-/310473
|
|
2022-10-03 03:50:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
学歴や年収が高くなった子どもに共通する「IQより重要なある力」とは - 教育現場は困ってる |
https://diamond.jp/articles/-/310482
|
|
2022-10-03 03:45:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
日常の「めんどくさい」が全て消える脳の使い方、仕事・人間関係・家事… - 要約の達人 from flier |
https://diamond.jp/articles/-/310631
|
日常の「めんどくさい」が全て消える脳の使い方、仕事・人間関係・家事…要約の達人fromflier感情は自分の中に閉じ込めず、口にしたほうが、スッキリする。 |
2022-10-03 03:40:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
日産エクストレイル新型、車内は広くて上質!走りの実力も大幅アップ【試乗記】 - CAR and DRIVER 注目カー・ファイル |
https://diamond.jp/articles/-/310608
|
caranddriver |
2022-10-03 03:35:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
非製造業の慎重な投資姿勢、企業の負担を軽減し成長投資の促進を - 数字は語る |
https://diamond.jp/articles/-/310645
|
季節調整値 |
2022-10-03 03:30:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
ほけんの窓口・猪俣礼治社長に聞く、就任から半年の手応えと新経営方針の中身 - ダイヤモンド保険ラボ |
https://diamond.jp/articles/-/310646
|
乗り合い |
2022-10-03 03:25:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
英金融混乱の教訓:恐れるべきは債券でなく通貨 - WSJ PickUp |
https://diamond.jp/articles/-/310647
|
wsjpickup |
2022-10-03 03:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
高校生は眠い 午前8時前の始業時間は有害 睡眠科学者 - WSJ PickUp |
https://diamond.jp/articles/-/310648
|
wsjpickup |
2022-10-03 03:15:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
強行プーチン氏、「行き過ぎ」リスク高まる - WSJ PickUp |
https://diamond.jp/articles/-/310649
|
wsjpickup |
2022-10-03 03:10:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【お寺の掲示板104】他人の不幸の上に自分の幸福を築いてはならない - 「お寺の掲示板」の深~いお言葉 |
https://diamond.jp/articles/-/310257
|
野比のび太 |
2022-10-03 03:05:00 |
コメント
コメントを投稿