Decode BigEndian Packet Headers Safely
Decode fixed-width BigEndian packet headers and length-prefixed payloads with encoding/binary, rejecting truncated frames or magic mismatches.
Keep data trustworthy across boundaries with schema checks and error-preserving transforms.
2,360 published examples — showing latest 48
Decode fixed-width BigEndian packet headers and length-prefixed payloads with encoding/binary, rejecting truncated frames or magic mismatches.
Inspect leading bytes with bufio.Reader.Peek without advancing the cursor, then split records via ReadBytes while handling a trailing io.EOF.
Configure csv.Reader with a pipe Comma, hash Comment, and TrimLeadingSpace, then normalize whitespace and re-export the rows as TSV.
Parse RFC 5322 headers, sender and recipient lists, timestamps, and message body streams from an in-memory reader using net/mail.ReadMessage.
Assert ascending monotonicity with sort.SliceIsSorted, then use sort.Search to match usage metrics against threshold tiers and handle overflows.
Parse MIME headers with net/textproto ReadMIMEHeader and decode dot-stuffed text blocks via DotReader, stopping cleanly at the terminator line.
Scan raw strings via utf8.DecodeRuneInString so invalid byte runs (RuneError with width 1) are separated from genuine U+FFFD runes (width 3).
Compute and verify rolling Adler32 checksums in-flight with CheckedOutputStream and CheckedInputStream, catching single-bit stream tampering.
Normalize trailing zeros with BigDecimal.stripTrailingZeros and print plain numbers via toPlainString so powers of ten never show 1E+2.
Toggle half-open slot ranges in BitSet with set(from, to), flip(from, to), and clear(from, to), then test schedule overlap via intersects.
Flip a ByteBuffer after writing and carve independent sub-views with slice() and slice(index, length) that share bytes without moving parent positions.
Query live sorted subSet ranges and atomic pollFirst entries on ConcurrentSkipListSet while concurrent mutations iterate safely without locks.
Switch regex patterns mid-scan with Matcher.usePattern and enable useTransparentBounds so lookaheads inspect characters past regionEnd.
Compare arbitrary Object references holding primitive arrays, nested Object[] graphs, and nulls safely using Objects.deepEquals instead of ==.
Split text with JDK 21 String.splitWithDelimiters so matched separators stay in odd array slots, comparing positive, zero, and negative limit rules.
Read and write multi-byte integers in a byte[] buffer using byteArrayViewVarHandle with explicit ByteOrder and aligned atomic CAS checks.
Replace a single element immutably with Array.prototype.with, supporting negative indices from the end while throwing RangeError on out-of-bounds updates.
Store signed 64-bit integers beyond MAX_SAFE_INTEGER in BigInt64Array without float rounding loss, and inspect raw bytes with DataView.getBigInt64.
Tokenize Latin and CJK text into linguistic words with Intl.Segmenter word granularity and filter out spaces and punctuation using the isWordLike flag.
Wrap iterables with Iterator.from and terminate lazy pipelines via drop, find, some, every, and reduce so infinite or large streams stop on first match.
Take roots with Math.sqrt and Math.cbrt: sqrt returns NaN for negatives, cbrt keeps the sign, and neither matches the precision promises of exact math.
Decode multi-byte UTF-8 payloads split mid-character across Node chunks with StringDecoder.write and flush incomplete tails via StringDecoder.end.
Clone getters, setters, symbol keys, and non-enumerable flags faithfully with Object.getOwnPropertyDescriptors and Object.defineProperties instead of spread.
Contrast Uint8ClampedArray saturating clamping to 0..255 with round-half-to-even against Uint8Array modulo-256 wraparound for pixel and signal channels.
Format binary digests with delimiter support via binascii.hexlify and pack bytes compactly with base64.b85encode compared against Base64 overhead.
Handle CSV rows with extra or missing trailing columns cleanly using csv.DictReader restkey and restval before normalizing via DictWriter.
Declare initialization-only parameters with dataclasses.InitVar so __post_init__ can derive or normalize state without leaking extra fields to asdict.
Contrast heapq.heappushpop and heapq.heapreplace in fixed-size top-k buffers: heappushpop keeps out smaller items, while heapreplace always pops first.
Mutate an in-memory BytesIO stream through getbuffer() without copying bytes, and release the memoryview cleanly before resizing or closing.
Resolve ambiguous fall-back clock times with datetime fold=0 and fold=1 under ZoneInfo, and detect nonexistent spring-forward gaps via UTC round-trips.
Turn BinaryHeap into a min-heap with std::cmp::Reverse to perform a deterministic k-way merge across multiple sorted integer slices.
Query ordered timestamp keys in BTreeMap using half-open ranges, inclusive aggregates, and Bound::Excluded for strict cursor resumption.
Stream byte records via BufReader::read_until into a single cleared Vec<u8> buffer, validating UTF-8 and checking capacity without per-line allocations.
Chain checked_mul and checked_add to catch integer overflow when summing invoice lines, while using saturating_add to clamp cumulative telemetry caps.
Split byte buffers into fixed 4-byte blocks with chunks_exact and inspect its trailing remainder, then scan adjacent steps via windows(2).
Return Cow::Borrowed when a header string needs no control-character cleanup, allocating a Cow::Owned String only on inputs that actually change.
Pair borrowed &str lookups via get_mut with entry().or_insert_with_key() on HashMap<String, V> so keys and defaults allocate only on cache misses.
Write length-prefixed binary records into an in-memory io::Cursor while capturing byte offsets via stream_position, then seek back and decode one.
Accumulate running account balances across transaction deltas with Iterator::scan and terminate iteration immediately when a balance goes negative.
Extract owned vectors from a mutable enum variant using std::mem::replace and drain buffers via std::mem::take without cloning.
Adapt a single &T or &mut T into &[T] or &mut [T] with std::slice::from_ref and from_mut so slice-oriented helpers accept one item with zero copies.
Pair two slice::partition_point binary lookups for lower and upper bounds to extract an O(log n) contiguous range slice from sorted structs.
Maintain a bounded sliding average by popping from the front and pushing to the back of VecDeque, then cycle elements with rotate_left.
Partition rows into multiple arrays in one GROUP BY via ARRAY_AGG FILTER (WHERE ...), wrapping outputs with COALESCE so empty matches stay {}.
Define a custom PostgreSQL aggregate using CREATE AGGREGATE with a state type, SFUNC, INITCOND, and FINALFUNC that works in GROUP BY and OVER frames.
Detect loops on multi-column graph keys with the PostgreSQL CYCLE clause, writing custom string flags and tracking hop counts via the path array.
Step timestamptz across spring-forward and fall-back DST boundaries in an explicit target zone using PostgreSQL 16 date_add and date_subtract.
Declare a GiST EXCLUDE constraint DEFERRABLE INITIALLY IMMEDIATE so a transaction can defer checks and shift overlapping schedule slots safely.
Showing 48 of 2,360 verified Data Integrity examples. Filter the full catalog by language, framework, or keyword in Explore.
Browse & filter all 2,360 examples in Explore →