RustのString/strは有効なUTF-8を維持しますが、オペレーティングシステムのパスは必ずしもUTF-8で表現できるとは限りません。データがテキスト、生バイト、またはシステムパスのいずれを表しているかをまず判断し、情報損失のない型と操作を選択する必要があります。
所有と借用は第1の軸
所有内容 借用ビュー 保証
String str / &str 有効なUTF-8テキスト
Vec [u8] / &[u8] 任意のバイト、テキストエンコーディングは保証しない
OsString OsStr / &OsStr プラットフォーム文字列、表現可能な内容を保持
PathBuf Path / &Path プラットフォームのパスコンポーネントセマンティクス
&strはStringの一部を借用できます。文字列リテラルを指すだけでなく、自動的に'staticライフタイムを持つわけではありません。Stringの安全なAPIはUTF-8不変条件を維持しますが、unsafeで構築または変更する場合、呼び出し手はそれを維持し続けなければならず、コンパイラがすべてのメモリ操作を自動的に検証するわけではありません。String
バイト、char、表示文字は異なる
UTF-8バイト:6バイト 65 | CC 81 | E4 B8 AD Unicodeスカラー値:3個 U+0065、U+0301、U+4E2D 拡張グラフームクラス:通常2個 同じテキストでも、カウント単位が異なる:e + 結合アクセント + 中 e + 結合アクセントが1つのクラスを構成;中がもう1つのクラスを構成 RustのcharはUnicodeスカラー値を表します。ユーザーが認識する文字や端末での表示幅には、他のルールが必要です。
fn main ( ) {
let text = " e\u{301} 中" ;
assert_eq! ( text.len ( ) , 6 ) ;
assert_eq! ( text.chars ( ) .count ( ) , 3 ) ;
assert_eq! ( text.char_indices ( ) .collect:: < Vec< _ > > ( ) ,
[ ( 0 , ' e' ) , ( 1 , ' \u{301} ' ) , ( 3 , ' 中' ) ] ) ;
assert_eq! ( text.get ( 1 .. 3 ) , Some ( " \u{301} " ) ) ;
assert_eq! ( text.get ( 2 .. 3 ) , None ) ; }
lenはバイト数をカウントし、charsはUnicodeスカラー値を反復処理します。Unicodeにおける「コードポイント」には、Rustのcharとして不適切なサロゲートなども含まれるため、正確に議論する際には「スカラー値」という概念を使用すべきです。
ユーザーが見る1文字は複数のスカラー値で構成される場合があり、絵文字シーケンスが常に4バイトのスカラー値1つだけである必要はありません。エディタでのカーソル移動やユーザー名の切り捨てなどのタスクには、通常、グラフームクラス分割ルールが必要です。表示される列幅はまた別の問題です。Unicodeテキスト分割
インデックスはまず単位を選択する必要がある
Rustには、text[n]で「n文字目」を返すインターフェースは提供されていません。なぜなら、この言葉はバイト、スカラー値、またはグラフームクラスのいずれかを指す可能性があり、コストとセマンティクスが異なるからです。
nバイト目の読み取り:text.as_bytes().get(n)。
nスカラー値目の読み取り:text.chars().nth(n)。通常、前方のエンコーディングをスキャンする必要がある。
バイト範囲によるテキストの借用:text.get(a..b)。範囲およびUTF-8境界が有効である必要がある。
グラフームクラスが必要:対応するUnicode分割ルールを実装するライブラリを採用し、そのUnicodeバージョンを明確にする。
無効な範囲または境界で直接&text[a..b]を行うとパニックします。getはOptionを使用して失敗を表します。ループ内で繰り返しchars().nth(i)を行うと、前方スキャンが重複して二次的な計算量になる可能性があるため、通常はchars/char_indicesの反復を1回で完了させるべきです。
有効なUTF-8であっても、Unicode正規化済みであるとは限りません。プリコンポーズされたéとe+結合アクセントは、通常、文字列の等値比較では等しく見なされません。検索や一致にどのような正規化戦略が必要かは、ビジネスロジックが明確に決定すべきです。
バジェットを制限されたバイト数で前方に移動し、有効な境界を探す
fn prefix_bytes ( text : & str , budget : usize ) -> & str {
let mut end = budget.min ( text.len ( ) ) ;
while ! text.is_char_boundary ( end) {
end - = 1 ;
}
& text[ .. end]
}
fn main ( ) {
assert_eq! ( prefix_bytes ( " 中ab" , 2 ) , " " ) ;
assert_eq! ( prefix_bytes ( " 中ab" , 4 ) , " 中a" ) ;
assert_eq! ( prefix_bytes ( " 中ab" , 100 ) , " 中ab" ) ;
assert_eq! ( prefix_bytes ( " e\u{301} " , 1 ) , " e" ) ;
}
これは、「指定されたUTF-8バイト数を超えず、結果が有効なテキストである」という契約を満たします。最後のアサートは、その境界を露呈しています。結合アクセントを文字の後ろから切り離すことができます。ネットワークフィールドのバイト上限には適しているかもしれませんが、ユーザーに表示されるニックネームには、グラフームクラスルールに基づいて切り捨て点を決定する必要があります。返されるのは元のテキストの借用であり、新しいStringは作成されません。そのため、借用がまだ使用されている間に、元の文字列を任意に変更することはできません。
テキストの等値比較は正規化を自動的に行わない
fn main ( ) {
let composed = " \u{e9} " ;
let decomposed = " e\u{301} " ;
assert_ne! ( composed, decomposed) ;
assert_eq! ( composed.len ( ) , 2 ) ;
assert_eq! ( decomposed.len ( ) , 3 ) ;
assert_eq! ( " a\n b\n " .lines ( ) .collect:: < Vec< _ > > ( ) , [ " a" , " b" ] ) ;
assert_eq! ( " a\n b\n " .split ( ' \n ' ) .collect:: < Vec< _ > > ( ) , [ " a" , " b" , " " ] ) ;
}
linesとsplitのどちらを選択するかは、プロトコルによっても異なります。前者は行セマンティクスで処理し、後者は区切り文字で末尾の空セグメントを保持します。空フィールドを保持したり、改行を正確に保持したりする必要がある場合、簡潔さのために安易に置き換えてはいけません。正規化、大文字小文字の変換、空白の除去も同様に、データ解釈の戦略に属し、入力境界で明確にし、表示や監査のために必要な元の表現を保持する必要があります。
UTF-8 の境界と見える文字の境界は違う
バイト上限の切り詰めでは、UTF-8 を壊さないことと、見える文字の分割を許すかを別々に考えます。2・3 バイトは「中」の符号の途中、5 バイトは有効な UTF-8 でも e のアクセントを切り離します。境界ごとに異なる方針が必要です。
図を準備しています 再読み込み
UTF-8 の境界と見える文字の境界は違う 有効な UTF-8 で切っても、e と結合アクセントを分離することがあります。
{"id":"rust-utf8-boundaries","title":"UTF-8 の境界と見える文字の境界は違う","summary":"有効な UTF-8 で切っても、e と結合アクセントを分離することがあります。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><div class=\"control\"><label for=\"budget\" data-i18n=\"budget\"></label><output for=\"budget\" id=\"budget-value\"></output><input id=\"budget\" type=\"range\" min=\"0\" max=\"7\" value=\"5\" step=\"1\"></div><div class=\"track-row\"><span data-i18n=\"bytes\"></span><div id=\"bytes\" class=\"track\"></div></div><section class=\"panel\"><h3 data-i18n=\"scalar\"></h3><div id=\"scalar\"></div></section><section class=\"panel\"><h3 data-i18n=\"grapheme\"></h3><div id=\"grapheme\"></div></section><div class=\"metrics\"><div><span data-i18n=\"direct\"></span><strong id=\"direct\"></strong></div><div><span data-i18n=\"safe\"></span><strong id=\"safe\"></strong></div></div><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"ok\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"split\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"invalid\"></p></div><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n.track{flex-wrap:wrap}.cell{flex-basis:20%}.metrics strong{font-size:16px;min-height:4em}.panel>div{font:13px ui-monospace,monospace;min-height:2.4em}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));function draw(){let k=n('budget'),bs=[0x41,0xe4,0xb8,0xad,0x65,0xcc,0x81],bounds=[0,1,4,5,7],end=Math.max(...bounds.filter(x=>x<=k)),decoder=new TextDecoder(),s=decoder.decode(new Uint8Array(bs.slice(0,end))),valid=bounds.includes(k);set('budget-value',k+' B');cells('bytes',bs.map((b,i)=>({text:i+'\\n'+b.toString(16).toUpperCase(),cls:i<end?'on':i<k?'gold':'empty'})));set('scalar','0 │ A │ 1 │ 中 │ 4 │ e │ 5 │ ◌́ │ 7');set('grapheme','0 │ A │ 1 │ 中 │ 4 │ é │ 7');set('direct',valid?'Some(\"'+s+'\")':'None');set('safe','\"'+s+'\" ('+end+' B)');set('explanation',t(!valid?'invalid':end===5?'split':'ok'));document.body.dataset.end=end;}inputs(draw);","audio":false,"strings":{"budget":"バイト上限","bytes":"UTF-8 のバイトと位置","direct":"text.get(..budget)","grapheme":"書記素境界","heading":"UTF-8 の境界と見える文字の境界は違う","intro":"バイト上限を動かし、get(..budget) と直前の UTF-8 境界への切り下げを比べます。","invalid":"上限がマルチバイト符号の途中にあるため get は None です。前に戻すと有効な文字列になります。","ok":"ここはこの例の UTF-8 境界かつ書記素境界です。","reset":"リセット","safe":"境界へ切り下げた文字列","scalar":"スカラー境界","scope":"固定文字列 A中é(U+0301)を使います。書記素境界はこの例の注記で、汎用の分割ライブラリではありません。","scopeLabel":"モデルの範囲と前提","split":"有効な UTF-8 ですが e の結合アクセントが切り離され、見える文字を分割しています。"}}
バイトからテキストへの変換で、損失の許容を明確にする
String::from_utf8は所有するバイトベクトルをチェックし、失敗時はエラーから元のバイトを取り戻すことができます。str::from_utf8は借用スライスに対してチェックを行います。from_utf8_lossyは不正なシーケンスを置き換え文字で表示し、特定のログには適していますが、損失のない戻しが必要なプロトコルやファイル名には適していません。
Stringは末尾にC言語のNULバイトがあることを保証しません。C文字列との相互運用にはCString/CStrを使用し、内部のNULと外部のバッファのライフサイクルを考慮してください。C ABIとbindgen を参照。
第1チャンク:41 E4 B8 完全なA + 「中」の最初の2バイト 第2チャンク:AD 42 「中」を補完 + 完全なB 結合バイト:41 E4 B8 AD 42 テキスト結果 A中B UTF-8エンコーディングの境界は、読み取りチャンクの境界と一致するとは限らな い error_len = None は、末尾が未完成であることを示す可能性があります。ストリーム終了後も未完成の場合は、切り捨て エラーとして処理する必要があります。
未完了のバイトと確定した不正なエンコーディングを区別する
fn main ( ) {
let mut bytes = vec! [ b ' A' , 0xe4 , 0xb8 ] ;
let error = std:: str:: from_utf8( & bytes) .unwrap_err ( ) ;
assert_eq! ( error.valid_up_to ( ) , 1 ) ;
assert_eq! ( error.error_len ( ) , None ) ;
bytes.extend ( [ 0xad , b ' B' ] ) ;
assert_eq! ( std:: str:: from_utf8( & bytes) , Ok ( " A中B" ) ) ;
let bad = vec! [ b ' A' , 0xff , b ' B' ] ;
let error = String :: from_utf8( bad) .unwrap_err ( ) ;
assert_eq! ( error.utf8_error ( ) .valid_up_to ( ) , 1 ) ;
assert_eq! ( error.utf8_error ( ) .error_len ( ) , Some ( 1 ) ) ;
assert_eq! ( error.into_bytes ( ) , [ b ' A' , 0xff , b ' B' ] ) ;
}
第1チャンクを読み取ったとき、末尾のE4 B8は単に「中」がチャンクを跨いでいるだけかもしれないため、すぐに破棄したり置き換えたりすることはできません。プロトコルがUTF-8ストリームを規定している場合、確認済みのプレフィックスを出力し、未完成の末尾を保持し、次のチャンクで継続してチェックできます。メッセージやストリームが終了している場合は、切り捨てを報告するか、明示的な置き換え戦略を実行する必要があります。読み取りチャンクごとに個別にfrom_utf8_lossyを行うと、本来有効なチャンクを跨ぐ文字が置き換え文字になってしまいます。Utf8Error
この例では、境界を示すためにすべてのバイトをVecに保存しています。実際のストリーミング実装では、累積バッファサイズを制限し、確認済みの長いプレフィックスを毎回先頭から再検証しないようにする必要があります。
OsStrは特定の永続化可能な内部エンコーディングを保証しない
Unixのファイル名コンポーネントにはUTF-8以外のバイトを含めることができますが、NULを含めることはできず、スラッシュはパスの区切り文字です。Windowsのシステムワイド文字インターフェースは16ビットエンコーディングユニットを使用しており、有効なUnicodeスカラーシーケンスとして扱えない内容が含まれる可能性があります。Windowsファイルシステムのネイティブフォーマットを単にWTF-8と呼ぶことはできません。
RustのWindows内部表現はWTF-8と実装上の関連がありますが、クロスプラットフォームなOsStr抽象化は、アプリケーションが特定の内部エンコーディングを永続化プロトコルとして依存することを許可しません。UnixではOsStrExt::as_bytesなどのプラットフォームインターフェースを使用して情報を失わずにアクセスでき、Windowsではencode_wideを使用してワイド文字ユニットを取得できます。OsStr 、Windows OsStrExt
# [ cfg ( unix ) ]
fn main ( ) {
use std:: ffi:: OsString;
use std:: os:: unix:: ffi:: OsStringExt;
use std:: path:: PathBuf;
let path = PathBuf:: from( OsString:: from_vec( vec! [ b ' f' , 0xff ] ) ) ;
assert! ( path.to_str ( ) .is_none ( ) ) ;
assert_eq! ( path.into_os_string ( ) .into_vec ( ) , [ b ' f' , 0xff ] ) ;
}
# [ cfg ( not ( unix ) ) ]
fn main ( ) { }
Path::displayとto_string_lossyは人間が読むのに適していますが、表示結果を元のパスのアイデンティティとして再使用すべきではありません。ファイル操作では、可能な限り&Path/PathBufを渡すようにし、UTF-8への変換往復を避けてください。
Path操作はファイルシステムへのアクセスや隔離を自動的に行わない
join、parent、extension、componentsなどの主要な操作は、主にプラットフォームのパス構文に従って処理されます。joinの右側が絶対パスの場合、前の基本パスを置き換えます。Windowsでは、プレフィックスとルートパスにプラットフォーム固有のルールが存在します。Path
use std:: path:: Path;
fn main ( ) {
let path = Path:: new( " reports" ) .join ( " 2026" ) .join ( " summary.txt" ) ;
assert_eq! ( path.file_name ( ) .unwrap ( ) , " summary.txt" ) ;
assert_eq! ( path.extension ( ) .unwrap ( ) , " txt" ) ;
}
componentsは、シンボリックリンクが意味を変更する可能性があるため、a/../bを任意に折りたたみません。canonicalizeはファイルシステムにアクセスして対応するパスを解決しますが、その結果が、その後のアクセス時にディレクトリやリンクが変更されていないことを証明するものではありません。
したがって、PathBuf::joinはパス連結を正しく表現するツールですが、「ユーザー入力が常に特定のディレクトリ内に留まることを保証する」安全な境界ではありません。タスクでアクセスルートディレクトリを制限する必要がある場合は、対象システムに応じて適切なディレクトリハンドルと解析制約を使用する必要があり、単なる文字列のプレフィックスチェックだけでは不十分です。
パスプレフィックスはコンポーネントで比較されるが、ファイルシステムの包含関係を意味しない
use std:: path:: { Component, Path} ;
fn normal_relative ( path : & Path) -> bool {
! path.as_os_str ( ) .is_empty ( )
& & path.components ( ) .all ( | c | matches! ( c, Component:: Normal( _ ) ) )
}
fn main ( ) {
assert! ( normal_relative ( Path:: new( " reports/summary.txt" ) ) ) ;
assert! ( ! normal_relative ( Path:: new( " ../outside" ) ) ) ;
assert! ( ! normal_relative ( Path:: new( " " ) ) ) ;
assert! ( ! Path:: new( " reports-old/a" ) .starts_with ( " reports" ) ) ;
assert! ( Path:: new( " reports/../outside" ) .starts_with ( " reports" ) ) ;
assert! ( ! normal_relative ( Path:: new( " reports/../outside" ) ) ) ;
}
この関数は、非空であり、解析されたコンポーネントがすべてNormalであるという、1つの構文入力戦略を表しています。componentsは限定的な構文正規化を行いますが、重複する区切り文字などの元のスペル情報は保持されない場合があります。異なるプラットフォームでは、それぞれ独自の区切り文字とプレフィックスルールを使用します。これはパスの存在をチェックするものではなく、reports内のシンボリックリンクが外部を指すことを防ぐこともできません。
Path::starts_withは文字列のプレフィックスよりもコンポーネントセマンティクスに近いので、reports-oldはreportsのサブパスにはなりません。ただし、..を含むパスは、このコンポーネントプレフィックス判定を通過する可能性があります。..を拒否した場合でも、シンボリックリンクと並行したディレクトリの変更は、実際のオープン段階で処理する必要があり、上記のnormal_relativeを完全なファイルアクセス隔離ソリューションとして扱うことはできません。Pathコンポーネントとプレフィックス
表示、保存、操作インターフェースを分離する
用途 適切な表現 変換時に保持されるもの
テキストプロトコルフィールド &str / String エンコーディングエラー、長さ単位、正規化戦略
不明なエンコーディング入力 &[u8] / Vec 生バイト、フォーマットを確認してからデコード
現在のプラットフォームのファイル操作 &Path / PathBuf 元のOsStr内容とプラットフォームのコンポーネントセマンティクス
ログ内のファイル名 displayまたは明示的なエスケープ表現 表示には損失がある可能性があり、元のファイルの特定には使用しない
クロスプラットフォームでのパス識別子の保存 明確に設計されたフォーマット プラットフォーム、ルート/プレフィックスルール、および表現できない内容の処理
ファイルAPIがパスを受け取る際、呼び出し手にAsRef<Path>または&Pathを渡すことを優先し、内部で直接パス操作を行います。強制的にStringを受け取ると、一部の有効なシステムパスが入口で除外されてしまいます。逆に、ネットワークプロトコルのリソース名がパスのように見えても、プロトコルの規定に従って解釈すべきであり、現在のオペレーティングシステムのPathルールをそのまま適用してはいけません。