Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(428)

Side by Side Diff: service/datastore/properties.go

Issue 1550903002: impl/memory: Fix time serialization encoding. (Closed) Base URL: https://github.com/luci/gae@master
Patch Set: Store PTTime as time.Time internally, ForIndex -> GetIndexTypeAndValue. Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « service/datastore/pls_impl.go ('k') | service/datastore/properties_test.go » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 package datastore 5 package datastore
6 6
7 import ( 7 import (
8 "bytes"
8 "encoding/base64" 9 "encoding/base64"
9 "errors" 10 "errors"
10 "fmt" 11 "fmt"
11 "math" 12 "math"
12 "reflect" 13 "reflect"
13 "time" 14 "time"
14 15
15 "github.com/luci/gae/service/blobstore" 16 "github.com/luci/gae/service/blobstore"
16 ) 17 )
17 18
(...skipping 149 matching lines...) Expand 10 before | Expand all | Expand 10 after
167 "PTUnknown (and therefore PropertyType) exceeds 0x7e. Th is conflicts " + 168 "PTUnknown (and therefore PropertyType) exceeds 0x7e. Th is conflicts " +
168 "with serialize.WriteProperty's use of the high bit to indicate " + 169 "with serialize.WriteProperty's use of the high bit to indicate " +
169 "NoIndex and/or \"impl/memory\".increment's abil ity to guarantee " + 170 "NoIndex and/or \"impl/memory\".increment's abil ity to guarantee " +
170 "incrementability.") 171 "incrementability.")
171 } 172 }
172 } 173 }
173 174
174 // Property is a value plus an indicator of whether the value should be 175 // Property is a value plus an indicator of whether the value should be
175 // indexed. Name and Multiple are stored in the PropertyMap object. 176 // indexed. Name and Multiple are stored in the PropertyMap object.
176 type Property struct { 177 type Property struct {
177 » value interface{} 178 » // value is the Property's value. It is stored in an internal, opaque ty pe and
179 » // should not be directly exported to consumers. Rather, it can be acces sed
180 » // in its original original value via Value().
iannucci 2016/01/05 02:02:57 too original?
dnj 2016/01/05 02:46:17 Everything is in bits.
181 » //
182 » // Specifically:
183 » //» - []byte- and string-based values are stored in a bytesByteSeque nce and
184 » //» stringByteSequence respectively.
185 » value interface{}
186
178 indexSetting IndexSetting 187 indexSetting IndexSetting
179 propType PropertyType 188 propType PropertyType
180 } 189 }
181 190
182 // MkProperty makes a new indexed* Property and returns it. If val is an 191 // MkProperty makes a new indexed* Property and returns it. If val is an
183 // invalid value, this panics (so don't do it). If you want to handle the error 192 // invalid value, this panics (so don't do it). If you want to handle the error
184 // normally, use SetValue(..., ShouldIndex) instead. 193 // normally, use SetValue(..., ShouldIndex) instead.
185 // 194 //
186 // *indexed if val is not an unindexable type like []byte. 195 // *indexed if val is not an unindexable type like []byte.
187 func MkProperty(val interface{}) Property { 196 func MkProperty(val interface{}) Property {
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
238 err := error(nil) 247 err := error(nil)
239 if checkValid && !x.Valid() { 248 if checkValid && !x.Valid() {
240 err = errors.New("invalid GeoPoint value") 249 err = errors.New("invalid GeoPoint value")
241 } 250 }
242 return PTGeoPoint, err 251 return PTGeoPoint, err
243 default: 252 default:
244 return PTUnknown, fmt.Errorf("gae: Property has bad type %T", v) 253 return PTUnknown, fmt.Errorf("gae: Property has bad type %T", v)
245 } 254 }
246 } 255 }
247 256
257 // RoundTime rounds a time.Time to microseconds, which is the (undocumented)
258 // way that the AppEngine SDK stores it.
259 func RoundTime(t time.Time) time.Time {
260 return t.Round(time.Microsecond)
261 }
262
263 // TimeToInt converts a time value to a datastore-appropraite integer value.
264 //
265 // This method truncates the time to microseconds and drops the timezone,
266 // because that's the (undocumented) way that the appengine SDK does it.
267 func TimeToInt(t time.Time) int64 {
268 if t.IsZero() {
269 return 0
270 }
271
272 t = RoundTime(t)
273 return t.Unix()*1e6 + int64(t.Nanosecond()/1e3)
274 }
275
276 // IntToTime converts a datastore time integer into its time.Time value.
277 func IntToTime(v int64) time.Time {
278 if v == 0 {
279 return time.Time{}
280 }
281 return RoundTime(time.Unix(int64(v/1e6), int64((v%1e6)*1e3))).UTC()
282 }
283
248 // timeLocationIsUTC tests if two time.Location are equal. 284 // timeLocationIsUTC tests if two time.Location are equal.
249 // 285 //
250 // This is tricky using the standard time API, as time is implicitly normalized 286 // This is tricky using the standard time API, as time is implicitly normalized
251 // to UTC and all equality checks are performed relative to that normalized 287 // to UTC and all equality checks are performed relative to that normalized
252 // time. To compensate, we instantiate two new time.Time using the respective 288 // time. To compensate, we instantiate two new time.Time using the respective
253 // Locations. 289 // Locations.
254 func timeLocationIsUTC(l *time.Location) bool { 290 func timeLocationIsUTC(l *time.Location) bool {
255 return time.Date(1970, 1, 1, 0, 0, 0, 0, l).Equal(utcTestTime) 291 return time.Date(1970, 1, 1, 0, 0, 0, 0, l).Equal(utcTestTime)
256 } 292 }
257 293
(...skipping 17 matching lines...) Expand all
275 o = v.String() 311 o = v.String()
276 } 312 }
277 case reflect.Float32, reflect.Float64: 313 case reflect.Float32, reflect.Float64:
278 o = v.Float() 314 o = v.Float()
279 case reflect.Slice: 315 case reflect.Slice:
280 if t.Elem().Kind() == reflect.Uint8 { 316 if t.Elem().Kind() == reflect.Uint8 {
281 o = v.Bytes() 317 o = v.Bytes()
282 } 318 }
283 case reflect.Struct: 319 case reflect.Struct:
284 if t == typeOfTime { 320 if t == typeOfTime {
285 // time in a Property can only hold microseconds
286 tim := v.Interface().(time.Time) 321 tim := v.Interface().(time.Time)
287 if !tim.IsZero() { 322 if !tim.IsZero() {
288 » » » » o = v.Interface().(time.Time).Round(time.Microse cond) 323 » » » » o = RoundTime(v.Interface().(time.Time))
289 } 324 }
290 } 325 }
291 } 326 }
292 return o 327 return o
293 } 328 }
294 329
295 // Value returns the current value held by this property. It's guaranteed to 330 // Value returns the current value held by this property. It's guaranteed to
296 // be a valid value type (i.e. `p.SetValue(p.Value(), true)` will never return 331 // be a valid value type (i.e. `p.SetValue(p.Value(), true)` will never return
297 // an error). 332 // an error).
298 func (p *Property) Value() interface{} { return p.value } 333 func (p *Property) Value() (v interface{}) {
334 » v = p.value
335
336 » switch p.propType {
337 » case PTBytes:
338 » » v = v.(byteSequence).Bytes()
339 » case PTString:
340 » » v = v.(byteSequence).String()
341 » case PTBlobKey:
342 » » v = blobstore.Key(v.(byteSequence).String())
343 » }
iannucci 2016/01/05 02:02:57 y no default?
dnj 2016/01/05 02:46:17 Done.
344
345 » return
346 }
299 347
300 // IndexSetting says whether or not the datastore should create indicies for 348 // IndexSetting says whether or not the datastore should create indicies for
301 // this value. 349 // this value.
302 func (p *Property) IndexSetting() IndexSetting { return p.indexSetting } 350 func (p *Property) IndexSetting() IndexSetting { return p.indexSetting }
303 351
304 // Type is the PT* type of the data contained in Value(). 352 // Type is the PT* type of the data contained in Value().
305 func (p *Property) Type() PropertyType { return p.propType } 353 func (p *Property) Type() PropertyType { return p.propType }
306 354
307 // SetValue sets the Value field of a Property, and ensures that its value 355 // SetValue sets the Value field of a Property, and ensures that its value
308 // conforms to the permissible types. That way, you're guaranteed that if you 356 // conforms to the permissible types. That way, you're guaranteed that if you
(...skipping 26 matching lines...) Expand all
335 // a nil-valued property into a struct will set that field to the zero 383 // a nil-valued property into a struct will set that field to the zero
336 // value. 384 // value.
337 func (p *Property) SetValue(value interface{}, is IndexSetting) (err error) { 385 func (p *Property) SetValue(value interface{}, is IndexSetting) (err error) {
338 pt := PTNull 386 pt := PTNull
339 if value != nil { 387 if value != nil {
340 value = UpconvertUnderlyingType(value) 388 value = UpconvertUnderlyingType(value)
341 if pt, err = PropertyTypeOf(value, true); err != nil { 389 if pt, err = PropertyTypeOf(value, true); err != nil {
342 return 390 return
343 } 391 }
344 } 392 }
393
394 // Convert value to underlying datastore type.
395 switch t := value.(type) {
396 case string:
397 value = stringByteSequence(t)
398 case blobstore.Key:
399 value = stringByteSequence(t)
400 case []byte:
401 value = bytesByteSequence(t)
402 case time.Time:
403 value = RoundTime(t)
404 }
405
345 p.propType = pt 406 p.propType = pt
346 p.value = value 407 p.value = value
347 p.indexSetting = is 408 p.indexSetting = is
348 return 409 return
349 } 410 }
350 411
351 // ForIndex gets a new Property with its value and type converted as if it were 412 // IndexTypeAndValue returns the type and value of the Property as it would
352 // being stored in a datastore index. See the doc on PropertyType for more info. 413 // show up in a datastore index.
353 func (p Property) ForIndex() Property { 414 //
354 » switch p.propType { 415 // This is used to operate on the Property as it would be stored in a datastore
355 » case PTNull, PTInt, PTBool, PTString, PTFloat, PTGeoPoint, PTKey: 416 // index, specifically for serialization and comparison.
356 » » return p 417 //
418 // The returned type will be the PropertyType used in the index. The returned
419 // value will be one of:
420 // - bool
421 // - int64
422 // - float64
423 // - string
424 // - []byte
425 // - GeoPoint
426 // - *Key
427 func (p Property) IndexTypeAndValue() (PropertyType, interface{}) {
428 » switch t := p.propType; t {
429 » case PTNull, PTInt, PTBool, PTFloat, PTGeoPoint, PTKey:
430 » » return t, p.Value()
357 431
358 case PTTime: 432 case PTTime:
359 » » v, _ := p.Project(PTInt) 433 » » return PTInt, TimeToInt(p.value.(time.Time))
360 » » return Property{v, p.indexSetting, PTInt}
361 434
362 » case PTBytes, PTBlobKey: 435 » case PTString, PTBytes, PTBlobKey:
363 » » v, _ := p.Project(PTString) 436 » » return PTString, p.value.(byteSequence).Value()
364 » » return Property{v, p.indexSetting, PTString} 437
438 » default:
439 » » panic(fmt.Errorf("unknown PropertyType: %s", t))
365 } 440 }
366 panic(fmt.Errorf("unknown PropertyType: %s", p.propType))
367 } 441 }
368 442
369 // Project can be used to project a Property retrieved from a Projection query 443 // Project can be used to project a Property retrieved from a Projection query
370 // into a different datatype. For example, if you have a PTInt property, you 444 // into a different datatype. For example, if you have a PTInt property, you
371 // could Project(PTTime) to convert it to a time.Time. The following conversions 445 // could Project(PTTime) to convert it to a time.Time. The following conversions
372 // are supported: 446 // are supported:
447 // PTString <-> PTBlobKey
448 // PTString <-> PTBytes
373 // PTXXX <-> PTXXX (i.e. identity) 449 // PTXXX <-> PTXXX (i.e. identity)
374 // PTInt <-> PTTime 450 // PTInt <-> PTTime
375 // PTString <-> PTBlobKey
376 // PTString <-> PTBytes
377 // PTNull <-> Anything 451 // PTNull <-> Anything
378 func (p *Property) Project(to PropertyType) (interface{}, error) { 452 func (p *Property) Project(to PropertyType) (interface{}, error) {
379 » switch { 453 » if to == PTNull {
380 » case to == p.propType: 454 » » return nil, nil
381 » » return p.value, nil 455 » }
382 456
383 » case to == PTInt && p.propType == PTTime: 457 » pt, v := p.propType, p.value
384 » » t := p.value.(time.Time) 458 » switch pt {
385 » » v := uint64(t.Unix())*1e6 + uint64(t.Nanosecond()/1e3) 459 » case PTBytes, PTString, PTBlobKey:
386 » » return int64(v), nil 460 » » v := v.(byteSequence)
461 » » switch to {
462 » » case PTBytes:
463 » » » return v.Bytes(), nil
464 » » case PTString:
465 » » » return v.String(), nil
466 » » case PTBlobKey:
467 » » » return blobstore.Key(v.String()), nil
468 » » }
387 469
388 » case to == PTTime && p.propType == PTInt: 470 » case PTTime:
389 » » v := p.value.(int64) 471 » » switch to {
390 » » t := time.Unix(int64(v/1e6), int64((v%1e6)*1e3)) 472 » » case PTInt:
391 » » if t.IsZero() { 473 » » » return TimeToInt(v.(time.Time)), nil
392 » » » return time.Time{}, nil 474 » » case PTTime:
475 » » » return v, nil
393 } 476 }
394 return t.UTC(), nil
395 477
396 » case to == PTString && p.propType == PTBytes: 478 » case PTInt:
397 » » return string(p.value.([]byte)), nil 479 » » switch to {
480 » » case PTInt:
481 » » » return v, nil
482 » » case PTTime:
483 » » » return IntToTime(v.(int64)), nil
484 » » }
398 485
399 » case to == PTString && p.propType == PTBlobKey: 486 » case to:
400 » » return string(p.value.(blobstore.Key)), nil 487 » » return v, nil
401 488
402 » case to == PTBytes && p.propType == PTString: 489 » case PTNull:
403 » » return []byte(p.value.(string)), nil
404
405 » case to == PTBlobKey && p.propType == PTString:
406 » » return blobstore.Key(p.value.(string)), nil
407
408 » case to == PTNull:
409 » » return nil, nil
410
411 » case p.propType == PTNull:
412 switch to { 490 switch to {
413 case PTInt: 491 case PTInt:
414 return int64(0), nil 492 return int64(0), nil
415 case PTTime: 493 case PTTime:
416 return time.Time{}, nil 494 return time.Time{}, nil
417 case PTBool: 495 case PTBool:
418 return false, nil 496 return false, nil
419 case PTBytes: 497 case PTBytes:
420 return []byte(nil), nil 498 return []byte(nil), nil
421 case PTString: 499 case PTString:
422 return "", nil 500 return "", nil
423 case PTFloat: 501 case PTFloat:
424 return float64(0), nil 502 return float64(0), nil
425 case PTGeoPoint: 503 case PTGeoPoint:
426 return GeoPoint{}, nil 504 return GeoPoint{}, nil
427 case PTKey: 505 case PTKey:
428 return nil, nil 506 return nil, nil
429 case PTBlobKey: 507 case PTBlobKey:
430 return blobstore.Key(""), nil 508 return blobstore.Key(""), nil
431 } 509 }
432 fallthrough
433 default:
434 return nil, fmt.Errorf("unable to project %s to %s", p.propType, to)
435 } 510 }
511 return nil, fmt.Errorf("unable to project %s to %s", pt, to)
436 } 512 }
437 513
438 func cmpVals(a, b interface{}, t PropertyType) int { 514 func cmpFloat(a, b float64) int {
439 » cmpFloat := func(a, b float64) int { 515 » if a == b {
440 » » if a == b { 516 » » return 0
441 » » » return 0 517 » }
442 » » } 518 » if a > b {
443 » » if a > b { 519 » » return 1
444 » » » return 1 520 » }
445 » » } 521 » return -1
522 }
523
524 // Less returns true iff p would sort before other.
525 //
526 // This uses datastore's index rules for sorting (e.g.
527 // []byte("hello") == "hello")
528 func (p *Property) Less(other *Property) bool {
529 » return p.Compare(other) < 0
530 }
531
532 // Equal returns true iff p and other have identical index representations.
533 //
534 // This uses datastore's index rules for sorting (e.g.
535 // []byte("hello") == "hello")
536 func (p *Property) Equal(other *Property) bool {
537 » return p.Compare(other) == 0
538 }
539
540 // Compare compares this Property to another, returning a trinary value
541 // indicating where it would sort relative to the other in datastore.
542 //
543 // It returns:
544 //» <0 if the Property would sort before `other`.
545 //» >0 if the Property would after before `other`.
546 //» 0 if the Property equals `other`.
547 func (p *Property) Compare(other *Property) int {
548 » if p.indexSetting && !other.indexSetting {
549 » » return 1
550 » } else if !p.indexSetting && other.indexSetting {
446 return -1 551 return -1
447 } 552 }
448 553
449 » switch t { 554 » at, av := p.IndexTypeAndValue()
555 » bt, bv := other.IndexTypeAndValue()
556 » if cmp := int(at) - int(bt); cmp != 0 {
557 » » return cmp
558 » }
559
560 » switch t := at; t {
450 case PTNull: 561 case PTNull:
451 return 0 562 return 0
452 563
453 case PTBool: 564 case PTBool:
454 » » a, b := a.(bool), b.(bool) 565 » » a, b := av.(bool), bv.(bool)
455 if a == b { 566 if a == b {
456 return 0 567 return 0
457 } 568 }
458 if a && !b { 569 if a && !b {
459 return 1 570 return 1
460 } 571 }
461 return -1 572 return -1
462 573
463 case PTInt: 574 case PTInt:
464 » » a, b := a.(int64), b.(int64) 575 » » a, b := av.(int64), bv.(int64)
465 if a == b { 576 if a == b {
466 return 0 577 return 0
467 } 578 }
468 if a > b { 579 if a > b {
469 return 1 580 return 1
470 } 581 }
471 return -1 582 return -1
472 583
473 case PTString: 584 case PTString:
474 » » a, b := a.(string), b.(string) 585 » » return cmpByteSequence(p.value.(byteSequence), other.value.(byte Sequence))
475 » » if a == b {
476 » » » return 0
477 » » }
478 » » if a > b {
479 » » » return 1
480 » » }
481 » » return -1
482 586
483 case PTFloat: 587 case PTFloat:
484 » » return cmpFloat(a.(float64), b.(float64)) 588 » » return cmpFloat(av.(float64), bv.(float64))
485 589
486 case PTGeoPoint: 590 case PTGeoPoint:
487 » » a, b := a.(GeoPoint), b.(GeoPoint) 591 » » a, b := av.(GeoPoint), bv.(GeoPoint)
488 cmp := cmpFloat(a.Lat, b.Lat) 592 cmp := cmpFloat(a.Lat, b.Lat)
489 if cmp != 0 { 593 if cmp != 0 {
490 return cmp 594 return cmp
491 } 595 }
492 return cmpFloat(a.Lng, b.Lng) 596 return cmpFloat(a.Lng, b.Lng)
493 597
494 case PTKey: 598 case PTKey:
495 » » a, b := a.(*Key), b.(*Key) 599 » » a, b := av.(*Key), bv.(*Key)
496 if a.Equal(b) { 600 if a.Equal(b) {
497 return 0 601 return 0
498 } 602 }
499 if b.Less(a) { 603 if b.Less(a) {
500 return 1 604 return 1
501 } 605 }
502 return -1 606 return -1
503 607
504 default: 608 default:
505 panic(fmt.Errorf("uncomparable type: %s", t)) 609 panic(fmt.Errorf("uncomparable type: %s", t))
506 } 610 }
507 } 611 }
508 612
509 // Less returns true iff p would sort before other.
510 //
511 // This uses datastore's index rules for sorting (e.g.
512 // []byte("hello") == "hello")
513 func (p *Property) Less(other *Property) bool {
514 if p.indexSetting && !other.indexSetting {
515 return true
516 } else if !p.indexSetting && other.indexSetting {
517 return false
518 }
519 a, b := p.ForIndex(), other.ForIndex()
520 cmp := int(a.propType) - int(b.propType)
521 if cmp < 0 {
522 return true
523 } else if cmp > 0 {
524 return false
525 }
526 return cmpVals(a.value, b.value, a.propType) < 0
527 }
528
529 // Equal returns true iff p and other have identical index representations.
530 //
531 // This uses datastore's index rules for sorting (e.g.
532 // []byte("hello") == "hello")
533 func (p *Property) Equal(other *Property) bool {
534 ret := p.indexSetting == other.indexSetting
535 if ret {
536 a, b := p.ForIndex(), other.ForIndex()
537 ret = a.propType == b.propType && cmpVals(a.value, b.value, a.pr opType) == 0
538 }
539 return ret
540 }
541
542 // GQL returns a correctly formatted Cloud Datastore GQL literal which 613 // GQL returns a correctly formatted Cloud Datastore GQL literal which
543 // is valid for a comparison value in the `WHERE` clause. 614 // is valid for a comparison value in the `WHERE` clause.
544 // 615 //
545 // The flavor of GQL that this emits is defined here: 616 // The flavor of GQL that this emits is defined here:
546 // https://cloud.google.com/datastore/docs/apis/gql/gql_reference 617 // https://cloud.google.com/datastore/docs/apis/gql/gql_reference
547 // 618 //
548 // NOTE: GeoPoint values are emitted with speculated future syntax. There is 619 // NOTE: GeoPoint values are emitted with speculated future syntax. There is
549 // currently no syntax for literal GeoPoint values. 620 // currently no syntax for literal GeoPoint values.
550 func (p *Property) GQL() string { 621 func (p *Property) GQL() string {
622 v := p.Value()
551 switch p.propType { 623 switch p.propType {
552 case PTNull: 624 case PTNull:
553 return "NULL" 625 return "NULL"
554 626
555 case PTInt, PTFloat, PTBool: 627 case PTInt, PTFloat, PTBool:
556 » » return fmt.Sprint(p.value) 628 » » return fmt.Sprint(v)
557 629
558 case PTString: 630 case PTString:
559 » » return gqlQuoteString(p.value.(string)) 631 » » return gqlQuoteString(v.(string))
560 632
561 case PTBytes: 633 case PTBytes:
562 return fmt.Sprintf("BLOB(%q)", 634 return fmt.Sprintf("BLOB(%q)",
563 » » » base64.URLEncoding.EncodeToString(p.value.([]byte))) 635 » » » base64.URLEncoding.EncodeToString(v.([]byte)))
564 636
565 case PTBlobKey: 637 case PTBlobKey:
566 return fmt.Sprintf("BLOBKEY(%s)", gqlQuoteString( 638 return fmt.Sprintf("BLOBKEY(%s)", gqlQuoteString(
567 » » » string(p.value.(blobstore.Key)))) 639 » » » string(v.(blobstore.Key))))
568 640
569 case PTKey: 641 case PTKey:
570 » » return p.value.(*Key).GQL() 642 » » return v.(*Key).GQL()
571 643
572 case PTTime: 644 case PTTime:
573 » » return fmt.Sprintf("DATETIME(%s)", p.value.(time.Time).Format(ti me.RFC3339Nano)) 645 » » return fmt.Sprintf("DATETIME(%s)", v.(time.Time).Format(time.RFC 3339Nano))
574 646
575 case PTGeoPoint: 647 case PTGeoPoint:
576 // note that cloud SQL doesn't support this yet, but take a good guess at 648 // note that cloud SQL doesn't support this yet, but take a good guess at
577 // it. 649 // it.
578 » » v := p.value.(GeoPoint) 650 » » v := v.(GeoPoint)
579 return fmt.Sprintf("GEOPOINT(%v, %v)", v.Lat, v.Lng) 651 return fmt.Sprintf("GEOPOINT(%v, %v)", v.Lat, v.Lng)
580 } 652 }
581 panic(fmt.Errorf("bad type: %s", p.propType)) 653 panic(fmt.Errorf("bad type: %s", p.propType))
582 } 654 }
583 655
584 // PropertySlice is a slice of Properties. It implements sort.Interface. 656 // PropertySlice is a slice of Properties. It implements sort.Interface.
585 type PropertySlice []Property 657 type PropertySlice []Property
586 658
587 func (s PropertySlice) Len() int { return len(s) } 659 func (s PropertySlice) Len() int { return len(s) }
588 func (s PropertySlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 660 func (s PropertySlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
589 func (s PropertySlice) Less(i, j int) bool { return s[i].Less(&s[j]) } 661 func (s PropertySlice) Less(i, j int) bool { return s[i].Less(&s[j]) }
590 662
591 // EstimateSize estimates the amount of space that this Property would consume 663 // EstimateSize estimates the amount of space that this Property would consume
592 // if it were committed as part of an entity in the real production datastore. 664 // if it were committed as part of an entity in the real production datastore.
593 // 665 //
594 // It uses https://cloud.google.com/appengine/articles/storage_breakdown?csw=1 666 // It uses https://cloud.google.com/appengine/articles/storage_breakdown?csw=1
595 // as a guide for these values. 667 // as a guide for these values.
596 func (p *Property) EstimateSize() int64 { 668 func (p *Property) EstimateSize() int64 {
597 switch p.Type() { 669 switch p.Type() {
598 case PTNull: 670 case PTNull:
599 return 1 671 return 1
600 case PTBool: 672 case PTBool:
601 return 1 + 4 673 return 1 + 4
602 case PTInt, PTTime, PTFloat: 674 case PTInt, PTTime, PTFloat:
603 return 1 + 8 675 return 1 + 8
604 case PTGeoPoint: 676 case PTGeoPoint:
605 return 1 + (8 * 2) 677 return 1 + (8 * 2)
606 case PTString: 678 case PTString:
607 » » return 1 + int64(len(p.value.(string))) 679 » » return 1 + int64(len(p.Value().(string)))
608 case PTBlobKey: 680 case PTBlobKey:
609 » » return 1 + int64(len(p.value.(blobstore.Key))) 681 » » return 1 + int64(len(p.Value().(blobstore.Key)))
610 case PTBytes: 682 case PTBytes:
611 » » return 1 + int64(len(p.value.([]byte))) 683 » » return 1 + int64(len(p.Value().([]byte)))
612 case PTKey: 684 case PTKey:
613 » » return 1 + p.value.(*Key).EstimateSize() 685 » » return 1 + p.Value().(*Key).EstimateSize()
614 } 686 }
615 panic(fmt.Errorf("Unknown property type: %s", p.Type().String())) 687 panic(fmt.Errorf("Unknown property type: %s", p.Type().String()))
616 } 688 }
617 689
618 // MetaGetter is a subinterface of PropertyLoadSaver, but is also used to 690 // MetaGetter is a subinterface of PropertyLoadSaver, but is also used to
619 // abstract the meta argument for RawInterface.GetMulti. 691 // abstract the meta argument for RawInterface.GetMulti.
620 type MetaGetter interface { 692 type MetaGetter interface {
621 // GetMeta will get information about the field which has the struct tag in 693 // GetMeta will get information about the field which has the struct tag in
622 // the form of `gae:"$<key>[,<default>]?"`. 694 // the form of `gae:"$<key>[,<default>]?"`.
623 // 695 //
(...skipping 197 matching lines...) Expand 10 before | Expand all | Expand 10 after
821 // Example: 893 // Example:
822 // pls.GetMetaDefault("foo", 100).(int64) 894 // pls.GetMetaDefault("foo", 100).(int64)
823 func GetMetaDefault(getter MetaGetter, key string, dflt interface{}) interface{} { 895 func GetMetaDefault(getter MetaGetter, key string, dflt interface{}) interface{} {
824 dflt = UpconvertUnderlyingType(dflt) 896 dflt = UpconvertUnderlyingType(dflt)
825 cur, ok := getter.GetMeta(key) 897 cur, ok := getter.GetMeta(key)
826 if !ok || (dflt != nil && reflect.TypeOf(cur) != reflect.TypeOf(dflt)) { 898 if !ok || (dflt != nil && reflect.TypeOf(cur) != reflect.TypeOf(dflt)) {
827 return dflt 899 return dflt
828 } 900 }
829 return cur 901 return cur
830 } 902 }
903
904 // byteSequence is a generic interface for an object that can be represented as
905 // a sequence of bytes. Its implementations are used internally by Property to
906 // enable zero-copy conversion and comparisons between byte sequence types.
907 type byteSequence interface {
908 Len() int
909 Get(int) byte
910 Value() interface{}
911 String() string
912 Bytes() []byte
913 FastCmp(o byteSequence) (int, bool)
914 }
915
916 func cmpByteSequence(a, b byteSequence) int {
917 if v, ok := a.FastCmp(b); ok {
918 return v
919 }
920
921 ld := a.Len() - b.Len()
922 if ld < 0 {
923 ld = -ld
924 }
925 for i := 0; i < ld; i++ {
926 av, bv := a.Get(i), b.Get(i)
927 switch {
928 case av < bv:
929 return -1
930 case av > bv:
931 return 1
932 }
933 }
934
935 return ld
936 }
937
938 // bytesByteSequence is a byteSequence implementation for a byte slice.
939 type bytesByteSequence []byte
940
941 func (s bytesByteSequence) Len() int { return len(s) }
942 func (s bytesByteSequence) Get(i int) byte { return s[i] }
943 func (s bytesByteSequence) Value() interface{} { return []byte(s) }
944 func (s bytesByteSequence) String() string { return string(s) }
945 func (s bytesByteSequence) Bytes() []byte { return []byte(s) }
946 func (s bytesByteSequence) FastCmp(o byteSequence) (int, bool) {
947 if t, ok := o.(bytesByteSequence); ok {
948 return bytes.Compare([]byte(s), []byte(t)), true
949 }
950 return 0, false
951 }
952
953 // stringByteSequence is a byteSequence implementation for a string.
954 type stringByteSequence string
955
956 func (s stringByteSequence) Len() int { return len(s) }
957 func (s stringByteSequence) Get(i int) byte { return s[i] }
958 func (s stringByteSequence) Value() interface{} { return string(s) }
959 func (s stringByteSequence) String() string { return string(s) }
960 func (s stringByteSequence) Bytes() []byte { return []byte(s) }
961 func (s stringByteSequence) FastCmp(o byteSequence) (int, bool) {
962 if t, ok := o.(stringByteSequence); ok {
963 if string(s) == string(t) {
964 return 0, true
965 }
966 if string(s) < string(t) {
967 return -1, true
968 }
969 return 0, true
970 }
971 return 0, false
972 }
OLDNEW
« no previous file with comments | « service/datastore/pls_impl.go ('k') | service/datastore/properties_test.go » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698